blob: 193b0cc1bc45b832665056cc9454930594cc533c [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
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +000044 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
45 etype* et = (etype*)type;
Tim Petersea7f75d2002-12-07 21:39:16 +000046
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +000047 Py_INCREF(et->name);
48 return et->name;
49 }
50 else {
51 s = strrchr(type->tp_name, '.');
52 if (s == NULL)
53 s = type->tp_name;
54 else
55 s++;
56 return PyString_FromString(s);
57 }
Guido van Rossumc3542212001-08-16 09:18:56 +000058}
59
Michael W. Hudson98bbc492002-11-26 14:47:27 +000060static int
61type_set_name(PyTypeObject *type, PyObject *value, void *context)
62{
63 etype* et;
64
65 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
66 PyErr_Format(PyExc_TypeError,
67 "can't set %s.__name__", type->tp_name);
68 return -1;
69 }
70 if (!value) {
71 PyErr_Format(PyExc_TypeError,
72 "can't delete %s.__name__", type->tp_name);
73 return -1;
74 }
75 if (!PyString_Check(value)) {
76 PyErr_Format(PyExc_TypeError,
77 "can only assign string to %s.__name__, not '%s'",
78 type->tp_name, value->ob_type->tp_name);
79 return -1;
80 }
Tim Petersea7f75d2002-12-07 21:39:16 +000081 if (strlen(PyString_AS_STRING(value))
Michael W. Hudson98bbc492002-11-26 14:47:27 +000082 != (size_t)PyString_GET_SIZE(value)) {
83 PyErr_Format(PyExc_ValueError,
84 "__name__ must not contain null bytes");
85 return -1;
86 }
87
88 et = (etype*)type;
89
90 Py_INCREF(value);
91
92 Py_DECREF(et->name);
93 et->name = value;
94
95 type->tp_name = PyString_AS_STRING(value);
96
97 return 0;
98}
99
Guido van Rossumc3542212001-08-16 09:18:56 +0000100static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000101type_module(PyTypeObject *type, void *context)
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000102{
Guido van Rossumc3542212001-08-16 09:18:56 +0000103 PyObject *mod;
104 char *s;
105
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +0000106 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
107 mod = PyDict_GetItemString(type->tp_dict, "__module__");
108 Py_XINCREF(mod);
Guido van Rossumc3542212001-08-16 09:18:56 +0000109 return mod;
110 }
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +0000111 else {
112 s = strrchr(type->tp_name, '.');
113 if (s != NULL)
114 return PyString_FromStringAndSize(
115 type->tp_name, (int)(s - type->tp_name));
116 return PyString_FromString("__builtin__");
117 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000118}
119
Guido van Rossum3926a632001-09-25 16:25:58 +0000120static int
121type_set_module(PyTypeObject *type, PyObject *value, void *context)
122{
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000123 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
Guido van Rossum3926a632001-09-25 16:25:58 +0000124 PyErr_Format(PyExc_TypeError,
125 "can't set %s.__module__", type->tp_name);
126 return -1;
127 }
128 if (!value) {
129 PyErr_Format(PyExc_TypeError,
130 "can't delete %s.__module__", type->tp_name);
131 return -1;
132 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000133
Guido van Rossum3926a632001-09-25 16:25:58 +0000134 return PyDict_SetItemString(type->tp_dict, "__module__", value);
135}
136
Tim Peters6d6c1a32001-08-02 04:15:00 +0000137static PyObject *
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000138type_get_bases(PyTypeObject *type, void *context)
139{
140 Py_INCREF(type->tp_bases);
141 return type->tp_bases;
142}
143
144static PyTypeObject *best_base(PyObject *);
145static int mro_internal(PyTypeObject *);
146static int compatible_for_assignment(PyTypeObject *, PyTypeObject *, char *);
147static int add_subclass(PyTypeObject*, PyTypeObject*);
148static void remove_subclass(PyTypeObject *, PyTypeObject *);
149static void update_all_slots(PyTypeObject *);
150
151static int
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000152mro_subclasses(PyTypeObject *type, PyObject* temp)
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000153{
154 PyTypeObject *subclass;
155 PyObject *ref, *subclasses, *old_mro;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000156 int i, n;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000157
158 subclasses = type->tp_subclasses;
159 if (subclasses == NULL)
160 return 0;
161 assert(PyList_Check(subclasses));
162 n = PyList_GET_SIZE(subclasses);
163 for (i = 0; i < n; i++) {
164 ref = PyList_GET_ITEM(subclasses, i);
165 assert(PyWeakref_CheckRef(ref));
166 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
167 assert(subclass != NULL);
168 if ((PyObject *)subclass == Py_None)
169 continue;
170 assert(PyType_Check(subclass));
171 old_mro = subclass->tp_mro;
172 if (mro_internal(subclass) < 0) {
173 subclass->tp_mro = old_mro;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000174 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000175 }
176 else {
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000177 PyObject* tuple;
178 tuple = Py_BuildValue("OO", subclass, old_mro);
179 if (!tuple)
180 return -1;
181 if (PyList_Append(temp, tuple) < 0)
182 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000183 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000184 if (mro_subclasses(subclass, temp) < 0)
185 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000186 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000187 return 0;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000188}
189
190static int
191type_set_bases(PyTypeObject *type, PyObject *value, void *context)
192{
193 int i, r = 0;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000194 PyObject *ob, *temp;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000195 PyTypeObject *new_base, *old_base;
196 PyObject *old_bases, *old_mro;
197
198 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
199 PyErr_Format(PyExc_TypeError,
200 "can't set %s.__bases__", type->tp_name);
201 return -1;
202 }
203 if (!value) {
204 PyErr_Format(PyExc_TypeError,
205 "can't delete %s.__bases__", type->tp_name);
206 return -1;
207 }
208 if (!PyTuple_Check(value)) {
209 PyErr_Format(PyExc_TypeError,
210 "can only assign tuple to %s.__bases__, not %s",
211 type->tp_name, value->ob_type->tp_name);
212 return -1;
213 }
214 for (i = 0; i < PyTuple_GET_SIZE(value); i++) {
215 ob = PyTuple_GET_ITEM(value, i);
216 if (!PyClass_Check(ob) && !PyType_Check(ob)) {
217 PyErr_Format(
218 PyExc_TypeError,
219 "%s.__bases__ must be tuple of old- or new-style classes, not '%s'",
220 type->tp_name, ob->ob_type->tp_name);
221 return -1;
222 }
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +0000223 if (PyType_Check(ob)) {
224 if (PyType_IsSubtype((PyTypeObject*)ob, type)) {
225 PyErr_SetString(PyExc_TypeError,
226 "a __bases__ item causes an inheritance cycle");
227 return -1;
228 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000229 }
230 }
231
232 new_base = best_base(value);
233
234 if (!new_base) {
235 return -1;
236 }
237
238 if (!compatible_for_assignment(type->tp_base, new_base, "__bases__"))
239 return -1;
240
241 Py_INCREF(new_base);
242 Py_INCREF(value);
243
244 old_bases = type->tp_bases;
245 old_base = type->tp_base;
246 old_mro = type->tp_mro;
247
248 type->tp_bases = value;
249 type->tp_base = new_base;
250
251 if (mro_internal(type) < 0) {
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000252 goto bail;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000253 }
254
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000255 temp = PyList_New(0);
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000256 if (!temp)
257 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000258
259 r = mro_subclasses(type, temp);
260
261 if (r < 0) {
262 for (i = 0; i < PyList_Size(temp); i++) {
263 PyTypeObject* cls;
264 PyObject* mro;
265 PyArg_ParseTuple(PyList_GetItem(temp, i),
266 "OO", &cls, &mro);
267 Py_DECREF(cls->tp_mro);
268 cls->tp_mro = mro;
269 Py_INCREF(cls->tp_mro);
270 }
271 Py_DECREF(temp);
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000272 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000273 }
274
275 Py_DECREF(temp);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000276
277 /* any base that was in __bases__ but now isn't, we
278 need to remove |type| from it's tp_subclasses.
279 conversely, any class now in __bases__ that wasn't
280 needs to have |type| added to it's subclasses. */
281
282 /* for now, sod that: just remove from all old_bases,
283 add to all new_bases */
284
285 for (i = PyTuple_GET_SIZE(old_bases) - 1; i >= 0; i--) {
286 ob = PyTuple_GET_ITEM(old_bases, i);
287 if (PyType_Check(ob)) {
288 remove_subclass(
289 (PyTypeObject*)ob, type);
290 }
291 }
292
293 for (i = PyTuple_GET_SIZE(value) - 1; i >= 0; i--) {
294 ob = PyTuple_GET_ITEM(value, i);
295 if (PyType_Check(ob)) {
296 if (add_subclass((PyTypeObject*)ob, type) < 0)
297 r = -1;
298 }
299 }
300
301 update_all_slots(type);
302
303 Py_DECREF(old_bases);
304 Py_DECREF(old_base);
305 Py_DECREF(old_mro);
306
307 return r;
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000308
309 bail:
310 type->tp_bases = old_bases;
311 type->tp_base = old_base;
312 type->tp_mro = old_mro;
Tim Petersea7f75d2002-12-07 21:39:16 +0000313
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000314 Py_DECREF(value);
315 Py_DECREF(new_base);
Tim Petersea7f75d2002-12-07 21:39:16 +0000316
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000317 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000318}
319
320static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000321type_dict(PyTypeObject *type, void *context)
322{
323 if (type->tp_dict == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000324 Py_INCREF(Py_None);
325 return Py_None;
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000326 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000327 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000328}
329
Tim Peters24008312002-03-17 18:56:20 +0000330static PyObject *
331type_get_doc(PyTypeObject *type, void *context)
332{
333 PyObject *result;
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000334 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL)
Tim Peters24008312002-03-17 18:56:20 +0000335 return PyString_FromString(type->tp_doc);
Tim Peters24008312002-03-17 18:56:20 +0000336 result = PyDict_GetItemString(type->tp_dict, "__doc__");
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000337 if (result == NULL) {
338 result = Py_None;
339 Py_INCREF(result);
340 }
341 else if (result->ob_type->tp_descr_get) {
Tim Peters2b858972002-04-18 04:12:28 +0000342 result = result->ob_type->tp_descr_get(result, NULL,
343 (PyObject *)type);
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000344 }
345 else {
346 Py_INCREF(result);
347 }
Tim Peters24008312002-03-17 18:56:20 +0000348 return result;
349}
350
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000351static PyGetSetDef type_getsets[] = {
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000352 {"__name__", (getter)type_name, (setter)type_set_name, NULL},
353 {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL},
Guido van Rossum3926a632001-09-25 16:25:58 +0000354 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000355 {"__dict__", (getter)type_dict, NULL, NULL},
Tim Peters24008312002-03-17 18:56:20 +0000356 {"__doc__", (getter)type_get_doc, NULL, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000357 {0}
358};
359
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000360static int
361type_compare(PyObject *v, PyObject *w)
362{
363 /* This is called with type objects only. So we
364 can just compare the addresses. */
365 Py_uintptr_t vv = (Py_uintptr_t)v;
366 Py_uintptr_t ww = (Py_uintptr_t)w;
367 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
368}
369
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000370static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000371type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000372{
Barry Warsaw7ce36942001-08-24 18:34:26 +0000373 PyObject *mod, *name, *rtn;
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000374 char *kind;
Guido van Rossumc3542212001-08-16 09:18:56 +0000375
376 mod = type_module(type, NULL);
377 if (mod == NULL)
378 PyErr_Clear();
379 else if (!PyString_Check(mod)) {
380 Py_DECREF(mod);
381 mod = NULL;
382 }
383 name = type_name(type, NULL);
384 if (name == NULL)
385 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000386
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000387 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
388 kind = "class";
389 else
390 kind = "type";
391
Barry Warsaw7ce36942001-08-24 18:34:26 +0000392 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__")) {
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000393 rtn = PyString_FromFormat("<%s '%s.%s'>",
394 kind,
Barry Warsaw7ce36942001-08-24 18:34:26 +0000395 PyString_AS_STRING(mod),
396 PyString_AS_STRING(name));
397 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000398 else
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000399 rtn = PyString_FromFormat("<%s '%s'>", kind, type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000400
Guido van Rossumc3542212001-08-16 09:18:56 +0000401 Py_XDECREF(mod);
402 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000403 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000404}
405
Tim Peters6d6c1a32001-08-02 04:15:00 +0000406static PyObject *
407type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
408{
409 PyObject *obj;
410
411 if (type->tp_new == NULL) {
412 PyErr_Format(PyExc_TypeError,
413 "cannot create '%.100s' instances",
414 type->tp_name);
415 return NULL;
416 }
417
Tim Peters3f996e72001-09-13 19:18:27 +0000418 obj = type->tp_new(type, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000419 if (obj != NULL) {
Guido van Rossumf76de622001-10-18 15:49:21 +0000420 /* Ugly exception: when the call was type(something),
421 don't call tp_init on the result. */
422 if (type == &PyType_Type &&
423 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
424 (kwds == NULL ||
425 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
426 return obj;
Guido van Rossum8ace1ab2002-04-06 01:05:01 +0000427 /* If the returned object is not an instance of type,
428 it won't be initialized. */
429 if (!PyType_IsSubtype(obj->ob_type, type))
430 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000431 type = obj->ob_type;
Jeremy Hylton719841e2002-07-16 19:39:38 +0000432 if (PyType_HasFeature(type, Py_TPFLAGS_HAVE_CLASS) &&
433 type->tp_init != NULL &&
Tim Peters6d6c1a32001-08-02 04:15:00 +0000434 type->tp_init(obj, args, kwds) < 0) {
435 Py_DECREF(obj);
436 obj = NULL;
437 }
438 }
439 return obj;
440}
441
442PyObject *
443PyType_GenericAlloc(PyTypeObject *type, int nitems)
444{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000445 PyObject *obj;
Tim Petersf2a67da2001-10-07 03:54:51 +0000446 const size_t size = _PyObject_VAR_SIZE(type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000447
448 if (PyType_IS_GC(type))
Neil Schemenauer09a2ae52002-04-12 03:06:53 +0000449 obj = _PyObject_GC_Malloc(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000450 else
Neil Schemenauerc806c882001-08-29 23:54:54 +0000451 obj = PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000452
Neil Schemenauerc806c882001-08-29 23:54:54 +0000453 if (obj == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000454 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000455
Neil Schemenauerc806c882001-08-29 23:54:54 +0000456 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000457
Tim Peters6d6c1a32001-08-02 04:15:00 +0000458 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
459 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000460
Tim Peters6d6c1a32001-08-02 04:15:00 +0000461 if (type->tp_itemsize == 0)
462 PyObject_INIT(obj, type);
463 else
464 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000465
Tim Peters6d6c1a32001-08-02 04:15:00 +0000466 if (PyType_IS_GC(type))
Neil Schemenauerc806c882001-08-29 23:54:54 +0000467 _PyObject_GC_TRACK(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000468 return obj;
469}
470
471PyObject *
472PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
473{
474 return type->tp_alloc(type, 0);
475}
476
Guido van Rossum9475a232001-10-05 20:51:39 +0000477/* Helpers for subtyping */
478
479static int
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000480traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
481{
482 int i, n;
483 PyMemberDef *mp;
484
485 n = type->ob_size;
486 mp = ((etype *)type)->members;
487 for (i = 0; i < n; i++, mp++) {
488 if (mp->type == T_OBJECT_EX) {
489 char *addr = (char *)self + mp->offset;
490 PyObject *obj = *(PyObject **)addr;
491 if (obj != NULL) {
492 int err = visit(obj, arg);
493 if (err)
494 return err;
495 }
496 }
497 }
498 return 0;
499}
500
501static int
Guido van Rossum9475a232001-10-05 20:51:39 +0000502subtype_traverse(PyObject *self, visitproc visit, void *arg)
503{
504 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000505 traverseproc basetraverse;
Guido van Rossum9475a232001-10-05 20:51:39 +0000506
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000507 /* Find the nearest base with a different tp_traverse,
508 and traverse slots while we're at it */
Guido van Rossum9475a232001-10-05 20:51:39 +0000509 type = self->ob_type;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000510 base = type;
511 while ((basetraverse = base->tp_traverse) == subtype_traverse) {
512 if (base->ob_size) {
513 int err = traverse_slots(base, self, visit, arg);
514 if (err)
515 return err;
516 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000517 base = base->tp_base;
518 assert(base);
519 }
520
521 if (type->tp_dictoffset != base->tp_dictoffset) {
522 PyObject **dictptr = _PyObject_GetDictPtr(self);
523 if (dictptr && *dictptr) {
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000524 int err = visit(*dictptr, arg);
Guido van Rossum9475a232001-10-05 20:51:39 +0000525 if (err)
526 return err;
527 }
528 }
529
Guido van Rossuma3862092002-06-10 15:24:42 +0000530 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
531 /* For a heaptype, the instances count as references
532 to the type. Traverse the type so the collector
533 can find cycles involving this link. */
534 int err = visit((PyObject *)type, arg);
535 if (err)
536 return err;
537 }
538
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000539 if (basetraverse)
540 return basetraverse(self, visit, arg);
541 return 0;
542}
543
544static void
545clear_slots(PyTypeObject *type, PyObject *self)
546{
547 int i, n;
548 PyMemberDef *mp;
549
550 n = type->ob_size;
551 mp = ((etype *)type)->members;
552 for (i = 0; i < n; i++, mp++) {
553 if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
554 char *addr = (char *)self + mp->offset;
555 PyObject *obj = *(PyObject **)addr;
556 if (obj != NULL) {
557 Py_DECREF(obj);
558 *(PyObject **)addr = NULL;
559 }
560 }
561 }
562}
563
564static int
565subtype_clear(PyObject *self)
566{
567 PyTypeObject *type, *base;
568 inquiry baseclear;
569
570 /* Find the nearest base with a different tp_clear
571 and clear slots while we're at it */
572 type = self->ob_type;
573 base = type;
574 while ((baseclear = base->tp_clear) == subtype_clear) {
575 if (base->ob_size)
576 clear_slots(base, self);
577 base = base->tp_base;
578 assert(base);
579 }
580
Guido van Rossuma3862092002-06-10 15:24:42 +0000581 /* There's no need to clear the instance dict (if any);
582 the collector will call its tp_clear handler. */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000583
584 if (baseclear)
585 return baseclear(self);
Guido van Rossum9475a232001-10-05 20:51:39 +0000586 return 0;
587}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000588
589static void
590subtype_dealloc(PyObject *self)
591{
Guido van Rossum14227b42001-12-06 02:35:58 +0000592 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000593 destructor basedealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000594
Guido van Rossum22b13872002-08-06 21:41:44 +0000595 /* Extract the type; we expect it to be a heap type */
596 type = self->ob_type;
597 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000598
Guido van Rossum22b13872002-08-06 21:41:44 +0000599 /* Test whether the type has GC exactly once */
600
601 if (!PyType_IS_GC(type)) {
602 /* It's really rare to find a dynamic type that doesn't have
603 GC; it can only happen when deriving from 'object' and not
604 adding any slots or instance variables. This allows
605 certain simplifications: there's no need to call
606 clear_slots(), or DECREF the dict, or clear weakrefs. */
607
608 /* Maybe call finalizer; exit early if resurrected */
Guido van Rossumfebd61d2002-08-08 20:55:20 +0000609 if (type->tp_del) {
610 type->tp_del(self);
611 if (self->ob_refcnt > 0)
612 return;
613 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000614
615 /* Find the nearest base with a different tp_dealloc */
616 base = type;
617 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
618 assert(base->ob_size == 0);
619 base = base->tp_base;
620 assert(base);
621 }
622
623 /* Call the base tp_dealloc() */
624 assert(basedealloc);
625 basedealloc(self);
626
627 /* Can't reference self beyond this point */
628 Py_DECREF(type);
629
630 /* Done */
631 return;
632 }
633
634 /* We get here only if the type has GC */
635
636 /* UnTrack and re-Track around the trashcan macro, alas */
Guido van Rossum0906e072002-08-07 20:42:09 +0000637 PyObject_GC_UnTrack(self);
Guido van Rossum22b13872002-08-06 21:41:44 +0000638 Py_TRASHCAN_SAFE_BEGIN(self);
639 _PyObject_GC_TRACK(self); /* We'll untrack for real later */
640
641 /* Maybe call finalizer; exit early if resurrected */
Guido van Rossumfebd61d2002-08-08 20:55:20 +0000642 if (type->tp_del) {
643 type->tp_del(self);
644 if (self->ob_refcnt > 0)
645 goto endlabel;
646 }
Guido van Rossum7ad2d1e2001-10-29 22:11:00 +0000647
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000648 /* Find the nearest base with a different tp_dealloc
649 and clear slots while we're at it */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000650 base = type;
651 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
652 if (base->ob_size)
653 clear_slots(base, self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000654 base = base->tp_base;
655 assert(base);
Guido van Rossum14227b42001-12-06 02:35:58 +0000656 }
657
Tim Peters6d6c1a32001-08-02 04:15:00 +0000658 /* If we added a dict, DECREF it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000659 if (type->tp_dictoffset && !base->tp_dictoffset) {
660 PyObject **dictptr = _PyObject_GetDictPtr(self);
661 if (dictptr != NULL) {
662 PyObject *dict = *dictptr;
663 if (dict != NULL) {
664 Py_DECREF(dict);
665 *dictptr = NULL;
666 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000667 }
668 }
669
Guido van Rossum9676b222001-08-17 20:32:36 +0000670 /* If we added weaklist, we clear it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000671 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
Guido van Rossum9676b222001-08-17 20:32:36 +0000672 PyObject_ClearWeakRefs(self);
673
Tim Peters6d6c1a32001-08-02 04:15:00 +0000674 /* Finalize GC if the base doesn't do GC and we do */
Guido van Rossum22b13872002-08-06 21:41:44 +0000675 if (!PyType_IS_GC(base))
Guido van Rossum048eb752001-10-02 21:24:57 +0000676 _PyObject_GC_UNTRACK(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000677
678 /* Call the base tp_dealloc() */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000679 assert(basedealloc);
680 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000681
682 /* Can't reference self beyond this point */
Guido van Rossum22b13872002-08-06 21:41:44 +0000683 Py_DECREF(type);
684
Guido van Rossum0906e072002-08-07 20:42:09 +0000685 endlabel:
Guido van Rossum22b13872002-08-06 21:41:44 +0000686 Py_TRASHCAN_SAFE_END(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000687}
688
Jeremy Hylton938ace62002-07-17 16:30:39 +0000689static PyTypeObject *solid_base(PyTypeObject *type);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000690
Tim Peters6d6c1a32001-08-02 04:15:00 +0000691/* type test with subclassing support */
692
693int
694PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
695{
696 PyObject *mro;
697
Guido van Rossum9478d072001-09-07 18:52:13 +0000698 if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
699 return b == a || b == &PyBaseObject_Type;
700
Tim Peters6d6c1a32001-08-02 04:15:00 +0000701 mro = a->tp_mro;
702 if (mro != NULL) {
703 /* Deal with multiple inheritance without recursion
704 by walking the MRO tuple */
705 int i, n;
706 assert(PyTuple_Check(mro));
707 n = PyTuple_GET_SIZE(mro);
708 for (i = 0; i < n; i++) {
709 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
710 return 1;
711 }
712 return 0;
713 }
714 else {
715 /* a is not completely initilized yet; follow tp_base */
716 do {
717 if (a == b)
718 return 1;
719 a = a->tp_base;
720 } while (a != NULL);
721 return b == &PyBaseObject_Type;
722 }
723}
724
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000725/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +0000726 without looking in the instance dictionary
727 (so we can't use PyObject_GetAttr) but still binding
728 it to the instance. The arguments are the object,
729 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000730 static variable used to cache the interned Python string.
731
732 Two variants:
733
734 - lookup_maybe() returns NULL without raising an exception
735 when the _PyType_Lookup() call fails;
736
737 - lookup_method() always raises an exception upon errors.
738*/
Guido van Rossum60718732001-08-28 17:47:51 +0000739
740static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000741lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +0000742{
743 PyObject *res;
744
745 if (*attrobj == NULL) {
746 *attrobj = PyString_InternFromString(attrstr);
747 if (*attrobj == NULL)
748 return NULL;
749 }
750 res = _PyType_Lookup(self->ob_type, *attrobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000751 if (res != NULL) {
Guido van Rossum60718732001-08-28 17:47:51 +0000752 descrgetfunc f;
753 if ((f = res->ob_type->tp_descr_get) == NULL)
754 Py_INCREF(res);
755 else
756 res = f(res, self, (PyObject *)(self->ob_type));
757 }
758 return res;
759}
760
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000761static PyObject *
762lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
763{
764 PyObject *res = lookup_maybe(self, attrstr, attrobj);
765 if (res == NULL && !PyErr_Occurred())
766 PyErr_SetObject(PyExc_AttributeError, *attrobj);
767 return res;
768}
769
Guido van Rossum2730b132001-08-28 18:22:14 +0000770/* A variation of PyObject_CallMethod that uses lookup_method()
771 instead of PyObject_GetAttrString(). This uses the same convention
772 as lookup_method to cache the interned name string object. */
773
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000774static PyObject *
Guido van Rossum2730b132001-08-28 18:22:14 +0000775call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
776{
777 va_list va;
778 PyObject *args, *func = 0, *retval;
Guido van Rossum2730b132001-08-28 18:22:14 +0000779 va_start(va, format);
780
Guido van Rossumda21c012001-10-03 00:50:18 +0000781 func = lookup_maybe(o, name, nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000782 if (func == NULL) {
783 va_end(va);
784 if (!PyErr_Occurred())
Guido van Rossumda21c012001-10-03 00:50:18 +0000785 PyErr_SetObject(PyExc_AttributeError, *nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000786 return NULL;
787 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000788
789 if (format && *format)
790 args = Py_VaBuildValue(format, va);
791 else
792 args = PyTuple_New(0);
793
794 va_end(va);
795
796 if (args == NULL)
797 return NULL;
798
799 assert(PyTuple_Check(args));
800 retval = PyObject_Call(func, args, NULL);
801
802 Py_DECREF(args);
803 Py_DECREF(func);
804
805 return retval;
806}
807
808/* Clone of call_method() that returns NotImplemented when the lookup fails. */
809
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000810static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000811call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
812{
813 va_list va;
814 PyObject *args, *func = 0, *retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000815 va_start(va, format);
816
Guido van Rossumda21c012001-10-03 00:50:18 +0000817 func = lookup_maybe(o, name, nameobj);
Guido van Rossum2730b132001-08-28 18:22:14 +0000818 if (func == NULL) {
819 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000820 if (!PyErr_Occurred()) {
821 Py_INCREF(Py_NotImplemented);
822 return Py_NotImplemented;
823 }
Guido van Rossum717ce002001-09-14 16:58:08 +0000824 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +0000825 }
826
827 if (format && *format)
828 args = Py_VaBuildValue(format, va);
829 else
830 args = PyTuple_New(0);
831
832 va_end(va);
833
Guido van Rossum717ce002001-09-14 16:58:08 +0000834 if (args == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +0000835 return NULL;
836
Guido van Rossum717ce002001-09-14 16:58:08 +0000837 assert(PyTuple_Check(args));
838 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +0000839
840 Py_DECREF(args);
841 Py_DECREF(func);
842
843 return retval;
844}
845
Tim Petersa91e9642001-11-14 23:32:33 +0000846static int
847fill_classic_mro(PyObject *mro, PyObject *cls)
848{
849 PyObject *bases, *base;
850 int i, n;
851
852 assert(PyList_Check(mro));
853 assert(PyClass_Check(cls));
854 i = PySequence_Contains(mro, cls);
855 if (i < 0)
856 return -1;
857 if (!i) {
858 if (PyList_Append(mro, cls) < 0)
859 return -1;
860 }
861 bases = ((PyClassObject *)cls)->cl_bases;
862 assert(bases && PyTuple_Check(bases));
863 n = PyTuple_GET_SIZE(bases);
864 for (i = 0; i < n; i++) {
865 base = PyTuple_GET_ITEM(bases, i);
866 if (fill_classic_mro(mro, base) < 0)
867 return -1;
868 }
869 return 0;
870}
871
872static PyObject *
873classic_mro(PyObject *cls)
874{
875 PyObject *mro;
876
877 assert(PyClass_Check(cls));
878 mro = PyList_New(0);
879 if (mro != NULL) {
880 if (fill_classic_mro(mro, cls) == 0)
881 return mro;
882 Py_DECREF(mro);
883 }
884 return NULL;
885}
886
Tim Petersea7f75d2002-12-07 21:39:16 +0000887/*
Guido van Rossum1f121312002-11-14 19:49:16 +0000888 Method resolution order algorithm C3 described in
889 "A Monotonic Superclass Linearization for Dylan",
890 by Kim Barrett, Bob Cassel, Paul Haahr,
Tim Petersea7f75d2002-12-07 21:39:16 +0000891 David A. Moon, Keith Playford, and P. Tucker Withington.
Guido van Rossum1f121312002-11-14 19:49:16 +0000892 (OOPSLA 1996)
893
Guido van Rossum98f33732002-11-25 21:36:54 +0000894 Some notes about the rules implied by C3:
895
Tim Petersea7f75d2002-12-07 21:39:16 +0000896 No duplicate bases.
Guido van Rossum98f33732002-11-25 21:36:54 +0000897 It isn't legal to repeat a class in a list of base classes.
898
899 The next three properties are the 3 constraints in "C3".
900
Tim Petersea7f75d2002-12-07 21:39:16 +0000901 Local precendece order.
Guido van Rossum98f33732002-11-25 21:36:54 +0000902 If A precedes B in C's MRO, then A will precede B in the MRO of all
903 subclasses of C.
904
905 Monotonicity.
906 The MRO of a class must be an extension without reordering of the
907 MRO of each of its superclasses.
908
909 Extended Precedence Graph (EPG).
910 Linearization is consistent if there is a path in the EPG from
911 each class to all its successors in the linearization. See
912 the paper for definition of EPG.
Guido van Rossum1f121312002-11-14 19:49:16 +0000913 */
914
Tim Petersea7f75d2002-12-07 21:39:16 +0000915static int
Guido van Rossum1f121312002-11-14 19:49:16 +0000916tail_contains(PyObject *list, int whence, PyObject *o) {
917 int j, size;
918 size = PyList_GET_SIZE(list);
919
920 for (j = whence+1; j < size; j++) {
921 if (PyList_GET_ITEM(list, j) == o)
922 return 1;
923 }
924 return 0;
925}
926
Guido van Rossum98f33732002-11-25 21:36:54 +0000927static PyObject *
928class_name(PyObject *cls)
929{
930 PyObject *name = PyObject_GetAttrString(cls, "__name__");
931 if (name == NULL) {
932 PyErr_Clear();
933 Py_XDECREF(name);
934 name = PyObject_Repr(cls);
935 }
936 if (name == NULL)
937 return NULL;
938 if (!PyString_Check(name)) {
939 Py_DECREF(name);
940 return NULL;
941 }
942 return name;
943}
944
945static int
946check_duplicates(PyObject *list)
947{
948 int i, j, n;
949 /* Let's use a quadratic time algorithm,
950 assuming that the bases lists is short.
951 */
952 n = PyList_GET_SIZE(list);
953 for (i = 0; i < n; i++) {
954 PyObject *o = PyList_GET_ITEM(list, i);
955 for (j = i + 1; j < n; j++) {
956 if (PyList_GET_ITEM(list, j) == o) {
957 o = class_name(o);
958 PyErr_Format(PyExc_TypeError,
959 "duplicate base class %s",
960 o ? PyString_AS_STRING(o) : "?");
961 Py_XDECREF(o);
962 return -1;
963 }
964 }
965 }
966 return 0;
967}
968
969/* Raise a TypeError for an MRO order disagreement.
970
971 It's hard to produce a good error message. In the absence of better
972 insight into error reporting, report the classes that were candidates
973 to be put next into the MRO. There is some conflict between the
974 order in which they should be put in the MRO, but it's hard to
975 diagnose what constraint can't be satisfied.
976*/
977
978static void
979set_mro_error(PyObject *to_merge, int *remain)
980{
981 int i, n, off, to_merge_size;
982 char buf[1000];
983 PyObject *k, *v;
984 PyObject *set = PyDict_New();
985
986 to_merge_size = PyList_GET_SIZE(to_merge);
987 for (i = 0; i < to_merge_size; i++) {
988 PyObject *L = PyList_GET_ITEM(to_merge, i);
989 if (remain[i] < PyList_GET_SIZE(L)) {
990 PyObject *c = PyList_GET_ITEM(L, remain[i]);
991 if (PyDict_SetItem(set, c, Py_None) < 0)
992 return;
993 }
994 }
995 n = PyDict_Size(set);
996
997 off = PyOS_snprintf(buf, sizeof(buf), "MRO conflict among bases");
998 i = 0;
999 while (PyDict_Next(set, &i, &k, &v) && off < sizeof(buf)) {
1000 PyObject *name = class_name(k);
1001 off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s",
1002 name ? PyString_AS_STRING(name) : "?");
1003 Py_XDECREF(name);
1004 if (--n && off+1 < sizeof(buf)) {
1005 buf[off++] = ',';
1006 buf[off] = '\0';
1007 }
1008 }
1009 PyErr_SetString(PyExc_TypeError, buf);
1010 Py_DECREF(set);
1011}
1012
Tim Petersea7f75d2002-12-07 21:39:16 +00001013static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001014pmerge(PyObject *acc, PyObject* to_merge) {
1015 int i, j, to_merge_size;
1016 int *remain;
1017 int ok, empty_cnt;
Tim Petersea7f75d2002-12-07 21:39:16 +00001018
Guido van Rossum1f121312002-11-14 19:49:16 +00001019 to_merge_size = PyList_GET_SIZE(to_merge);
1020
Guido van Rossum98f33732002-11-25 21:36:54 +00001021 /* remain stores an index into each sublist of to_merge.
1022 remain[i] is the index of the next base in to_merge[i]
1023 that is not included in acc.
1024 */
Guido van Rossum1f121312002-11-14 19:49:16 +00001025 remain = PyMem_MALLOC(SIZEOF_INT*to_merge_size);
1026 if (remain == NULL)
1027 return -1;
1028 for (i = 0; i < to_merge_size; i++)
1029 remain[i] = 0;
1030
1031 again:
1032 empty_cnt = 0;
1033 for (i = 0; i < to_merge_size; i++) {
1034 PyObject *candidate;
Tim Petersea7f75d2002-12-07 21:39:16 +00001035
Guido van Rossum1f121312002-11-14 19:49:16 +00001036 PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
1037
1038 if (remain[i] >= PyList_GET_SIZE(cur_list)) {
1039 empty_cnt++;
1040 continue;
1041 }
1042
Guido van Rossum98f33732002-11-25 21:36:54 +00001043 /* Choose next candidate for MRO.
1044
1045 The input sequences alone can determine the choice.
1046 If not, choose the class which appears in the MRO
1047 of the earliest direct superclass of the new class.
1048 */
1049
Guido van Rossum1f121312002-11-14 19:49:16 +00001050 candidate = PyList_GET_ITEM(cur_list, remain[i]);
1051 for (j = 0; j < to_merge_size; j++) {
1052 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum98f33732002-11-25 21:36:54 +00001053 if (tail_contains(j_lst, remain[j], candidate)) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001054 goto skip; /* continue outer loop */
Guido van Rossum98f33732002-11-25 21:36:54 +00001055 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001056 }
1057 ok = PyList_Append(acc, candidate);
1058 if (ok < 0) {
1059 PyMem_Free(remain);
1060 return -1;
1061 }
1062 for (j = 0; j < to_merge_size; j++) {
1063 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
1064 if (PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
1065 remain[j]++;
1066 }
1067 }
1068 goto again;
Tim Peters9a6b8d82002-11-14 23:22:33 +00001069 skip: ;
Guido van Rossum1f121312002-11-14 19:49:16 +00001070 }
1071
Guido van Rossum98f33732002-11-25 21:36:54 +00001072 if (empty_cnt == to_merge_size) {
1073 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001074 return 0;
Guido van Rossum98f33732002-11-25 21:36:54 +00001075 }
1076 set_mro_error(to_merge, remain);
1077 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001078 return -1;
1079}
1080
Tim Peters6d6c1a32001-08-02 04:15:00 +00001081static PyObject *
1082mro_implementation(PyTypeObject *type)
1083{
1084 int i, n, ok;
1085 PyObject *bases, *result;
Guido van Rossum1f121312002-11-14 19:49:16 +00001086 PyObject *to_merge, *bases_aslist;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001087
Guido van Rossum63517572002-06-18 16:44:57 +00001088 if(type->tp_dict == NULL) {
1089 if(PyType_Ready(type) < 0)
1090 return NULL;
1091 }
1092
Guido van Rossum98f33732002-11-25 21:36:54 +00001093 /* Find a superclass linearization that honors the constraints
1094 of the explicit lists of bases and the constraints implied by
Tim Petersea7f75d2002-12-07 21:39:16 +00001095 each base class.
Guido van Rossum98f33732002-11-25 21:36:54 +00001096
1097 to_merge is a list of lists, where each list is a superclass
1098 linearization implied by a base class. The last element of
1099 to_merge is the declared list of bases.
1100 */
1101
Tim Peters6d6c1a32001-08-02 04:15:00 +00001102 bases = type->tp_bases;
1103 n = PyTuple_GET_SIZE(bases);
Guido van Rossum1f121312002-11-14 19:49:16 +00001104
1105 to_merge = PyList_New(n+1);
1106 if (to_merge == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001107 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001108
Tim Peters6d6c1a32001-08-02 04:15:00 +00001109 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001110 PyObject *base = PyTuple_GET_ITEM(bases, i);
1111 PyObject *parentMRO;
1112 if (PyType_Check(base))
1113 parentMRO = PySequence_List(
1114 ((PyTypeObject*)base)->tp_mro);
1115 else
1116 parentMRO = classic_mro(base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001117 if (parentMRO == NULL) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001118 Py_DECREF(to_merge);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001119 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001120 }
1121
1122 PyList_SET_ITEM(to_merge, i, parentMRO);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001123 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001124
1125 bases_aslist = PySequence_List(bases);
1126 if (bases_aslist == NULL) {
1127 Py_DECREF(to_merge);
1128 return NULL;
1129 }
Guido van Rossum98f33732002-11-25 21:36:54 +00001130 /* This is just a basic sanity check. */
1131 if (check_duplicates(bases_aslist) < 0) {
1132 Py_DECREF(to_merge);
1133 Py_DECREF(bases_aslist);
1134 return NULL;
1135 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001136 PyList_SET_ITEM(to_merge, n, bases_aslist);
1137
1138 result = Py_BuildValue("[O]", (PyObject *)type);
1139 if (result == NULL) {
1140 Py_DECREF(to_merge);
1141 return NULL;
1142 }
1143
1144 ok = pmerge(result, to_merge);
1145 Py_DECREF(to_merge);
1146 if (ok < 0) {
1147 Py_DECREF(result);
1148 return NULL;
1149 }
1150
Tim Peters6d6c1a32001-08-02 04:15:00 +00001151 return result;
1152}
1153
1154static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001155mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001156{
1157 PyTypeObject *type = (PyTypeObject *)self;
1158
Tim Peters6d6c1a32001-08-02 04:15:00 +00001159 return mro_implementation(type);
1160}
1161
1162static int
1163mro_internal(PyTypeObject *type)
1164{
1165 PyObject *mro, *result, *tuple;
1166
1167 if (type->ob_type == &PyType_Type) {
1168 result = mro_implementation(type);
1169 }
1170 else {
Guido van Rossum60718732001-08-28 17:47:51 +00001171 static PyObject *mro_str;
1172 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001173 if (mro == NULL)
1174 return -1;
1175 result = PyObject_CallObject(mro, NULL);
1176 Py_DECREF(mro);
1177 }
1178 if (result == NULL)
1179 return -1;
1180 tuple = PySequence_Tuple(result);
1181 Py_DECREF(result);
1182 type->tp_mro = tuple;
1183 return 0;
1184}
1185
1186
1187/* Calculate the best base amongst multiple base classes.
1188 This is the first one that's on the path to the "solid base". */
1189
1190static PyTypeObject *
1191best_base(PyObject *bases)
1192{
1193 int i, n;
1194 PyTypeObject *base, *winner, *candidate, *base_i;
Tim Petersa91e9642001-11-14 23:32:33 +00001195 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001196
1197 assert(PyTuple_Check(bases));
1198 n = PyTuple_GET_SIZE(bases);
1199 assert(n > 0);
Tim Petersa91e9642001-11-14 23:32:33 +00001200 base = NULL;
1201 winner = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001202 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001203 base_proto = PyTuple_GET_ITEM(bases, i);
1204 if (PyClass_Check(base_proto))
1205 continue;
1206 if (!PyType_Check(base_proto)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001207 PyErr_SetString(
1208 PyExc_TypeError,
1209 "bases must be types");
1210 return NULL;
1211 }
Tim Petersa91e9642001-11-14 23:32:33 +00001212 base_i = (PyTypeObject *)base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001213 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001214 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001215 return NULL;
1216 }
1217 candidate = solid_base(base_i);
Tim Petersa91e9642001-11-14 23:32:33 +00001218 if (winner == NULL) {
1219 winner = candidate;
1220 base = base_i;
1221 }
1222 else if (PyType_IsSubtype(winner, candidate))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001223 ;
1224 else if (PyType_IsSubtype(candidate, winner)) {
1225 winner = candidate;
1226 base = base_i;
1227 }
1228 else {
1229 PyErr_SetString(
1230 PyExc_TypeError,
1231 "multiple bases have "
1232 "instance lay-out conflict");
1233 return NULL;
1234 }
1235 }
Guido van Rossume54616c2001-12-14 04:19:56 +00001236 if (base == NULL)
1237 PyErr_SetString(PyExc_TypeError,
1238 "a new-style class can't have only classic bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001239 return base;
1240}
1241
1242static int
1243extra_ivars(PyTypeObject *type, PyTypeObject *base)
1244{
Neil Schemenauerc806c882001-08-29 23:54:54 +00001245 size_t t_size = type->tp_basicsize;
1246 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001247
Guido van Rossum9676b222001-08-17 20:32:36 +00001248 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001249 if (type->tp_itemsize || base->tp_itemsize) {
1250 /* If itemsize is involved, stricter rules */
1251 return t_size != b_size ||
1252 type->tp_itemsize != base->tp_itemsize;
1253 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001254 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
1255 type->tp_weaklistoffset + sizeof(PyObject *) == t_size)
1256 t_size -= sizeof(PyObject *);
1257 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
1258 type->tp_dictoffset + sizeof(PyObject *) == t_size)
1259 t_size -= sizeof(PyObject *);
1260
1261 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001262}
1263
1264static PyTypeObject *
1265solid_base(PyTypeObject *type)
1266{
1267 PyTypeObject *base;
1268
1269 if (type->tp_base)
1270 base = solid_base(type->tp_base);
1271 else
1272 base = &PyBaseObject_Type;
1273 if (extra_ivars(type, base))
1274 return type;
1275 else
1276 return base;
1277}
1278
Jeremy Hylton938ace62002-07-17 16:30:39 +00001279static void object_dealloc(PyObject *);
1280static int object_init(PyObject *, PyObject *, PyObject *);
1281static int update_slot(PyTypeObject *, PyObject *);
1282static void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001283
1284static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001285subtype_dict(PyObject *obj, void *context)
1286{
1287 PyObject **dictptr = _PyObject_GetDictPtr(obj);
1288 PyObject *dict;
1289
1290 if (dictptr == NULL) {
1291 PyErr_SetString(PyExc_AttributeError,
1292 "This object has no __dict__");
1293 return NULL;
1294 }
1295 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +00001296 if (dict == NULL)
1297 *dictptr = dict = PyDict_New();
1298 Py_XINCREF(dict);
1299 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001300}
1301
Guido van Rossum6661be32001-10-26 04:26:12 +00001302static int
1303subtype_setdict(PyObject *obj, PyObject *value, void *context)
1304{
1305 PyObject **dictptr = _PyObject_GetDictPtr(obj);
1306 PyObject *dict;
1307
1308 if (dictptr == NULL) {
1309 PyErr_SetString(PyExc_AttributeError,
1310 "This object has no __dict__");
1311 return -1;
1312 }
Guido van Rossumd331cb52001-12-05 19:46:42 +00001313 if (value != NULL && !PyDict_Check(value)) {
Guido van Rossum6661be32001-10-26 04:26:12 +00001314 PyErr_SetString(PyExc_TypeError,
1315 "__dict__ must be set to a dictionary");
1316 return -1;
1317 }
1318 dict = *dictptr;
Guido van Rossumd331cb52001-12-05 19:46:42 +00001319 Py_XINCREF(value);
Guido van Rossum6661be32001-10-26 04:26:12 +00001320 *dictptr = value;
1321 Py_XDECREF(dict);
1322 return 0;
1323}
1324
Guido van Rossumad47da02002-08-12 19:05:44 +00001325static PyObject *
1326subtype_getweakref(PyObject *obj, void *context)
1327{
1328 PyObject **weaklistptr;
1329 PyObject *result;
1330
1331 if (obj->ob_type->tp_weaklistoffset == 0) {
1332 PyErr_SetString(PyExc_AttributeError,
1333 "This object has no __weaklist__");
1334 return NULL;
1335 }
1336 assert(obj->ob_type->tp_weaklistoffset > 0);
1337 assert(obj->ob_type->tp_weaklistoffset + sizeof(PyObject *) <=
Guido van Rossum3747a0f2002-08-12 19:25:08 +00001338 (size_t)(obj->ob_type->tp_basicsize));
Guido van Rossumad47da02002-08-12 19:05:44 +00001339 weaklistptr = (PyObject **)
Guido van Rossum3747a0f2002-08-12 19:25:08 +00001340 ((char *)obj + obj->ob_type->tp_weaklistoffset);
Guido van Rossumad47da02002-08-12 19:05:44 +00001341 if (*weaklistptr == NULL)
1342 result = Py_None;
1343 else
1344 result = *weaklistptr;
1345 Py_INCREF(result);
1346 return result;
1347}
1348
Neil Schemenauerf23473f2001-10-21 22:28:58 +00001349static PyGetSetDef subtype_getsets[] = {
Guido van Rossumad47da02002-08-12 19:05:44 +00001350 /* Not all objects have these attributes!
1351 The descriptor's __get__ method may raise AttributeError. */
1352 {"__dict__", subtype_dict, subtype_setdict,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001353 PyDoc_STR("dictionary for instance variables (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001354 {"__weakref__", subtype_getweakref, NULL,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001355 PyDoc_STR("list of weak references to the object (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001356 {0}
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001357};
1358
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001359/* bozo: __getstate__ that raises TypeError */
1360
1361static PyObject *
1362bozo_func(PyObject *self, PyObject *args)
1363{
1364 PyErr_SetString(PyExc_TypeError,
1365 "a class that defines __slots__ without "
1366 "defining __getstate__ cannot be pickled");
1367 return NULL;
1368}
1369
Neal Norwitz93c1e232002-03-31 16:06:11 +00001370static PyMethodDef bozo_ml = {"__getstate__", bozo_func, METH_VARARGS};
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001371
1372static PyObject *bozo_obj = NULL;
1373
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001374static int
1375valid_identifier(PyObject *s)
1376{
Guido van Rossum03013a02002-07-16 14:30:28 +00001377 unsigned char *p;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001378 int i, n;
1379
1380 if (!PyString_Check(s)) {
1381 PyErr_SetString(PyExc_TypeError,
1382 "__slots__ must be strings");
1383 return 0;
1384 }
Guido van Rossum03013a02002-07-16 14:30:28 +00001385 p = (unsigned char *) PyString_AS_STRING(s);
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001386 n = PyString_GET_SIZE(s);
1387 /* We must reject an empty name. As a hack, we bump the
1388 length to 1 so that the loop will balk on the trailing \0. */
1389 if (n == 0)
1390 n = 1;
1391 for (i = 0; i < n; i++, p++) {
1392 if (!(i == 0 ? isalpha(*p) : isalnum(*p)) && *p != '_') {
1393 PyErr_SetString(PyExc_TypeError,
1394 "__slots__ must be identifiers");
1395 return 0;
1396 }
1397 }
1398 return 1;
1399}
1400
Martin v. Löwisd919a592002-10-14 21:07:28 +00001401#ifdef Py_USING_UNICODE
1402/* Replace Unicode objects in slots. */
1403
1404static PyObject *
1405_unicode_to_string(PyObject *slots, int nslots)
1406{
1407 PyObject *tmp = slots;
1408 PyObject *o, *o1;
1409 int i;
1410 intintargfunc copy = slots->ob_type->tp_as_sequence->sq_slice;
1411 for (i = 0; i < nslots; i++) {
1412 if (PyUnicode_Check(o = PyTuple_GET_ITEM(tmp, i))) {
1413 if (tmp == slots) {
1414 tmp = copy(slots, 0, PyTuple_GET_SIZE(slots));
1415 if (tmp == NULL)
1416 return NULL;
1417 }
1418 o1 = _PyUnicode_AsDefaultEncodedString
1419 (o, NULL);
1420 if (o1 == NULL) {
1421 Py_DECREF(tmp);
1422 return 0;
1423 }
1424 Py_INCREF(o1);
1425 Py_DECREF(o);
1426 PyTuple_SET_ITEM(tmp, i, o1);
1427 }
1428 }
1429 return tmp;
1430}
1431#endif
1432
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001433static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001434type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
1435{
1436 PyObject *name, *bases, *dict;
1437 static char *kwlist[] = {"name", "bases", "dict", 0};
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001438 PyObject *slots, *tmp, *newslots;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001439 PyTypeObject *type, *base, *tmptype, *winner;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001440 etype *et;
Guido van Rossum6f799372001-09-20 20:46:19 +00001441 PyMemberDef *mp;
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001442 int i, nbases, nslots, slotoffset, add_dict, add_weak;
Guido van Rossumad47da02002-08-12 19:05:44 +00001443 int j, may_add_dict, may_add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001444
Tim Peters3abca122001-10-27 19:37:48 +00001445 assert(args != NULL && PyTuple_Check(args));
1446 assert(kwds == NULL || PyDict_Check(kwds));
1447
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001448 /* Special case: type(x) should return x->ob_type */
Tim Peters3abca122001-10-27 19:37:48 +00001449 {
1450 const int nargs = PyTuple_GET_SIZE(args);
1451 const int nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
1452
1453 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
1454 PyObject *x = PyTuple_GET_ITEM(args, 0);
1455 Py_INCREF(x->ob_type);
1456 return (PyObject *) x->ob_type;
1457 }
1458
1459 /* SF bug 475327 -- if that didn't trigger, we need 3
1460 arguments. but PyArg_ParseTupleAndKeywords below may give
1461 a msg saying type() needs exactly 3. */
1462 if (nargs + nkwds != 3) {
1463 PyErr_SetString(PyExc_TypeError,
1464 "type() takes 1 or 3 arguments");
1465 return NULL;
1466 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001467 }
1468
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001469 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001470 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
1471 &name,
1472 &PyTuple_Type, &bases,
1473 &PyDict_Type, &dict))
1474 return NULL;
1475
1476 /* Determine the proper metatype to deal with this,
1477 and check for metatype conflicts while we're at it.
1478 Note that if some other metatype wins to contract,
1479 it's possible that its instances are not types. */
1480 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001481 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001482 for (i = 0; i < nbases; i++) {
1483 tmp = PyTuple_GET_ITEM(bases, i);
1484 tmptype = tmp->ob_type;
Tim Petersa91e9642001-11-14 23:32:33 +00001485 if (tmptype == &PyClass_Type)
1486 continue; /* Special case classic classes */
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001487 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001488 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001489 if (PyType_IsSubtype(tmptype, winner)) {
1490 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001491 continue;
1492 }
1493 PyErr_SetString(PyExc_TypeError,
1494 "metatype conflict among bases");
1495 return NULL;
1496 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001497 if (winner != metatype) {
1498 if (winner->tp_new != type_new) /* Pass it to the winner */
1499 return winner->tp_new(winner, args, kwds);
1500 metatype = winner;
1501 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001502
1503 /* Adjust for empty tuple bases */
1504 if (nbases == 0) {
1505 bases = Py_BuildValue("(O)", &PyBaseObject_Type);
1506 if (bases == NULL)
1507 return NULL;
1508 nbases = 1;
1509 }
1510 else
1511 Py_INCREF(bases);
1512
1513 /* XXX From here until type is allocated, "return NULL" leaks bases! */
1514
1515 /* Calculate best base, and check that all bases are type objects */
1516 base = best_base(bases);
1517 if (base == NULL)
1518 return NULL;
1519 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
1520 PyErr_Format(PyExc_TypeError,
1521 "type '%.100s' is not an acceptable base type",
1522 base->tp_name);
1523 return NULL;
1524 }
1525
Tim Peters6d6c1a32001-08-02 04:15:00 +00001526 /* Check for a __slots__ sequence variable in dict, and count it */
1527 slots = PyDict_GetItemString(dict, "__slots__");
1528 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +00001529 add_dict = 0;
1530 add_weak = 0;
Guido van Rossumad47da02002-08-12 19:05:44 +00001531 may_add_dict = base->tp_dictoffset == 0;
1532 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
1533 if (slots == NULL) {
1534 if (may_add_dict) {
1535 add_dict++;
1536 }
1537 if (may_add_weak) {
1538 add_weak++;
1539 }
1540 }
1541 else {
1542 /* Have slots */
1543
Tim Peters6d6c1a32001-08-02 04:15:00 +00001544 /* Make it into a tuple */
1545 if (PyString_Check(slots))
1546 slots = Py_BuildValue("(O)", slots);
1547 else
1548 slots = PySequence_Tuple(slots);
1549 if (slots == NULL)
1550 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00001551 assert(PyTuple_Check(slots));
1552
1553 /* Are slots allowed? */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001554 nslots = PyTuple_GET_SIZE(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +00001555 if (nslots > 0 && base->tp_itemsize != 0) {
1556 PyErr_Format(PyExc_TypeError,
1557 "nonempty __slots__ "
1558 "not supported for subtype of '%s'",
1559 base->tp_name);
Guido van Rossumad47da02002-08-12 19:05:44 +00001560 bad_slots:
1561 Py_DECREF(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +00001562 return NULL;
1563 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001564
Martin v. Löwisd919a592002-10-14 21:07:28 +00001565#ifdef Py_USING_UNICODE
1566 tmp = _unicode_to_string(slots, nslots);
Martin v. Löwis13b1a5c2002-10-14 21:11:34 +00001567 if (tmp != slots) {
1568 Py_DECREF(slots);
1569 slots = tmp;
1570 }
Martin v. Löwisd919a592002-10-14 21:07:28 +00001571 if (!tmp)
1572 return NULL;
1573#endif
Guido van Rossumad47da02002-08-12 19:05:44 +00001574 /* Check for valid slot names and two special cases */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001575 for (i = 0; i < nslots; i++) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001576 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
1577 char *s;
1578 if (!valid_identifier(tmp))
1579 goto bad_slots;
1580 assert(PyString_Check(tmp));
1581 s = PyString_AS_STRING(tmp);
1582 if (strcmp(s, "__dict__") == 0) {
1583 if (!may_add_dict || add_dict) {
1584 PyErr_SetString(PyExc_TypeError,
1585 "__dict__ slot disallowed: "
1586 "we already got one");
1587 goto bad_slots;
1588 }
1589 add_dict++;
1590 }
1591 if (strcmp(s, "__weakref__") == 0) {
1592 if (!may_add_weak || add_weak) {
1593 PyErr_SetString(PyExc_TypeError,
1594 "__weakref__ slot disallowed: "
1595 "either we already got one, "
1596 "or __itemsize__ != 0");
1597 goto bad_slots;
1598 }
1599 add_weak++;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001600 }
1601 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001602
Guido van Rossumad47da02002-08-12 19:05:44 +00001603 /* Copy slots into yet another tuple, demangling names */
1604 newslots = PyTuple_New(nslots - add_dict - add_weak);
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001605 if (newslots == NULL)
Guido van Rossumad47da02002-08-12 19:05:44 +00001606 goto bad_slots;
1607 for (i = j = 0; i < nslots; i++) {
1608 char *s;
Guido van Rossum8e829202002-08-16 03:47:49 +00001609 char buffer[256];
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001610 tmp = PyTuple_GET_ITEM(slots, i);
Guido van Rossumad47da02002-08-12 19:05:44 +00001611 s = PyString_AS_STRING(tmp);
1612 if ((add_dict && strcmp(s, "__dict__") == 0) ||
1613 (add_weak && strcmp(s, "__weakref__") == 0))
1614 continue;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001615 if (_Py_Mangle(PyString_AS_STRING(name),
Guido van Rossumad47da02002-08-12 19:05:44 +00001616 PyString_AS_STRING(tmp),
1617 buffer, sizeof(buffer)))
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001618 {
1619 tmp = PyString_FromString(buffer);
1620 } else {
1621 Py_INCREF(tmp);
1622 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001623 PyTuple_SET_ITEM(newslots, j, tmp);
1624 j++;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001625 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001626 assert(j == nslots - add_dict - add_weak);
1627 nslots = j;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001628 Py_DECREF(slots);
1629 slots = newslots;
1630
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001631 /* See if *this* class defines __getstate__ */
Guido van Rossumad47da02002-08-12 19:05:44 +00001632 if (PyDict_GetItemString(dict, "__getstate__") == NULL) {
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001633 /* If not, provide a bozo that raises TypeError */
1634 if (bozo_obj == NULL) {
1635 bozo_obj = PyCFunction_New(&bozo_ml, NULL);
Guido van Rossumad47da02002-08-12 19:05:44 +00001636 if (bozo_obj == NULL)
1637 goto bad_slots;
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001638 }
1639 if (PyDict_SetItemString(dict,
1640 "__getstate__",
Guido van Rossumad47da02002-08-12 19:05:44 +00001641 bozo_obj) < 0)
1642 {
1643 Py_DECREF(bozo_obj);
1644 goto bad_slots;
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001645 }
1646 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001647
1648 /* Secondary bases may provide weakrefs or dict */
1649 if (nbases > 1 &&
1650 ((may_add_dict && !add_dict) ||
1651 (may_add_weak && !add_weak))) {
1652 for (i = 0; i < nbases; i++) {
1653 tmp = PyTuple_GET_ITEM(bases, i);
1654 if (tmp == (PyObject *)base)
1655 continue; /* Skip primary base */
1656 if (PyClass_Check(tmp)) {
1657 /* Classic base class provides both */
1658 if (may_add_dict && !add_dict)
1659 add_dict++;
1660 if (may_add_weak && !add_weak)
1661 add_weak++;
1662 break;
1663 }
1664 assert(PyType_Check(tmp));
1665 tmptype = (PyTypeObject *)tmp;
1666 if (may_add_dict && !add_dict &&
1667 tmptype->tp_dictoffset != 0)
1668 add_dict++;
1669 if (may_add_weak && !add_weak &&
1670 tmptype->tp_weaklistoffset != 0)
1671 add_weak++;
1672 if (may_add_dict && !add_dict)
1673 continue;
1674 if (may_add_weak && !add_weak)
1675 continue;
1676 /* Nothing more to check */
1677 break;
1678 }
1679 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001680 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001681
1682 /* XXX From here until type is safely allocated,
1683 "return NULL" may leak slots! */
1684
1685 /* Allocate the type object */
1686 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
Guido van Rossumad47da02002-08-12 19:05:44 +00001687 if (type == NULL) {
1688 Py_XDECREF(slots);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001689 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00001690 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001691
1692 /* Keep name and slots alive in the extended type object */
1693 et = (etype *)type;
1694 Py_INCREF(name);
1695 et->name = name;
1696 et->slots = slots;
1697
Guido van Rossumdc91b992001-08-08 22:26:22 +00001698 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001699 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
1700 Py_TPFLAGS_BASETYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00001701 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
1702 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00001703
1704 /* It's a new-style number unless it specifically inherits any
1705 old-style numeric behavior */
1706 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
1707 (base->tp_as_number == NULL))
1708 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
1709
1710 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001711 type->tp_as_number = &et->as_number;
1712 type->tp_as_sequence = &et->as_sequence;
1713 type->tp_as_mapping = &et->as_mapping;
1714 type->tp_as_buffer = &et->as_buffer;
1715 type->tp_name = PyString_AS_STRING(name);
1716
1717 /* Set tp_base and tp_bases */
1718 type->tp_bases = bases;
1719 Py_INCREF(base);
1720 type->tp_base = base;
1721
Guido van Rossum687ae002001-10-15 22:03:32 +00001722 /* Initialize tp_dict from passed-in dict */
1723 type->tp_dict = dict = PyDict_Copy(dict);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001724 if (dict == NULL) {
1725 Py_DECREF(type);
1726 return NULL;
1727 }
1728
Guido van Rossumc3542212001-08-16 09:18:56 +00001729 /* Set __module__ in the dict */
1730 if (PyDict_GetItemString(dict, "__module__") == NULL) {
1731 tmp = PyEval_GetGlobals();
1732 if (tmp != NULL) {
1733 tmp = PyDict_GetItemString(tmp, "__name__");
1734 if (tmp != NULL) {
1735 if (PyDict_SetItemString(dict, "__module__",
1736 tmp) < 0)
1737 return NULL;
1738 }
1739 }
1740 }
1741
Tim Peters2f93e282001-10-04 05:27:00 +00001742 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
Tim Peters24008312002-03-17 18:56:20 +00001743 and is a string. The __doc__ accessor will first look for tp_doc;
1744 if that fails, it will still look into __dict__.
Tim Peters2f93e282001-10-04 05:27:00 +00001745 */
1746 {
1747 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
1748 if (doc != NULL && PyString_Check(doc)) {
1749 const size_t n = (size_t)PyString_GET_SIZE(doc);
Tim Peters59f809d2001-10-04 05:43:02 +00001750 type->tp_doc = (char *)PyObject_MALLOC(n+1);
Tim Peters2f93e282001-10-04 05:27:00 +00001751 if (type->tp_doc == NULL) {
1752 Py_DECREF(type);
1753 return NULL;
1754 }
1755 memcpy(type->tp_doc, PyString_AS_STRING(doc), n+1);
1756 }
1757 }
1758
Tim Peters6d6c1a32001-08-02 04:15:00 +00001759 /* Special-case __new__: if it's a plain function,
1760 make it a static function */
1761 tmp = PyDict_GetItemString(dict, "__new__");
1762 if (tmp != NULL && PyFunction_Check(tmp)) {
1763 tmp = PyStaticMethod_New(tmp);
1764 if (tmp == NULL) {
1765 Py_DECREF(type);
1766 return NULL;
1767 }
1768 PyDict_SetItemString(dict, "__new__", tmp);
1769 Py_DECREF(tmp);
1770 }
1771
1772 /* Add descriptors for custom slots from __slots__, or for __dict__ */
1773 mp = et->members;
Neil Schemenauerc806c882001-08-29 23:54:54 +00001774 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001775 if (slots != NULL) {
1776 for (i = 0; i < nslots; i++, mp++) {
1777 mp->name = PyString_AS_STRING(
1778 PyTuple_GET_ITEM(slots, i));
Guido van Rossum64b206c2001-12-04 17:13:22 +00001779 mp->type = T_OBJECT_EX;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001780 mp->offset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +00001781 if (base->tp_weaklistoffset == 0 &&
Guido van Rossum64b206c2001-12-04 17:13:22 +00001782 strcmp(mp->name, "__weakref__") == 0) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001783 add_weak++;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001784 mp->type = T_OBJECT;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001785 mp->flags = READONLY;
Guido van Rossum9676b222001-08-17 20:32:36 +00001786 type->tp_weaklistoffset = slotoffset;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001787 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001788 slotoffset += sizeof(PyObject *);
1789 }
1790 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001791 if (add_dict) {
1792 if (base->tp_itemsize)
1793 type->tp_dictoffset = -(long)sizeof(PyObject *);
1794 else
1795 type->tp_dictoffset = slotoffset;
1796 slotoffset += sizeof(PyObject *);
1797 }
1798 if (add_weak) {
1799 assert(!base->tp_itemsize);
1800 type->tp_weaklistoffset = slotoffset;
1801 slotoffset += sizeof(PyObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001802 }
1803 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001804 type->tp_itemsize = base->tp_itemsize;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001805 type->tp_members = et->members;
Guido van Rossumad47da02002-08-12 19:05:44 +00001806 type->tp_getset = subtype_getsets;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001807
1808 /* Special case some slots */
1809 if (type->tp_dictoffset != 0 || nslots > 0) {
1810 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
1811 type->tp_getattro = PyObject_GenericGetAttr;
1812 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
1813 type->tp_setattro = PyObject_GenericSetAttr;
1814 }
1815 type->tp_dealloc = subtype_dealloc;
1816
Guido van Rossum9475a232001-10-05 20:51:39 +00001817 /* Enable GC unless there are really no instance variables possible */
1818 if (!(type->tp_basicsize == sizeof(PyObject) &&
1819 type->tp_itemsize == 0))
1820 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
1821
Tim Peters6d6c1a32001-08-02 04:15:00 +00001822 /* Always override allocation strategy to use regular heap */
1823 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00001824 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001825 type->tp_free = PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00001826 type->tp_traverse = subtype_traverse;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001827 type->tp_clear = subtype_clear;
Guido van Rossum048eb752001-10-02 21:24:57 +00001828 }
1829 else
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001830 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001831
1832 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001833 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001834 Py_DECREF(type);
1835 return NULL;
1836 }
1837
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001838 /* Put the proper slots in place */
1839 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00001840
Tim Peters6d6c1a32001-08-02 04:15:00 +00001841 return (PyObject *)type;
1842}
1843
1844/* Internal API to look for a name through the MRO.
1845 This returns a borrowed reference, and doesn't set an exception! */
1846PyObject *
1847_PyType_Lookup(PyTypeObject *type, PyObject *name)
1848{
1849 int i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00001850 PyObject *mro, *res, *base, *dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001851
Guido van Rossum687ae002001-10-15 22:03:32 +00001852 /* Look in tp_dict of types in MRO */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001853 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00001854
1855 /* If mro is NULL, the type is either not yet initialized
1856 by PyType_Ready(), or already cleared by type_clear().
1857 Either way the safest thing to do is to return NULL. */
1858 if (mro == NULL)
1859 return NULL;
1860
Tim Peters6d6c1a32001-08-02 04:15:00 +00001861 assert(PyTuple_Check(mro));
1862 n = PyTuple_GET_SIZE(mro);
1863 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001864 base = PyTuple_GET_ITEM(mro, i);
1865 if (PyClass_Check(base))
1866 dict = ((PyClassObject *)base)->cl_dict;
1867 else {
1868 assert(PyType_Check(base));
1869 dict = ((PyTypeObject *)base)->tp_dict;
1870 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001871 assert(dict && PyDict_Check(dict));
1872 res = PyDict_GetItem(dict, name);
1873 if (res != NULL)
1874 return res;
1875 }
1876 return NULL;
1877}
1878
1879/* This is similar to PyObject_GenericGetAttr(),
1880 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
1881static PyObject *
1882type_getattro(PyTypeObject *type, PyObject *name)
1883{
1884 PyTypeObject *metatype = type->ob_type;
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001885 PyObject *meta_attribute, *attribute;
1886 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001887
1888 /* Initialize this type (we'll assume the metatype is initialized) */
1889 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001890 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001891 return NULL;
1892 }
1893
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001894 /* No readable descriptor found yet */
1895 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00001896
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001897 /* Look for the attribute in the metatype */
1898 meta_attribute = _PyType_Lookup(metatype, name);
1899
1900 if (meta_attribute != NULL) {
1901 meta_get = meta_attribute->ob_type->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00001902
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001903 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
1904 /* Data descriptors implement tp_descr_set to intercept
1905 * writes. Assume the attribute is not overridden in
1906 * type's tp_dict (and bases): call the descriptor now.
1907 */
1908 return meta_get(meta_attribute, (PyObject *)type,
1909 (PyObject *)metatype);
1910 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001911 }
1912
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001913 /* No data descriptor found on metatype. Look in tp_dict of this
1914 * type and its bases */
1915 attribute = _PyType_Lookup(type, name);
1916 if (attribute != NULL) {
1917 /* Implement descriptor functionality, if any */
1918 descrgetfunc local_get = attribute->ob_type->tp_descr_get;
1919 if (local_get != NULL) {
1920 /* NULL 2nd argument indicates the descriptor was
1921 * found on the target object itself (or a base) */
1922 return local_get(attribute, (PyObject *)NULL,
1923 (PyObject *)type);
1924 }
Tim Peters34592512002-07-11 06:23:50 +00001925
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001926 Py_INCREF(attribute);
1927 return attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001928 }
1929
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001930 /* No attribute found in local __dict__ (or bases): use the
1931 * descriptor from the metatype, if any */
1932 if (meta_get != NULL)
1933 return meta_get(meta_attribute, (PyObject *)type,
1934 (PyObject *)metatype);
1935
1936 /* If an ordinary attribute was found on the metatype, return it now */
1937 if (meta_attribute != NULL) {
1938 Py_INCREF(meta_attribute);
1939 return meta_attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001940 }
1941
1942 /* Give up */
1943 PyErr_Format(PyExc_AttributeError,
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001944 "type object '%.50s' has no attribute '%.400s'",
1945 type->tp_name, PyString_AS_STRING(name));
Tim Peters6d6c1a32001-08-02 04:15:00 +00001946 return NULL;
1947}
1948
1949static int
1950type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
1951{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001952 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
1953 PyErr_Format(
1954 PyExc_TypeError,
1955 "can't set attributes of built-in/extension type '%s'",
1956 type->tp_name);
1957 return -1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001958 }
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001959 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
1960 return -1;
1961 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001962}
1963
1964static void
1965type_dealloc(PyTypeObject *type)
1966{
1967 etype *et;
1968
1969 /* Assert this is a heap-allocated type object */
1970 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00001971 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00001972 PyObject_ClearWeakRefs((PyObject *)type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001973 et = (etype *)type;
1974 Py_XDECREF(type->tp_base);
1975 Py_XDECREF(type->tp_dict);
1976 Py_XDECREF(type->tp_bases);
1977 Py_XDECREF(type->tp_mro);
Guido van Rossum687ae002001-10-15 22:03:32 +00001978 Py_XDECREF(type->tp_cache);
Guido van Rossum1c450732001-10-08 15:18:27 +00001979 Py_XDECREF(type->tp_subclasses);
Neal Norwitzcee5ca02002-07-30 00:42:06 +00001980 PyObject_Free(type->tp_doc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001981 Py_XDECREF(et->name);
1982 Py_XDECREF(et->slots);
1983 type->ob_type->tp_free((PyObject *)type);
1984}
1985
Guido van Rossum1c450732001-10-08 15:18:27 +00001986static PyObject *
1987type_subclasses(PyTypeObject *type, PyObject *args_ignored)
1988{
1989 PyObject *list, *raw, *ref;
1990 int i, n;
1991
1992 list = PyList_New(0);
1993 if (list == NULL)
1994 return NULL;
1995 raw = type->tp_subclasses;
1996 if (raw == NULL)
1997 return list;
1998 assert(PyList_Check(raw));
1999 n = PyList_GET_SIZE(raw);
2000 for (i = 0; i < n; i++) {
2001 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00002002 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00002003 ref = PyWeakref_GET_OBJECT(ref);
2004 if (ref != Py_None) {
2005 if (PyList_Append(list, ref) < 0) {
2006 Py_DECREF(list);
2007 return NULL;
2008 }
2009 }
2010 }
2011 return list;
2012}
2013
Tim Peters6d6c1a32001-08-02 04:15:00 +00002014static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002015 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002016 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
Guido van Rossum1c450732001-10-08 15:18:27 +00002017 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002018 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002019 {0}
2020};
2021
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002022PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002023"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002024"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002025
Guido van Rossum048eb752001-10-02 21:24:57 +00002026static int
2027type_traverse(PyTypeObject *type, visitproc visit, void *arg)
2028{
Guido van Rossum048eb752001-10-02 21:24:57 +00002029 int err;
2030
Guido van Rossuma3862092002-06-10 15:24:42 +00002031 /* Because of type_is_gc(), the collector only calls this
2032 for heaptypes. */
2033 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002034
2035#define VISIT(SLOT) \
2036 if (SLOT) { \
2037 err = visit((PyObject *)(SLOT), arg); \
2038 if (err) \
2039 return err; \
2040 }
2041
2042 VISIT(type->tp_dict);
Guido van Rossum687ae002001-10-15 22:03:32 +00002043 VISIT(type->tp_cache);
Guido van Rossum048eb752001-10-02 21:24:57 +00002044 VISIT(type->tp_mro);
2045 VISIT(type->tp_bases);
2046 VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00002047
2048 /* There's no need to visit type->tp_subclasses or
2049 ((etype *)type)->slots, because they can't be involved
2050 in cycles; tp_subclasses is a list of weak references,
2051 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00002052
2053#undef VISIT
2054
2055 return 0;
2056}
2057
2058static int
2059type_clear(PyTypeObject *type)
2060{
Guido van Rossum048eb752001-10-02 21:24:57 +00002061 PyObject *tmp;
2062
Guido van Rossuma3862092002-06-10 15:24:42 +00002063 /* Because of type_is_gc(), the collector only calls this
2064 for heaptypes. */
2065 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002066
2067#define CLEAR(SLOT) \
2068 if (SLOT) { \
2069 tmp = (PyObject *)(SLOT); \
2070 SLOT = NULL; \
2071 Py_DECREF(tmp); \
2072 }
2073
Guido van Rossuma3862092002-06-10 15:24:42 +00002074 /* The only field we need to clear is tp_mro, which is part of a
2075 hard cycle (its first element is the class itself) that won't
2076 be broken otherwise (it's a tuple and tuples don't have a
2077 tp_clear handler). None of the other fields need to be
2078 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00002079
Guido van Rossuma3862092002-06-10 15:24:42 +00002080 tp_dict:
2081 It is a dict, so the collector will call its tp_clear.
2082
2083 tp_cache:
2084 Not used; if it were, it would be a dict.
2085
2086 tp_bases, tp_base:
2087 If these are involved in a cycle, there must be at least
2088 one other, mutable object in the cycle, e.g. a base
2089 class's dict; the cycle will be broken that way.
2090
2091 tp_subclasses:
2092 A list of weak references can't be part of a cycle; and
2093 lists have their own tp_clear.
2094
2095 slots (in etype):
2096 A tuple of strings can't be part of a cycle.
2097 */
2098
2099 CLEAR(type->tp_mro);
Tim Peters2f93e282001-10-04 05:27:00 +00002100
Guido van Rossum048eb752001-10-02 21:24:57 +00002101#undef CLEAR
2102
2103 return 0;
2104}
2105
2106static int
2107type_is_gc(PyTypeObject *type)
2108{
2109 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
2110}
2111
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002112PyTypeObject PyType_Type = {
2113 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002114 0, /* ob_size */
2115 "type", /* tp_name */
2116 sizeof(etype), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00002117 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002118 (destructor)type_dealloc, /* tp_dealloc */
2119 0, /* tp_print */
2120 0, /* tp_getattr */
2121 0, /* tp_setattr */
2122 type_compare, /* tp_compare */
2123 (reprfunc)type_repr, /* tp_repr */
2124 0, /* tp_as_number */
2125 0, /* tp_as_sequence */
2126 0, /* tp_as_mapping */
2127 (hashfunc)_Py_HashPointer, /* tp_hash */
2128 (ternaryfunc)type_call, /* tp_call */
2129 0, /* tp_str */
2130 (getattrofunc)type_getattro, /* tp_getattro */
2131 (setattrofunc)type_setattro, /* tp_setattro */
2132 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00002133 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2134 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002135 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00002136 (traverseproc)type_traverse, /* tp_traverse */
2137 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002138 0, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00002139 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002140 0, /* tp_iter */
2141 0, /* tp_iternext */
2142 type_methods, /* tp_methods */
2143 type_members, /* tp_members */
2144 type_getsets, /* tp_getset */
2145 0, /* tp_base */
2146 0, /* tp_dict */
2147 0, /* tp_descr_get */
2148 0, /* tp_descr_set */
2149 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
2150 0, /* tp_init */
2151 0, /* tp_alloc */
2152 type_new, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002153 PyObject_GC_Del, /* tp_free */
Guido van Rossum048eb752001-10-02 21:24:57 +00002154 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002155};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002156
2157
2158/* The base type of all types (eventually)... except itself. */
2159
2160static int
2161object_init(PyObject *self, PyObject *args, PyObject *kwds)
2162{
2163 return 0;
2164}
2165
2166static void
2167object_dealloc(PyObject *self)
2168{
2169 self->ob_type->tp_free(self);
2170}
2171
Guido van Rossum8e248182001-08-12 05:17:56 +00002172static PyObject *
2173object_repr(PyObject *self)
2174{
Guido van Rossum76e69632001-08-16 18:52:43 +00002175 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00002176 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002177
Guido van Rossum76e69632001-08-16 18:52:43 +00002178 type = self->ob_type;
2179 mod = type_module(type, NULL);
2180 if (mod == NULL)
2181 PyErr_Clear();
2182 else if (!PyString_Check(mod)) {
2183 Py_DECREF(mod);
2184 mod = NULL;
2185 }
2186 name = type_name(type, NULL);
2187 if (name == NULL)
2188 return NULL;
2189 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002190 rtn = PyString_FromFormat("<%s.%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002191 PyString_AS_STRING(mod),
2192 PyString_AS_STRING(name),
2193 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002194 else
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002195 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002196 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002197 Py_XDECREF(mod);
2198 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00002199 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002200}
2201
Guido van Rossumb8f63662001-08-15 23:57:02 +00002202static PyObject *
2203object_str(PyObject *self)
2204{
2205 unaryfunc f;
2206
2207 f = self->ob_type->tp_repr;
2208 if (f == NULL)
2209 f = object_repr;
2210 return f(self);
2211}
2212
Guido van Rossum8e248182001-08-12 05:17:56 +00002213static long
2214object_hash(PyObject *self)
2215{
2216 return _Py_HashPointer(self);
2217}
Guido van Rossum8e248182001-08-12 05:17:56 +00002218
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002219static PyObject *
2220object_get_class(PyObject *self, void *closure)
2221{
2222 Py_INCREF(self->ob_type);
2223 return (PyObject *)(self->ob_type);
2224}
2225
2226static int
2227equiv_structs(PyTypeObject *a, PyTypeObject *b)
2228{
2229 return a == b ||
2230 (a != NULL &&
2231 b != NULL &&
2232 a->tp_basicsize == b->tp_basicsize &&
2233 a->tp_itemsize == b->tp_itemsize &&
2234 a->tp_dictoffset == b->tp_dictoffset &&
2235 a->tp_weaklistoffset == b->tp_weaklistoffset &&
2236 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
2237 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
2238}
2239
2240static int
2241same_slots_added(PyTypeObject *a, PyTypeObject *b)
2242{
2243 PyTypeObject *base = a->tp_base;
2244 int size;
2245
2246 if (base != b->tp_base)
2247 return 0;
2248 if (equiv_structs(a, base) && equiv_structs(b, base))
2249 return 1;
2250 size = base->tp_basicsize;
2251 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
2252 size += sizeof(PyObject *);
2253 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
2254 size += sizeof(PyObject *);
2255 return size == a->tp_basicsize && size == b->tp_basicsize;
2256}
2257
2258static int
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002259compatible_for_assignment(PyTypeObject* old, PyTypeObject* new, char* attr)
2260{
2261 PyTypeObject *newbase, *oldbase;
2262
2263 if (new->tp_dealloc != old->tp_dealloc ||
2264 new->tp_free != old->tp_free)
2265 {
2266 PyErr_Format(PyExc_TypeError,
2267 "%s assignment: "
2268 "'%s' deallocator differs from '%s'",
2269 attr,
2270 new->tp_name,
2271 old->tp_name);
2272 return 0;
2273 }
2274 newbase = new;
2275 oldbase = old;
2276 while (equiv_structs(newbase, newbase->tp_base))
2277 newbase = newbase->tp_base;
2278 while (equiv_structs(oldbase, oldbase->tp_base))
2279 oldbase = oldbase->tp_base;
2280 if (newbase != oldbase &&
2281 (newbase->tp_base != oldbase->tp_base ||
2282 !same_slots_added(newbase, oldbase))) {
2283 PyErr_Format(PyExc_TypeError,
2284 "%s assignment: "
2285 "'%s' object layout differs from '%s'",
2286 attr,
2287 new->tp_name,
2288 old->tp_name);
2289 return 0;
2290 }
Tim Petersea7f75d2002-12-07 21:39:16 +00002291
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002292 return 1;
2293}
2294
2295static int
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002296object_set_class(PyObject *self, PyObject *value, void *closure)
2297{
2298 PyTypeObject *old = self->ob_type;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002299 PyTypeObject *new;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002300
Guido van Rossumb6b89422002-04-15 01:03:30 +00002301 if (value == NULL) {
2302 PyErr_SetString(PyExc_TypeError,
2303 "can't delete __class__ attribute");
2304 return -1;
2305 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002306 if (!PyType_Check(value)) {
2307 PyErr_Format(PyExc_TypeError,
2308 "__class__ must be set to new-style class, not '%s' object",
2309 value->ob_type->tp_name);
2310 return -1;
2311 }
2312 new = (PyTypeObject *)value;
Guido van Rossum40af8892002-08-10 05:42:07 +00002313 if (!(new->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
2314 !(old->tp_flags & Py_TPFLAGS_HEAPTYPE))
2315 {
2316 PyErr_Format(PyExc_TypeError,
2317 "__class__ assignment: only for heap types");
2318 return -1;
2319 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002320 if (compatible_for_assignment(new, old, "__class__")) {
2321 Py_INCREF(new);
2322 self->ob_type = new;
2323 Py_DECREF(old);
2324 return 0;
2325 }
2326 else {
Guido van Rossum9ee4b942002-05-24 18:47:47 +00002327 return -1;
2328 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002329}
2330
2331static PyGetSetDef object_getsets[] = {
2332 {"__class__", object_get_class, object_set_class,
Neal Norwitz858e34f2002-08-13 17:18:45 +00002333 PyDoc_STR("the object's class")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002334 {0}
2335};
2336
Guido van Rossum3926a632001-09-25 16:25:58 +00002337static PyObject *
2338object_reduce(PyObject *self, PyObject *args)
2339{
2340 /* Call copy_reg._reduce(self) */
2341 static PyObject *copy_reg_str;
2342 PyObject *copy_reg, *res;
2343
2344 if (!copy_reg_str) {
2345 copy_reg_str = PyString_InternFromString("copy_reg");
2346 if (copy_reg_str == NULL)
2347 return NULL;
2348 }
2349 copy_reg = PyImport_Import(copy_reg_str);
2350 if (!copy_reg)
2351 return NULL;
2352 res = PyEval_CallMethod(copy_reg, "_reduce", "(O)", self);
2353 Py_DECREF(copy_reg);
2354 return res;
2355}
2356
2357static PyMethodDef object_methods[] = {
Tim Petersea7f75d2002-12-07 21:39:16 +00002358 {"__reduce__", object_reduce, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002359 PyDoc_STR("helper for pickle")},
Guido van Rossum3926a632001-09-25 16:25:58 +00002360 {0}
2361};
2362
Tim Peters6d6c1a32001-08-02 04:15:00 +00002363PyTypeObject PyBaseObject_Type = {
2364 PyObject_HEAD_INIT(&PyType_Type)
2365 0, /* ob_size */
2366 "object", /* tp_name */
2367 sizeof(PyObject), /* tp_basicsize */
2368 0, /* tp_itemsize */
2369 (destructor)object_dealloc, /* tp_dealloc */
2370 0, /* tp_print */
2371 0, /* tp_getattr */
2372 0, /* tp_setattr */
2373 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002374 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002375 0, /* tp_as_number */
2376 0, /* tp_as_sequence */
2377 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002378 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002379 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002380 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002381 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002382 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002383 0, /* tp_as_buffer */
2384 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002385 PyDoc_STR("The most base type"), /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002386 0, /* tp_traverse */
2387 0, /* tp_clear */
2388 0, /* tp_richcompare */
2389 0, /* tp_weaklistoffset */
2390 0, /* tp_iter */
2391 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00002392 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002393 0, /* tp_members */
2394 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002395 0, /* tp_base */
2396 0, /* tp_dict */
2397 0, /* tp_descr_get */
2398 0, /* tp_descr_set */
2399 0, /* tp_dictoffset */
2400 object_init, /* tp_init */
2401 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossumc11e1922001-08-09 19:38:15 +00002402 PyType_GenericNew, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002403 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002404};
2405
2406
2407/* Initialize the __dict__ in a type object */
2408
Fred Drake7bf97152002-03-28 05:33:33 +00002409static PyObject *
2410create_specialmethod(PyMethodDef *meth, PyObject *(*func)(PyObject *))
2411{
2412 PyObject *cfunc;
2413 PyObject *result;
2414
2415 cfunc = PyCFunction_New(meth, NULL);
2416 if (cfunc == NULL)
2417 return NULL;
2418 result = func(cfunc);
2419 Py_DECREF(cfunc);
2420 return result;
2421}
2422
Tim Peters6d6c1a32001-08-02 04:15:00 +00002423static int
2424add_methods(PyTypeObject *type, PyMethodDef *meth)
2425{
Guido van Rossum687ae002001-10-15 22:03:32 +00002426 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002427
2428 for (; meth->ml_name != NULL; meth++) {
2429 PyObject *descr;
2430 if (PyDict_GetItemString(dict, meth->ml_name))
2431 continue;
Fred Drake7bf97152002-03-28 05:33:33 +00002432 if (meth->ml_flags & METH_CLASS) {
2433 if (meth->ml_flags & METH_STATIC) {
2434 PyErr_SetString(PyExc_ValueError,
2435 "method cannot be both class and static");
2436 return -1;
2437 }
Tim Petersbca1cbc2002-12-09 22:56:13 +00002438 descr = PyDescr_NewClassMethod(type, meth);
Fred Drake7bf97152002-03-28 05:33:33 +00002439 }
2440 else if (meth->ml_flags & METH_STATIC) {
2441 descr = create_specialmethod(meth, PyStaticMethod_New);
2442 }
2443 else {
2444 descr = PyDescr_NewMethod(type, meth);
2445 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002446 if (descr == NULL)
2447 return -1;
Fred Drake7bf97152002-03-28 05:33:33 +00002448 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002449 return -1;
2450 Py_DECREF(descr);
2451 }
2452 return 0;
2453}
2454
2455static int
Guido van Rossum6f799372001-09-20 20:46:19 +00002456add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002457{
Guido van Rossum687ae002001-10-15 22:03:32 +00002458 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002459
2460 for (; memb->name != NULL; memb++) {
2461 PyObject *descr;
2462 if (PyDict_GetItemString(dict, memb->name))
2463 continue;
2464 descr = PyDescr_NewMember(type, memb);
2465 if (descr == NULL)
2466 return -1;
2467 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
2468 return -1;
2469 Py_DECREF(descr);
2470 }
2471 return 0;
2472}
2473
2474static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00002475add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002476{
Guido van Rossum687ae002001-10-15 22:03:32 +00002477 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002478
2479 for (; gsp->name != NULL; gsp++) {
2480 PyObject *descr;
2481 if (PyDict_GetItemString(dict, gsp->name))
2482 continue;
2483 descr = PyDescr_NewGetSet(type, gsp);
2484
2485 if (descr == NULL)
2486 return -1;
2487 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
2488 return -1;
2489 Py_DECREF(descr);
2490 }
2491 return 0;
2492}
2493
Guido van Rossum13d52f02001-08-10 21:24:08 +00002494static void
2495inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002496{
2497 int oldsize, newsize;
2498
Guido van Rossum13d52f02001-08-10 21:24:08 +00002499 /* Special flag magic */
2500 if (!type->tp_as_buffer && base->tp_as_buffer) {
2501 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
2502 type->tp_flags |=
2503 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
2504 }
2505 if (!type->tp_as_sequence && base->tp_as_sequence) {
2506 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
2507 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
2508 }
2509 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
2510 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
2511 if ((!type->tp_as_number && base->tp_as_number) ||
2512 (!type->tp_as_sequence && base->tp_as_sequence)) {
2513 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
2514 if (!type->tp_as_number && !type->tp_as_sequence) {
2515 type->tp_flags |= base->tp_flags &
2516 Py_TPFLAGS_HAVE_INPLACEOPS;
2517 }
2518 }
2519 /* Wow */
2520 }
2521 if (!type->tp_as_number && base->tp_as_number) {
2522 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
2523 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
2524 }
2525
2526 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00002527 oldsize = base->tp_basicsize;
2528 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
2529 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
2530 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00002531 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
2532 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00002533 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00002534 if (type->tp_traverse == NULL)
2535 type->tp_traverse = base->tp_traverse;
2536 if (type->tp_clear == NULL)
2537 type->tp_clear = base->tp_clear;
2538 }
2539 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
Guido van Rossumf884b742001-12-17 17:14:22 +00002540 /* The condition below could use some explanation.
2541 It appears that tp_new is not inherited for static types
2542 whose base class is 'object'; this seems to be a precaution
2543 so that old extension types don't suddenly become
2544 callable (object.__new__ wouldn't insure the invariants
2545 that the extension type's own factory function ensures).
2546 Heap types, of course, are under our control, so they do
2547 inherit tp_new; static extension types that specify some
2548 other built-in type as the default are considered
2549 new-style-aware so they also inherit object.__new__. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002550 if (base != &PyBaseObject_Type ||
2551 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2552 if (type->tp_new == NULL)
2553 type->tp_new = base->tp_new;
2554 }
2555 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00002556 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00002557
2558 /* Copy other non-function slots */
2559
2560#undef COPYVAL
2561#define COPYVAL(SLOT) \
2562 if (type->SLOT == 0) type->SLOT = base->SLOT
2563
2564 COPYVAL(tp_itemsize);
2565 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
2566 COPYVAL(tp_weaklistoffset);
2567 }
2568 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2569 COPYVAL(tp_dictoffset);
2570 }
Guido van Rossum13d52f02001-08-10 21:24:08 +00002571}
2572
2573static void
2574inherit_slots(PyTypeObject *type, PyTypeObject *base)
2575{
2576 PyTypeObject *basebase;
2577
2578#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00002579#undef COPYSLOT
2580#undef COPYNUM
2581#undef COPYSEQ
2582#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00002583#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00002584
2585#define SLOTDEFINED(SLOT) \
2586 (base->SLOT != 0 && \
2587 (basebase == NULL || base->SLOT != basebase->SLOT))
2588
Tim Peters6d6c1a32001-08-02 04:15:00 +00002589#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00002590 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00002591
2592#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
2593#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
2594#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00002595#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002596
Guido van Rossum13d52f02001-08-10 21:24:08 +00002597 /* This won't inherit indirect slots (from tp_as_number etc.)
2598 if type doesn't provide the space. */
2599
2600 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
2601 basebase = base->tp_base;
2602 if (basebase->tp_as_number == NULL)
2603 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002604 COPYNUM(nb_add);
2605 COPYNUM(nb_subtract);
2606 COPYNUM(nb_multiply);
2607 COPYNUM(nb_divide);
2608 COPYNUM(nb_remainder);
2609 COPYNUM(nb_divmod);
2610 COPYNUM(nb_power);
2611 COPYNUM(nb_negative);
2612 COPYNUM(nb_positive);
2613 COPYNUM(nb_absolute);
2614 COPYNUM(nb_nonzero);
2615 COPYNUM(nb_invert);
2616 COPYNUM(nb_lshift);
2617 COPYNUM(nb_rshift);
2618 COPYNUM(nb_and);
2619 COPYNUM(nb_xor);
2620 COPYNUM(nb_or);
2621 COPYNUM(nb_coerce);
2622 COPYNUM(nb_int);
2623 COPYNUM(nb_long);
2624 COPYNUM(nb_float);
2625 COPYNUM(nb_oct);
2626 COPYNUM(nb_hex);
2627 COPYNUM(nb_inplace_add);
2628 COPYNUM(nb_inplace_subtract);
2629 COPYNUM(nb_inplace_multiply);
2630 COPYNUM(nb_inplace_divide);
2631 COPYNUM(nb_inplace_remainder);
2632 COPYNUM(nb_inplace_power);
2633 COPYNUM(nb_inplace_lshift);
2634 COPYNUM(nb_inplace_rshift);
2635 COPYNUM(nb_inplace_and);
2636 COPYNUM(nb_inplace_xor);
2637 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00002638 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
2639 COPYNUM(nb_true_divide);
2640 COPYNUM(nb_floor_divide);
2641 COPYNUM(nb_inplace_true_divide);
2642 COPYNUM(nb_inplace_floor_divide);
2643 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002644 }
2645
Guido van Rossum13d52f02001-08-10 21:24:08 +00002646 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
2647 basebase = base->tp_base;
2648 if (basebase->tp_as_sequence == NULL)
2649 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002650 COPYSEQ(sq_length);
2651 COPYSEQ(sq_concat);
2652 COPYSEQ(sq_repeat);
2653 COPYSEQ(sq_item);
2654 COPYSEQ(sq_slice);
2655 COPYSEQ(sq_ass_item);
2656 COPYSEQ(sq_ass_slice);
2657 COPYSEQ(sq_contains);
2658 COPYSEQ(sq_inplace_concat);
2659 COPYSEQ(sq_inplace_repeat);
2660 }
2661
Guido van Rossum13d52f02001-08-10 21:24:08 +00002662 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
2663 basebase = base->tp_base;
2664 if (basebase->tp_as_mapping == NULL)
2665 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002666 COPYMAP(mp_length);
2667 COPYMAP(mp_subscript);
2668 COPYMAP(mp_ass_subscript);
2669 }
2670
Tim Petersfc57ccb2001-10-12 02:38:24 +00002671 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
2672 basebase = base->tp_base;
2673 if (basebase->tp_as_buffer == NULL)
2674 basebase = NULL;
2675 COPYBUF(bf_getreadbuffer);
2676 COPYBUF(bf_getwritebuffer);
2677 COPYBUF(bf_getsegcount);
2678 COPYBUF(bf_getcharbuffer);
2679 }
2680
Guido van Rossum13d52f02001-08-10 21:24:08 +00002681 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002682
Tim Peters6d6c1a32001-08-02 04:15:00 +00002683 COPYSLOT(tp_dealloc);
2684 COPYSLOT(tp_print);
2685 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
2686 type->tp_getattr = base->tp_getattr;
2687 type->tp_getattro = base->tp_getattro;
2688 }
2689 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
2690 type->tp_setattr = base->tp_setattr;
2691 type->tp_setattro = base->tp_setattro;
2692 }
2693 /* tp_compare see tp_richcompare */
2694 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002695 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002696 COPYSLOT(tp_call);
2697 COPYSLOT(tp_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002698 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00002699 if (type->tp_compare == NULL &&
2700 type->tp_richcompare == NULL &&
2701 type->tp_hash == NULL)
2702 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00002703 type->tp_compare = base->tp_compare;
2704 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002705 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002706 }
2707 }
2708 else {
2709 COPYSLOT(tp_compare);
2710 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002711 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
2712 COPYSLOT(tp_iter);
2713 COPYSLOT(tp_iternext);
2714 }
2715 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2716 COPYSLOT(tp_descr_get);
2717 COPYSLOT(tp_descr_set);
2718 COPYSLOT(tp_dictoffset);
2719 COPYSLOT(tp_init);
2720 COPYSLOT(tp_alloc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002721 COPYSLOT(tp_free);
Guido van Rossumcc8fe042002-04-05 17:10:16 +00002722 COPYSLOT(tp_is_gc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002723 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002724}
2725
Jeremy Hylton938ace62002-07-17 16:30:39 +00002726static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00002727
Tim Peters6d6c1a32001-08-02 04:15:00 +00002728int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002729PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002730{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002731 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002732 PyTypeObject *base;
2733 int i, n;
2734
Guido van Rossumcab05802002-06-10 15:29:03 +00002735 if (type->tp_flags & Py_TPFLAGS_READY) {
2736 assert(type->tp_dict != NULL);
Guido van Rossumd614f972001-08-10 17:39:49 +00002737 return 0;
Guido van Rossumcab05802002-06-10 15:29:03 +00002738 }
Guido van Rossumd614f972001-08-10 17:39:49 +00002739 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00002740
2741 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002742
2743 /* Initialize tp_base (defaults to BaseObject unless that's us) */
2744 base = type->tp_base;
2745 if (base == NULL && type != &PyBaseObject_Type)
2746 base = type->tp_base = &PyBaseObject_Type;
2747
Guido van Rossum323a9cf2002-08-14 17:26:30 +00002748 /* Initialize the base class */
2749 if (base && base->tp_dict == NULL) {
2750 if (PyType_Ready(base) < 0)
2751 goto error;
2752 }
2753
Guido van Rossum0986d822002-04-08 01:38:42 +00002754 /* Initialize ob_type if NULL. This means extensions that want to be
2755 compilable separately on Windows can call PyType_Ready() instead of
2756 initializing the ob_type field of their type objects. */
2757 if (type->ob_type == NULL)
2758 type->ob_type = base->ob_type;
2759
Tim Peters6d6c1a32001-08-02 04:15:00 +00002760 /* Initialize tp_bases */
2761 bases = type->tp_bases;
2762 if (bases == NULL) {
2763 if (base == NULL)
2764 bases = PyTuple_New(0);
2765 else
2766 bases = Py_BuildValue("(O)", base);
2767 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00002768 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002769 type->tp_bases = bases;
2770 }
2771
Guido van Rossum687ae002001-10-15 22:03:32 +00002772 /* Initialize tp_dict */
2773 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002774 if (dict == NULL) {
2775 dict = PyDict_New();
2776 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00002777 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00002778 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002779 }
2780
Guido van Rossum687ae002001-10-15 22:03:32 +00002781 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002782 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002783 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002784 if (type->tp_methods != NULL) {
2785 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002786 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002787 }
2788 if (type->tp_members != NULL) {
2789 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002790 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002791 }
2792 if (type->tp_getset != NULL) {
2793 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002794 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002795 }
2796
Tim Peters6d6c1a32001-08-02 04:15:00 +00002797 /* Calculate method resolution order */
2798 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00002799 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002800 }
2801
Guido van Rossum13d52f02001-08-10 21:24:08 +00002802 /* Inherit special flags from dominant base */
2803 if (type->tp_base != NULL)
2804 inherit_special(type, type->tp_base);
2805
Tim Peters6d6c1a32001-08-02 04:15:00 +00002806 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002807 bases = type->tp_mro;
2808 assert(bases != NULL);
2809 assert(PyTuple_Check(bases));
2810 n = PyTuple_GET_SIZE(bases);
2811 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002812 PyObject *b = PyTuple_GET_ITEM(bases, i);
2813 if (PyType_Check(b))
2814 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002815 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002816
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00002817 /* if the type dictionary doesn't contain a __doc__, set it from
2818 the tp_doc slot.
2819 */
2820 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
2821 if (type->tp_doc != NULL) {
2822 PyObject *doc = PyString_FromString(type->tp_doc);
2823 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
2824 Py_DECREF(doc);
2825 } else {
Guido van Rossumd4641072002-04-03 02:13:37 +00002826 PyDict_SetItemString(type->tp_dict,
2827 "__doc__", Py_None);
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00002828 }
2829 }
2830
Guido van Rossum13d52f02001-08-10 21:24:08 +00002831 /* Some more special stuff */
2832 base = type->tp_base;
2833 if (base != NULL) {
2834 if (type->tp_as_number == NULL)
2835 type->tp_as_number = base->tp_as_number;
2836 if (type->tp_as_sequence == NULL)
2837 type->tp_as_sequence = base->tp_as_sequence;
2838 if (type->tp_as_mapping == NULL)
2839 type->tp_as_mapping = base->tp_as_mapping;
2840 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002841
Guido van Rossum1c450732001-10-08 15:18:27 +00002842 /* Link into each base class's list of subclasses */
2843 bases = type->tp_bases;
2844 n = PyTuple_GET_SIZE(bases);
2845 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002846 PyObject *b = PyTuple_GET_ITEM(bases, i);
2847 if (PyType_Check(b) &&
2848 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00002849 goto error;
2850 }
2851
Guido van Rossum13d52f02001-08-10 21:24:08 +00002852 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00002853 assert(type->tp_dict != NULL);
2854 type->tp_flags =
2855 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002856 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00002857
2858 error:
2859 type->tp_flags &= ~Py_TPFLAGS_READYING;
2860 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002861}
2862
Guido van Rossum1c450732001-10-08 15:18:27 +00002863static int
2864add_subclass(PyTypeObject *base, PyTypeObject *type)
2865{
2866 int i;
2867 PyObject *list, *ref, *new;
2868
2869 list = base->tp_subclasses;
2870 if (list == NULL) {
2871 base->tp_subclasses = list = PyList_New(0);
2872 if (list == NULL)
2873 return -1;
2874 }
2875 assert(PyList_Check(list));
2876 new = PyWeakref_NewRef((PyObject *)type, NULL);
2877 i = PyList_GET_SIZE(list);
2878 while (--i >= 0) {
2879 ref = PyList_GET_ITEM(list, i);
2880 assert(PyWeakref_CheckRef(ref));
Guido van Rossum3930bc32002-10-18 13:51:49 +00002881 if (PyWeakref_GET_OBJECT(ref) == Py_None)
2882 return PyList_SetItem(list, i, new);
Guido van Rossum1c450732001-10-08 15:18:27 +00002883 }
2884 i = PyList_Append(list, new);
2885 Py_DECREF(new);
2886 return i;
2887}
2888
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002889static void
2890remove_subclass(PyTypeObject *base, PyTypeObject *type)
2891{
2892 int i;
2893 PyObject *list, *ref;
2894
2895 list = base->tp_subclasses;
2896 if (list == NULL) {
2897 return;
2898 }
2899 assert(PyList_Check(list));
2900 i = PyList_GET_SIZE(list);
2901 while (--i >= 0) {
2902 ref = PyList_GET_ITEM(list, i);
2903 assert(PyWeakref_CheckRef(ref));
2904 if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
2905 /* this can't fail, right? */
2906 PySequence_DelItem(list, i);
2907 return;
2908 }
2909 }
2910}
Tim Peters6d6c1a32001-08-02 04:15:00 +00002911
2912/* Generic wrappers for overloadable 'operators' such as __getitem__ */
2913
2914/* There's a wrapper *function* for each distinct function typedef used
2915 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
2916 wrapper *table* for each distinct operation (e.g. __len__, __add__).
2917 Most tables have only one entry; the tables for binary operators have two
2918 entries, one regular and one with reversed arguments. */
2919
2920static PyObject *
2921wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
2922{
2923 inquiry func = (inquiry)wrapped;
2924 int res;
2925
2926 if (!PyArg_ParseTuple(args, ""))
2927 return NULL;
2928 res = (*func)(self);
2929 if (res == -1 && PyErr_Occurred())
2930 return NULL;
2931 return PyInt_FromLong((long)res);
2932}
2933
Tim Peters6d6c1a32001-08-02 04:15:00 +00002934static PyObject *
2935wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
2936{
2937 binaryfunc func = (binaryfunc)wrapped;
2938 PyObject *other;
2939
2940 if (!PyArg_ParseTuple(args, "O", &other))
2941 return NULL;
2942 return (*func)(self, other);
2943}
2944
2945static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002946wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
2947{
2948 binaryfunc func = (binaryfunc)wrapped;
2949 PyObject *other;
2950
2951 if (!PyArg_ParseTuple(args, "O", &other))
2952 return NULL;
2953 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002954 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002955 Py_INCREF(Py_NotImplemented);
2956 return Py_NotImplemented;
2957 }
2958 return (*func)(self, other);
2959}
2960
2961static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00002962wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2963{
2964 binaryfunc func = (binaryfunc)wrapped;
2965 PyObject *other;
2966
2967 if (!PyArg_ParseTuple(args, "O", &other))
2968 return NULL;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002969 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002970 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002971 Py_INCREF(Py_NotImplemented);
2972 return Py_NotImplemented;
2973 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002974 return (*func)(other, self);
2975}
2976
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002977static PyObject *
2978wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
2979{
2980 coercion func = (coercion)wrapped;
2981 PyObject *other, *res;
2982 int ok;
2983
2984 if (!PyArg_ParseTuple(args, "O", &other))
2985 return NULL;
2986 ok = func(&self, &other);
2987 if (ok < 0)
2988 return NULL;
2989 if (ok > 0) {
2990 Py_INCREF(Py_NotImplemented);
2991 return Py_NotImplemented;
2992 }
2993 res = PyTuple_New(2);
2994 if (res == NULL) {
2995 Py_DECREF(self);
2996 Py_DECREF(other);
2997 return NULL;
2998 }
2999 PyTuple_SET_ITEM(res, 0, self);
3000 PyTuple_SET_ITEM(res, 1, other);
3001 return res;
3002}
3003
Tim Peters6d6c1a32001-08-02 04:15:00 +00003004static PyObject *
3005wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
3006{
3007 ternaryfunc func = (ternaryfunc)wrapped;
3008 PyObject *other;
3009 PyObject *third = Py_None;
3010
3011 /* Note: This wrapper only works for __pow__() */
3012
3013 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
3014 return NULL;
3015 return (*func)(self, other, third);
3016}
3017
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00003018static PyObject *
3019wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3020{
3021 ternaryfunc func = (ternaryfunc)wrapped;
3022 PyObject *other;
3023 PyObject *third = Py_None;
3024
3025 /* Note: This wrapper only works for __pow__() */
3026
3027 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
3028 return NULL;
3029 return (*func)(other, self, third);
3030}
3031
Tim Peters6d6c1a32001-08-02 04:15:00 +00003032static PyObject *
3033wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
3034{
3035 unaryfunc func = (unaryfunc)wrapped;
3036
3037 if (!PyArg_ParseTuple(args, ""))
3038 return NULL;
3039 return (*func)(self);
3040}
3041
Tim Peters6d6c1a32001-08-02 04:15:00 +00003042static PyObject *
3043wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
3044{
3045 intargfunc func = (intargfunc)wrapped;
3046 int i;
3047
3048 if (!PyArg_ParseTuple(args, "i", &i))
3049 return NULL;
3050 return (*func)(self, i);
3051}
3052
Guido van Rossum5d815f32001-08-17 21:57:47 +00003053static int
3054getindex(PyObject *self, PyObject *arg)
3055{
3056 int i;
3057
3058 i = PyInt_AsLong(arg);
3059 if (i == -1 && PyErr_Occurred())
3060 return -1;
3061 if (i < 0) {
3062 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
3063 if (sq && sq->sq_length) {
3064 int n = (*sq->sq_length)(self);
3065 if (n < 0)
3066 return -1;
3067 i += n;
3068 }
3069 }
3070 return i;
3071}
3072
3073static PyObject *
3074wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
3075{
3076 intargfunc func = (intargfunc)wrapped;
3077 PyObject *arg;
3078 int i;
3079
Guido van Rossumf4593e02001-10-03 12:09:30 +00003080 if (PyTuple_GET_SIZE(args) == 1) {
3081 arg = PyTuple_GET_ITEM(args, 0);
3082 i = getindex(self, arg);
3083 if (i == -1 && PyErr_Occurred())
3084 return NULL;
3085 return (*func)(self, i);
3086 }
3087 PyArg_ParseTuple(args, "O", &arg);
3088 assert(PyErr_Occurred());
3089 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003090}
3091
Tim Peters6d6c1a32001-08-02 04:15:00 +00003092static PyObject *
3093wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
3094{
3095 intintargfunc func = (intintargfunc)wrapped;
3096 int i, j;
3097
3098 if (!PyArg_ParseTuple(args, "ii", &i, &j))
3099 return NULL;
3100 return (*func)(self, i, j);
3101}
3102
Tim Peters6d6c1a32001-08-02 04:15:00 +00003103static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003104wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003105{
3106 intobjargproc func = (intobjargproc)wrapped;
3107 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003108 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003109
Guido van Rossum5d815f32001-08-17 21:57:47 +00003110 if (!PyArg_ParseTuple(args, "OO", &arg, &value))
3111 return NULL;
3112 i = getindex(self, arg);
3113 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00003114 return NULL;
3115 res = (*func)(self, i, value);
3116 if (res == -1 && PyErr_Occurred())
3117 return NULL;
3118 Py_INCREF(Py_None);
3119 return Py_None;
3120}
3121
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003122static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003123wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003124{
3125 intobjargproc func = (intobjargproc)wrapped;
3126 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003127 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003128
Guido van Rossum5d815f32001-08-17 21:57:47 +00003129 if (!PyArg_ParseTuple(args, "O", &arg))
3130 return NULL;
3131 i = getindex(self, arg);
3132 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003133 return NULL;
3134 res = (*func)(self, i, NULL);
3135 if (res == -1 && PyErr_Occurred())
3136 return NULL;
3137 Py_INCREF(Py_None);
3138 return Py_None;
3139}
3140
Tim Peters6d6c1a32001-08-02 04:15:00 +00003141static PyObject *
3142wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
3143{
3144 intintobjargproc func = (intintobjargproc)wrapped;
3145 int i, j, res;
3146 PyObject *value;
3147
3148 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
3149 return NULL;
3150 res = (*func)(self, i, j, value);
3151 if (res == -1 && PyErr_Occurred())
3152 return NULL;
3153 Py_INCREF(Py_None);
3154 return Py_None;
3155}
3156
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003157static PyObject *
3158wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
3159{
3160 intintobjargproc func = (intintobjargproc)wrapped;
3161 int i, j, res;
3162
3163 if (!PyArg_ParseTuple(args, "ii", &i, &j))
3164 return NULL;
3165 res = (*func)(self, i, j, NULL);
3166 if (res == -1 && PyErr_Occurred())
3167 return NULL;
3168 Py_INCREF(Py_None);
3169 return Py_None;
3170}
3171
Tim Peters6d6c1a32001-08-02 04:15:00 +00003172/* XXX objobjproc is a misnomer; should be objargpred */
3173static PyObject *
3174wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
3175{
3176 objobjproc func = (objobjproc)wrapped;
3177 int res;
3178 PyObject *value;
3179
3180 if (!PyArg_ParseTuple(args, "O", &value))
3181 return NULL;
3182 res = (*func)(self, value);
3183 if (res == -1 && PyErr_Occurred())
3184 return NULL;
3185 return PyInt_FromLong((long)res);
3186}
3187
Tim Peters6d6c1a32001-08-02 04:15:00 +00003188static PyObject *
3189wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
3190{
3191 objobjargproc func = (objobjargproc)wrapped;
3192 int res;
3193 PyObject *key, *value;
3194
3195 if (!PyArg_ParseTuple(args, "OO", &key, &value))
3196 return NULL;
3197 res = (*func)(self, key, value);
3198 if (res == -1 && PyErr_Occurred())
3199 return NULL;
3200 Py_INCREF(Py_None);
3201 return Py_None;
3202}
3203
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003204static PyObject *
3205wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
3206{
3207 objobjargproc func = (objobjargproc)wrapped;
3208 int res;
3209 PyObject *key;
3210
3211 if (!PyArg_ParseTuple(args, "O", &key))
3212 return NULL;
3213 res = (*func)(self, key, NULL);
3214 if (res == -1 && PyErr_Occurred())
3215 return NULL;
3216 Py_INCREF(Py_None);
3217 return Py_None;
3218}
3219
Tim Peters6d6c1a32001-08-02 04:15:00 +00003220static PyObject *
3221wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
3222{
3223 cmpfunc func = (cmpfunc)wrapped;
3224 int res;
3225 PyObject *other;
3226
3227 if (!PyArg_ParseTuple(args, "O", &other))
3228 return NULL;
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00003229 if (other->ob_type->tp_compare != func &&
3230 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00003231 PyErr_Format(
3232 PyExc_TypeError,
3233 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
3234 self->ob_type->tp_name,
3235 self->ob_type->tp_name,
3236 other->ob_type->tp_name);
3237 return NULL;
3238 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003239 res = (*func)(self, other);
3240 if (PyErr_Occurred())
3241 return NULL;
3242 return PyInt_FromLong((long)res);
3243}
3244
Tim Peters6d6c1a32001-08-02 04:15:00 +00003245static PyObject *
3246wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
3247{
3248 setattrofunc func = (setattrofunc)wrapped;
3249 int res;
3250 PyObject *name, *value;
3251
3252 if (!PyArg_ParseTuple(args, "OO", &name, &value))
3253 return NULL;
3254 res = (*func)(self, name, value);
3255 if (res < 0)
3256 return NULL;
3257 Py_INCREF(Py_None);
3258 return Py_None;
3259}
3260
3261static PyObject *
3262wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
3263{
3264 setattrofunc func = (setattrofunc)wrapped;
3265 int res;
3266 PyObject *name;
3267
3268 if (!PyArg_ParseTuple(args, "O", &name))
3269 return NULL;
3270 res = (*func)(self, name, NULL);
3271 if (res < 0)
3272 return NULL;
3273 Py_INCREF(Py_None);
3274 return Py_None;
3275}
3276
Tim Peters6d6c1a32001-08-02 04:15:00 +00003277static PyObject *
3278wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
3279{
3280 hashfunc func = (hashfunc)wrapped;
3281 long res;
3282
3283 if (!PyArg_ParseTuple(args, ""))
3284 return NULL;
3285 res = (*func)(self);
3286 if (res == -1 && PyErr_Occurred())
3287 return NULL;
3288 return PyInt_FromLong(res);
3289}
3290
Tim Peters6d6c1a32001-08-02 04:15:00 +00003291static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00003292wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003293{
3294 ternaryfunc func = (ternaryfunc)wrapped;
3295
Guido van Rossumc8e56452001-10-22 00:43:43 +00003296 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003297}
3298
Tim Peters6d6c1a32001-08-02 04:15:00 +00003299static PyObject *
3300wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
3301{
3302 richcmpfunc func = (richcmpfunc)wrapped;
3303 PyObject *other;
3304
3305 if (!PyArg_ParseTuple(args, "O", &other))
3306 return NULL;
3307 return (*func)(self, other, op);
3308}
3309
3310#undef RICHCMP_WRAPPER
3311#define RICHCMP_WRAPPER(NAME, OP) \
3312static PyObject * \
3313richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
3314{ \
3315 return wrap_richcmpfunc(self, args, wrapped, OP); \
3316}
3317
Jack Jansen8e938b42001-08-08 15:29:49 +00003318RICHCMP_WRAPPER(lt, Py_LT)
3319RICHCMP_WRAPPER(le, Py_LE)
3320RICHCMP_WRAPPER(eq, Py_EQ)
3321RICHCMP_WRAPPER(ne, Py_NE)
3322RICHCMP_WRAPPER(gt, Py_GT)
3323RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003324
Tim Peters6d6c1a32001-08-02 04:15:00 +00003325static PyObject *
3326wrap_next(PyObject *self, PyObject *args, void *wrapped)
3327{
3328 unaryfunc func = (unaryfunc)wrapped;
3329 PyObject *res;
3330
3331 if (!PyArg_ParseTuple(args, ""))
3332 return NULL;
3333 res = (*func)(self);
3334 if (res == NULL && !PyErr_Occurred())
3335 PyErr_SetNone(PyExc_StopIteration);
3336 return res;
3337}
3338
Tim Peters6d6c1a32001-08-02 04:15:00 +00003339static PyObject *
3340wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
3341{
3342 descrgetfunc func = (descrgetfunc)wrapped;
3343 PyObject *obj;
3344 PyObject *type = NULL;
3345
3346 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
3347 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003348 return (*func)(self, obj, type);
3349}
3350
Tim Peters6d6c1a32001-08-02 04:15:00 +00003351static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003352wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003353{
3354 descrsetfunc func = (descrsetfunc)wrapped;
3355 PyObject *obj, *value;
3356 int ret;
3357
3358 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
3359 return NULL;
3360 ret = (*func)(self, obj, value);
3361 if (ret < 0)
3362 return NULL;
3363 Py_INCREF(Py_None);
3364 return Py_None;
3365}
Guido van Rossum22b13872002-08-06 21:41:44 +00003366
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00003367static PyObject *
3368wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
3369{
3370 descrsetfunc func = (descrsetfunc)wrapped;
3371 PyObject *obj;
3372 int ret;
3373
3374 if (!PyArg_ParseTuple(args, "O", &obj))
3375 return NULL;
3376 ret = (*func)(self, obj, NULL);
3377 if (ret < 0)
3378 return NULL;
3379 Py_INCREF(Py_None);
3380 return Py_None;
3381}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003382
Tim Peters6d6c1a32001-08-02 04:15:00 +00003383static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00003384wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003385{
3386 initproc func = (initproc)wrapped;
3387
Guido van Rossumc8e56452001-10-22 00:43:43 +00003388 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003389 return NULL;
3390 Py_INCREF(Py_None);
3391 return Py_None;
3392}
3393
Tim Peters6d6c1a32001-08-02 04:15:00 +00003394static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003395tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003396{
Barry Warsaw60f01882001-08-22 19:24:42 +00003397 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003398 PyObject *arg0, *res;
3399
3400 if (self == NULL || !PyType_Check(self))
3401 Py_FatalError("__new__() called with non-type 'self'");
3402 type = (PyTypeObject *)self;
3403 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003404 PyErr_Format(PyExc_TypeError,
3405 "%s.__new__(): not enough arguments",
3406 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003407 return NULL;
3408 }
3409 arg0 = PyTuple_GET_ITEM(args, 0);
3410 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003411 PyErr_Format(PyExc_TypeError,
3412 "%s.__new__(X): X is not a type object (%s)",
3413 type->tp_name,
3414 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003415 return NULL;
3416 }
3417 subtype = (PyTypeObject *)arg0;
3418 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003419 PyErr_Format(PyExc_TypeError,
3420 "%s.__new__(%s): %s is not a subtype of %s",
3421 type->tp_name,
3422 subtype->tp_name,
3423 subtype->tp_name,
3424 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003425 return NULL;
3426 }
Barry Warsaw60f01882001-08-22 19:24:42 +00003427
3428 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00003429 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00003430 most derived base that's not a heap type is this type. */
3431 staticbase = subtype;
3432 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
3433 staticbase = staticbase->tp_base;
Guido van Rossuma8c60f42001-09-14 19:43:36 +00003434 if (staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003435 PyErr_Format(PyExc_TypeError,
3436 "%s.__new__(%s) is not safe, use %s.__new__()",
3437 type->tp_name,
3438 subtype->tp_name,
3439 staticbase == NULL ? "?" : staticbase->tp_name);
3440 return NULL;
3441 }
3442
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003443 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
3444 if (args == NULL)
3445 return NULL;
3446 res = type->tp_new(subtype, args, kwds);
3447 Py_DECREF(args);
3448 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003449}
3450
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003451static struct PyMethodDef tp_new_methoddef[] = {
3452 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00003453 PyDoc_STR("T.__new__(S, ...) -> "
3454 "a new object with type S, a subtype of T")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00003455 {0}
3456};
3457
3458static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003459add_tp_new_wrapper(PyTypeObject *type)
3460{
Guido van Rossumf040ede2001-08-07 16:40:56 +00003461 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003462
Guido van Rossum687ae002001-10-15 22:03:32 +00003463 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00003464 return 0;
3465 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003466 if (func == NULL)
3467 return -1;
Guido van Rossum687ae002001-10-15 22:03:32 +00003468 return PyDict_SetItemString(type->tp_dict, "__new__", func);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003469}
3470
Guido van Rossumf040ede2001-08-07 16:40:56 +00003471/* Slot wrappers that call the corresponding __foo__ slot. See comments
3472 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003473
Guido van Rossumdc91b992001-08-08 22:26:22 +00003474#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003475static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003476FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003477{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00003478 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003479 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003480}
3481
Guido van Rossumdc91b992001-08-08 22:26:22 +00003482#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003483static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003484FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003485{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003486 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003487 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003488}
3489
Guido van Rossumdc91b992001-08-08 22:26:22 +00003490
3491#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003492static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003493FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003494{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003495 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00003496 int do_other = self->ob_type != other->ob_type && \
3497 other->ob_type->tp_as_number != NULL && \
3498 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003499 if (self->ob_type->tp_as_number != NULL && \
3500 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
3501 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00003502 if (do_other && \
3503 PyType_IsSubtype(other->ob_type, self->ob_type)) { \
3504 r = call_maybe( \
3505 other, ROPSTR, &rcache_str, "(O)", self); \
3506 if (r != Py_NotImplemented) \
3507 return r; \
3508 Py_DECREF(r); \
3509 do_other = 0; \
3510 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00003511 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00003512 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003513 if (r != Py_NotImplemented || \
3514 other->ob_type == self->ob_type) \
3515 return r; \
3516 Py_DECREF(r); \
3517 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00003518 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00003519 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00003520 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003521 } \
3522 Py_INCREF(Py_NotImplemented); \
3523 return Py_NotImplemented; \
3524}
3525
3526#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
3527 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
3528
3529#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
3530static PyObject * \
3531FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
3532{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003533 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003534 return call_method(self, OPSTR, &cache_str, \
3535 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003536}
3537
3538static int
3539slot_sq_length(PyObject *self)
3540{
Guido van Rossum2730b132001-08-28 18:22:14 +00003541 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00003542 PyObject *res = call_method(self, "__len__", &len_str, "()");
Guido van Rossum26111622001-10-01 16:42:49 +00003543 int len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003544
3545 if (res == NULL)
3546 return -1;
Guido van Rossum26111622001-10-01 16:42:49 +00003547 len = (int)PyInt_AsLong(res);
3548 Py_DECREF(res);
Jeremy Hylton73a088e2002-07-25 16:43:29 +00003549 if (len == -1 && PyErr_Occurred())
3550 return -1;
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00003551 if (len < 0) {
Guido van Rossum22b13872002-08-06 21:41:44 +00003552 PyErr_SetString(PyExc_ValueError,
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00003553 "__len__() should return >= 0");
3554 return -1;
3555 }
Guido van Rossum26111622001-10-01 16:42:49 +00003556 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003557}
3558
Guido van Rossumdc91b992001-08-08 22:26:22 +00003559SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
3560SLOT1(slot_sq_repeat, "__mul__", int, "i")
Guido van Rossumf4593e02001-10-03 12:09:30 +00003561
3562/* Super-optimized version of slot_sq_item.
3563 Other slots could do the same... */
3564static PyObject *
3565slot_sq_item(PyObject *self, int i)
3566{
3567 static PyObject *getitem_str;
3568 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
3569 descrgetfunc f;
3570
3571 if (getitem_str == NULL) {
3572 getitem_str = PyString_InternFromString("__getitem__");
3573 if (getitem_str == NULL)
3574 return NULL;
3575 }
3576 func = _PyType_Lookup(self->ob_type, getitem_str);
3577 if (func != NULL) {
Guido van Rossumf4593e02001-10-03 12:09:30 +00003578 if ((f = func->ob_type->tp_descr_get) == NULL)
3579 Py_INCREF(func);
Neal Norwitz673cd822002-10-18 16:33:13 +00003580 else {
Guido van Rossumf4593e02001-10-03 12:09:30 +00003581 func = f(func, self, (PyObject *)(self->ob_type));
Neal Norwitz673cd822002-10-18 16:33:13 +00003582 if (func == NULL) {
3583 return NULL;
3584 }
3585 }
Guido van Rossumf4593e02001-10-03 12:09:30 +00003586 ival = PyInt_FromLong(i);
3587 if (ival != NULL) {
3588 args = PyTuple_New(1);
3589 if (args != NULL) {
3590 PyTuple_SET_ITEM(args, 0, ival);
3591 retval = PyObject_Call(func, args, NULL);
3592 Py_XDECREF(args);
3593 Py_XDECREF(func);
3594 return retval;
3595 }
3596 }
3597 }
3598 else {
3599 PyErr_SetObject(PyExc_AttributeError, getitem_str);
3600 }
3601 Py_XDECREF(args);
3602 Py_XDECREF(ival);
3603 Py_XDECREF(func);
3604 return NULL;
3605}
3606
Guido van Rossumdc91b992001-08-08 22:26:22 +00003607SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003608
3609static int
3610slot_sq_ass_item(PyObject *self, int index, PyObject *value)
3611{
3612 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003613 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003614
3615 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003616 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003617 "(i)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003618 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003619 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003620 "(iO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003621 if (res == NULL)
3622 return -1;
3623 Py_DECREF(res);
3624 return 0;
3625}
3626
3627static int
3628slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
3629{
3630 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003631 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003632
3633 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003634 res = call_method(self, "__delslice__", &delslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003635 "(ii)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003636 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003637 res = call_method(self, "__setslice__", &setslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003638 "(iiO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003639 if (res == NULL)
3640 return -1;
3641 Py_DECREF(res);
3642 return 0;
3643}
3644
3645static int
3646slot_sq_contains(PyObject *self, PyObject *value)
3647{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003648 PyObject *func, *res, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00003649 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003650
Guido van Rossum55f20992001-10-01 17:18:22 +00003651 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003652
3653 if (func != NULL) {
3654 args = Py_BuildValue("(O)", value);
3655 if (args == NULL)
3656 res = NULL;
3657 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003658 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003659 Py_DECREF(args);
3660 }
3661 Py_DECREF(func);
3662 if (res == NULL)
3663 return -1;
3664 return PyObject_IsTrue(res);
3665 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003666 else if (PyErr_Occurred())
3667 return -1;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003668 else {
Tim Peters16a77ad2001-09-08 04:00:12 +00003669 return _PySequence_IterSearch(self, value,
3670 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003671 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003672}
3673
Guido van Rossumdc91b992001-08-08 22:26:22 +00003674SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
3675SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003676
3677#define slot_mp_length slot_sq_length
3678
Guido van Rossumdc91b992001-08-08 22:26:22 +00003679SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003680
3681static int
3682slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
3683{
3684 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003685 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003686
3687 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003688 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003689 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003690 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003691 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003692 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003693 if (res == NULL)
3694 return -1;
3695 Py_DECREF(res);
3696 return 0;
3697}
3698
Guido van Rossumdc91b992001-08-08 22:26:22 +00003699SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
3700SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
3701SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
3702SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
3703SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
3704SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
3705
Jeremy Hylton938ace62002-07-17 16:30:39 +00003706static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003707
3708SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
3709 nb_power, "__pow__", "__rpow__")
3710
3711static PyObject *
3712slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
3713{
Guido van Rossum2730b132001-08-28 18:22:14 +00003714 static PyObject *pow_str;
3715
Guido van Rossumdc91b992001-08-08 22:26:22 +00003716 if (modulus == Py_None)
3717 return slot_nb_power_binary(self, other);
Guido van Rossum23094982002-06-10 14:30:43 +00003718 /* Three-arg power doesn't use __rpow__. But ternary_op
3719 can call this when the second argument's type uses
3720 slot_nb_power, so check before calling self.__pow__. */
3721 if (self->ob_type->tp_as_number != NULL &&
3722 self->ob_type->tp_as_number->nb_power == slot_nb_power) {
3723 return call_method(self, "__pow__", &pow_str,
3724 "(OO)", other, modulus);
3725 }
3726 Py_INCREF(Py_NotImplemented);
3727 return Py_NotImplemented;
Guido van Rossumdc91b992001-08-08 22:26:22 +00003728}
3729
3730SLOT0(slot_nb_negative, "__neg__")
3731SLOT0(slot_nb_positive, "__pos__")
3732SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003733
3734static int
3735slot_nb_nonzero(PyObject *self)
3736{
Tim Petersea7f75d2002-12-07 21:39:16 +00003737 PyObject *func, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00003738 static PyObject *nonzero_str, *len_str;
Tim Petersea7f75d2002-12-07 21:39:16 +00003739 int result = -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003740
Guido van Rossum55f20992001-10-01 17:18:22 +00003741 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003742 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00003743 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00003744 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00003745 func = lookup_maybe(self, "__len__", &len_str);
Tim Petersea7f75d2002-12-07 21:39:16 +00003746 if (func == NULL)
3747 return PyErr_Occurred() ? -1 : 1;
3748 }
3749 args = PyTuple_New(0);
3750 if (args != NULL) {
3751 PyObject *temp = PyObject_Call(func, args, NULL);
3752 Py_DECREF(args);
3753 if (temp != NULL) {
3754 result = PyObject_IsTrue(temp);
3755 Py_DECREF(temp);
Guido van Rossum55f20992001-10-01 17:18:22 +00003756 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00003757 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003758 Py_DECREF(func);
Tim Petersea7f75d2002-12-07 21:39:16 +00003759 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003760}
3761
Guido van Rossumdc91b992001-08-08 22:26:22 +00003762SLOT0(slot_nb_invert, "__invert__")
3763SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
3764SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
3765SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
3766SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
3767SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003768
3769static int
3770slot_nb_coerce(PyObject **a, PyObject **b)
3771{
3772 static PyObject *coerce_str;
3773 PyObject *self = *a, *other = *b;
3774
3775 if (self->ob_type->tp_as_number != NULL &&
3776 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3777 PyObject *r;
3778 r = call_maybe(
3779 self, "__coerce__", &coerce_str, "(O)", other);
3780 if (r == NULL)
3781 return -1;
3782 if (r == Py_NotImplemented) {
3783 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003784 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003785 else {
3786 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3787 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003788 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00003789 Py_DECREF(r);
3790 return -1;
3791 }
3792 *a = PyTuple_GET_ITEM(r, 0);
3793 Py_INCREF(*a);
3794 *b = PyTuple_GET_ITEM(r, 1);
3795 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003796 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00003797 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003798 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003799 }
3800 if (other->ob_type->tp_as_number != NULL &&
3801 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3802 PyObject *r;
3803 r = call_maybe(
3804 other, "__coerce__", &coerce_str, "(O)", self);
3805 if (r == NULL)
3806 return -1;
3807 if (r == Py_NotImplemented) {
3808 Py_DECREF(r);
3809 return 1;
3810 }
3811 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3812 PyErr_SetString(PyExc_TypeError,
3813 "__coerce__ didn't return a 2-tuple");
3814 Py_DECREF(r);
3815 return -1;
3816 }
3817 *a = PyTuple_GET_ITEM(r, 1);
3818 Py_INCREF(*a);
3819 *b = PyTuple_GET_ITEM(r, 0);
3820 Py_INCREF(*b);
3821 Py_DECREF(r);
3822 return 0;
3823 }
3824 return 1;
3825}
3826
Guido van Rossumdc91b992001-08-08 22:26:22 +00003827SLOT0(slot_nb_int, "__int__")
3828SLOT0(slot_nb_long, "__long__")
3829SLOT0(slot_nb_float, "__float__")
3830SLOT0(slot_nb_oct, "__oct__")
3831SLOT0(slot_nb_hex, "__hex__")
3832SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
3833SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
3834SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
3835SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
3836SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003837SLOT1(slot_nb_inplace_power, "__ipow__", PyObject *, "O")
Guido van Rossumdc91b992001-08-08 22:26:22 +00003838SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
3839SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
3840SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
3841SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
3842SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
3843SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
3844 "__floordiv__", "__rfloordiv__")
3845SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
3846SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
3847SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003848
3849static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00003850half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003851{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003852 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003853 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003854 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003855
Guido van Rossum60718732001-08-28 17:47:51 +00003856 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003857 if (func == NULL) {
3858 PyErr_Clear();
3859 }
3860 else {
3861 args = Py_BuildValue("(O)", other);
3862 if (args == NULL)
3863 res = NULL;
3864 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003865 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003866 Py_DECREF(args);
3867 }
Raymond Hettingerab5dae32002-06-24 13:08:16 +00003868 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003869 if (res != Py_NotImplemented) {
3870 if (res == NULL)
3871 return -2;
3872 c = PyInt_AsLong(res);
3873 Py_DECREF(res);
3874 if (c == -1 && PyErr_Occurred())
3875 return -2;
3876 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
3877 }
3878 Py_DECREF(res);
3879 }
3880 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003881}
3882
Guido van Rossumab3b0342001-09-18 20:38:53 +00003883/* This slot is published for the benefit of try_3way_compare in object.c */
3884int
3885_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00003886{
3887 int c;
3888
Guido van Rossumab3b0342001-09-18 20:38:53 +00003889 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003890 c = half_compare(self, other);
3891 if (c <= 1)
3892 return c;
3893 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00003894 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003895 c = half_compare(other, self);
3896 if (c < -1)
3897 return -2;
3898 if (c <= 1)
3899 return -c;
3900 }
3901 return (void *)self < (void *)other ? -1 :
3902 (void *)self > (void *)other ? 1 : 0;
3903}
3904
3905static PyObject *
3906slot_tp_repr(PyObject *self)
3907{
3908 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003909 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003910
Guido van Rossum60718732001-08-28 17:47:51 +00003911 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003912 if (func != NULL) {
3913 res = PyEval_CallObject(func, NULL);
3914 Py_DECREF(func);
3915 return res;
3916 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00003917 PyErr_Clear();
3918 return PyString_FromFormat("<%s object at %p>",
3919 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003920}
3921
3922static PyObject *
3923slot_tp_str(PyObject *self)
3924{
3925 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003926 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003927
Guido van Rossum60718732001-08-28 17:47:51 +00003928 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003929 if (func != NULL) {
3930 res = PyEval_CallObject(func, NULL);
3931 Py_DECREF(func);
3932 return res;
3933 }
3934 else {
3935 PyErr_Clear();
3936 return slot_tp_repr(self);
3937 }
3938}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003939
3940static long
3941slot_tp_hash(PyObject *self)
3942{
Tim Peters61ce0a92002-12-06 23:38:02 +00003943 PyObject *func;
Guido van Rossum60718732001-08-28 17:47:51 +00003944 static PyObject *hash_str, *eq_str, *cmp_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003945 long h;
3946
Guido van Rossum60718732001-08-28 17:47:51 +00003947 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003948
3949 if (func != NULL) {
Tim Peters61ce0a92002-12-06 23:38:02 +00003950 PyObject *res = PyEval_CallObject(func, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003951 Py_DECREF(func);
3952 if (res == NULL)
3953 return -1;
3954 h = PyInt_AsLong(res);
Tim Peters61ce0a92002-12-06 23:38:02 +00003955 Py_DECREF(res);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003956 }
3957 else {
3958 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003959 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003960 if (func == NULL) {
3961 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003962 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003963 }
3964 if (func != NULL) {
3965 Py_DECREF(func);
3966 PyErr_SetString(PyExc_TypeError, "unhashable type");
3967 return -1;
3968 }
3969 PyErr_Clear();
3970 h = _Py_HashPointer((void *)self);
3971 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003972 if (h == -1 && !PyErr_Occurred())
3973 h = -2;
3974 return h;
3975}
3976
3977static PyObject *
3978slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
3979{
Guido van Rossum60718732001-08-28 17:47:51 +00003980 static PyObject *call_str;
3981 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003982 PyObject *res;
3983
3984 if (meth == NULL)
3985 return NULL;
3986 res = PyObject_Call(meth, args, kwds);
3987 Py_DECREF(meth);
3988 return res;
3989}
3990
Guido van Rossum14a6f832001-10-17 13:59:09 +00003991/* There are two slot dispatch functions for tp_getattro.
3992
3993 - slot_tp_getattro() is used when __getattribute__ is overridden
3994 but no __getattr__ hook is present;
3995
3996 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
3997
Guido van Rossumc334df52002-04-04 23:44:47 +00003998 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
3999 detects the absence of __getattr__ and then installs the simpler slot if
4000 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00004001
Tim Peters6d6c1a32001-08-02 04:15:00 +00004002static PyObject *
4003slot_tp_getattro(PyObject *self, PyObject *name)
4004{
Guido van Rossum14a6f832001-10-17 13:59:09 +00004005 static PyObject *getattribute_str = NULL;
4006 return call_method(self, "__getattribute__", &getattribute_str,
4007 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004008}
4009
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004010static PyObject *
4011slot_tp_getattr_hook(PyObject *self, PyObject *name)
4012{
4013 PyTypeObject *tp = self->ob_type;
4014 PyObject *getattr, *getattribute, *res;
4015 static PyObject *getattribute_str = NULL;
4016 static PyObject *getattr_str = NULL;
4017
4018 if (getattr_str == NULL) {
4019 getattr_str = PyString_InternFromString("__getattr__");
4020 if (getattr_str == NULL)
4021 return NULL;
4022 }
4023 if (getattribute_str == NULL) {
4024 getattribute_str =
4025 PyString_InternFromString("__getattribute__");
4026 if (getattribute_str == NULL)
4027 return NULL;
4028 }
4029 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004030 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004031 /* No __getattr__ hook: use a simpler dispatcher */
4032 tp->tp_getattro = slot_tp_getattro;
4033 return slot_tp_getattro(self, name);
4034 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004035 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004036 if (getattribute == NULL ||
4037 (getattribute->ob_type == &PyWrapperDescr_Type &&
4038 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
4039 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004040 res = PyObject_GenericGetAttr(self, name);
4041 else
4042 res = PyObject_CallFunction(getattribute, "OO", self, name);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004043 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004044 PyErr_Clear();
4045 res = PyObject_CallFunction(getattr, "OO", self, name);
4046 }
4047 return res;
4048}
4049
Tim Peters6d6c1a32001-08-02 04:15:00 +00004050static int
4051slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
4052{
4053 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004054 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004055
4056 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004057 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004058 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004059 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004060 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004061 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004062 if (res == NULL)
4063 return -1;
4064 Py_DECREF(res);
4065 return 0;
4066}
4067
4068/* Map rich comparison operators to their __xx__ namesakes */
4069static char *name_op[] = {
4070 "__lt__",
4071 "__le__",
4072 "__eq__",
4073 "__ne__",
4074 "__gt__",
4075 "__ge__",
4076};
4077
4078static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00004079half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004080{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004081 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004082 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00004083
Guido van Rossum60718732001-08-28 17:47:51 +00004084 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004085 if (func == NULL) {
4086 PyErr_Clear();
4087 Py_INCREF(Py_NotImplemented);
4088 return Py_NotImplemented;
4089 }
4090 args = Py_BuildValue("(O)", other);
4091 if (args == NULL)
4092 res = NULL;
4093 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004094 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004095 Py_DECREF(args);
4096 }
4097 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004098 return res;
4099}
4100
Guido van Rossumb8f63662001-08-15 23:57:02 +00004101/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
4102static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
4103
4104static PyObject *
4105slot_tp_richcompare(PyObject *self, PyObject *other, int op)
4106{
4107 PyObject *res;
4108
4109 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
4110 res = half_richcompare(self, other, op);
4111 if (res != Py_NotImplemented)
4112 return res;
4113 Py_DECREF(res);
4114 }
4115 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
4116 res = half_richcompare(other, self, swapped_op[op]);
4117 if (res != Py_NotImplemented) {
4118 return res;
4119 }
4120 Py_DECREF(res);
4121 }
4122 Py_INCREF(Py_NotImplemented);
4123 return Py_NotImplemented;
4124}
4125
4126static PyObject *
4127slot_tp_iter(PyObject *self)
4128{
4129 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004130 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004131
Guido van Rossum60718732001-08-28 17:47:51 +00004132 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004133 if (func != NULL) {
Guido van Rossum84b2bed2002-08-16 17:01:09 +00004134 PyObject *args;
4135 args = res = PyTuple_New(0);
4136 if (args != NULL) {
4137 res = PyObject_Call(func, args, NULL);
4138 Py_DECREF(args);
4139 }
4140 Py_DECREF(func);
4141 return res;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004142 }
4143 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004144 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004145 if (func == NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00004146 PyErr_SetString(PyExc_TypeError,
4147 "iteration over non-sequence");
Guido van Rossumb8f63662001-08-15 23:57:02 +00004148 return NULL;
4149 }
4150 Py_DECREF(func);
4151 return PySeqIter_New(self);
4152}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004153
4154static PyObject *
4155slot_tp_iternext(PyObject *self)
4156{
Guido van Rossum2730b132001-08-28 18:22:14 +00004157 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00004158 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004159}
4160
Guido van Rossum1a493502001-08-17 16:47:50 +00004161static PyObject *
4162slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4163{
4164 PyTypeObject *tp = self->ob_type;
4165 PyObject *get;
4166 static PyObject *get_str = NULL;
4167
4168 if (get_str == NULL) {
4169 get_str = PyString_InternFromString("__get__");
4170 if (get_str == NULL)
4171 return NULL;
4172 }
4173 get = _PyType_Lookup(tp, get_str);
4174 if (get == NULL) {
4175 /* Avoid further slowdowns */
4176 if (tp->tp_descr_get == slot_tp_descr_get)
4177 tp->tp_descr_get = NULL;
4178 Py_INCREF(self);
4179 return self;
4180 }
Guido van Rossum2c252392001-08-24 10:13:31 +00004181 if (obj == NULL)
4182 obj = Py_None;
4183 if (type == NULL)
4184 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00004185 return PyObject_CallFunction(get, "OOO", self, obj, type);
4186}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004187
4188static int
4189slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
4190{
Guido van Rossum2c252392001-08-24 10:13:31 +00004191 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004192 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00004193
4194 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00004195 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004196 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00004197 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004198 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004199 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004200 if (res == NULL)
4201 return -1;
4202 Py_DECREF(res);
4203 return 0;
4204}
4205
4206static int
4207slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
4208{
Guido van Rossum60718732001-08-28 17:47:51 +00004209 static PyObject *init_str;
4210 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004211 PyObject *res;
4212
4213 if (meth == NULL)
4214 return -1;
4215 res = PyObject_Call(meth, args, kwds);
4216 Py_DECREF(meth);
4217 if (res == NULL)
4218 return -1;
4219 Py_DECREF(res);
4220 return 0;
4221}
4222
4223static PyObject *
4224slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4225{
Guido van Rossum7bed2132002-08-08 21:57:53 +00004226 static PyObject *new_str;
4227 PyObject *func;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004228 PyObject *newargs, *x;
4229 int i, n;
4230
Guido van Rossum7bed2132002-08-08 21:57:53 +00004231 if (new_str == NULL) {
4232 new_str = PyString_InternFromString("__new__");
4233 if (new_str == NULL)
4234 return NULL;
4235 }
4236 func = PyObject_GetAttr((PyObject *)type, new_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004237 if (func == NULL)
4238 return NULL;
4239 assert(PyTuple_Check(args));
4240 n = PyTuple_GET_SIZE(args);
4241 newargs = PyTuple_New(n+1);
4242 if (newargs == NULL)
4243 return NULL;
4244 Py_INCREF(type);
4245 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
4246 for (i = 0; i < n; i++) {
4247 x = PyTuple_GET_ITEM(args, i);
4248 Py_INCREF(x);
4249 PyTuple_SET_ITEM(newargs, i+1, x);
4250 }
4251 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00004252 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004253 Py_DECREF(func);
4254 return x;
4255}
4256
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004257static void
4258slot_tp_del(PyObject *self)
4259{
4260 static PyObject *del_str = NULL;
4261 PyObject *del, *res;
4262 PyObject *error_type, *error_value, *error_traceback;
4263
4264 /* Temporarily resurrect the object. */
4265 assert(self->ob_refcnt == 0);
4266 self->ob_refcnt = 1;
4267
4268 /* Save the current exception, if any. */
4269 PyErr_Fetch(&error_type, &error_value, &error_traceback);
4270
4271 /* Execute __del__ method, if any. */
4272 del = lookup_maybe(self, "__del__", &del_str);
4273 if (del != NULL) {
4274 res = PyEval_CallObject(del, NULL);
4275 if (res == NULL)
4276 PyErr_WriteUnraisable(del);
4277 else
4278 Py_DECREF(res);
4279 Py_DECREF(del);
4280 }
4281
4282 /* Restore the saved exception. */
4283 PyErr_Restore(error_type, error_value, error_traceback);
4284
4285 /* Undo the temporary resurrection; can't use DECREF here, it would
4286 * cause a recursive call.
4287 */
4288 assert(self->ob_refcnt > 0);
4289 if (--self->ob_refcnt == 0)
4290 return; /* this is the normal path out */
4291
4292 /* __del__ resurrected it! Make it look like the original Py_DECREF
4293 * never happened.
4294 */
4295 {
4296 int refcnt = self->ob_refcnt;
4297 _Py_NewReference(self);
4298 self->ob_refcnt = refcnt;
4299 }
4300 assert(!PyType_IS_GC(self->ob_type) ||
4301 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
4302 /* If Py_REF_DEBUG, the original decref dropped _Py_RefTotal, but
4303 * _Py_NewReference bumped it again, so that's a wash.
4304 * If Py_TRACE_REFS, _Py_NewReference re-added self to the object
4305 * chain, so no more to do there either.
4306 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
4307 * _Py_NewReference bumped tp_allocs: both of those need to be
4308 * undone.
4309 */
4310#ifdef COUNT_ALLOCS
4311 --self->ob_type->tp_frees;
4312 --self->ob_type->tp_allocs;
4313#endif
4314}
4315
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004316
4317/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
4318 functions. The offsets here are relative to the 'etype' structure, which
4319 incorporates the additional structures used for numbers, sequences and
4320 mappings. Note that multiple names may map to the same slot (e.g. __eq__,
4321 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00004322 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
4323 terminated with an all-zero entry. (This table is further initialized and
4324 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004325
Guido van Rossum6d204072001-10-21 00:44:31 +00004326typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004327
4328#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00004329#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004330#undef ETSLOT
4331#undef SQSLOT
4332#undef MPSLOT
4333#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00004334#undef UNSLOT
4335#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004336#undef BINSLOT
4337#undef RBINSLOT
4338
Guido van Rossum6d204072001-10-21 00:44:31 +00004339#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004340 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
4341 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00004342#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
4343 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004344 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00004345#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004346 {NAME, offsetof(etype, SLOT), (void *)(FUNCTION), WRAPPER, \
4347 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00004348#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4349 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
4350#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4351 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
4352#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4353 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
4354#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4355 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
4356 "x." NAME "() <==> " DOC)
4357#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4358 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
4359 "x." NAME "(y) <==> x" DOC "y")
4360#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
4361 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
4362 "x." NAME "(y) <==> x" DOC "y")
4363#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
4364 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
4365 "x." NAME "(y) <==> y" DOC "x")
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004366
4367static slotdef slotdefs[] = {
Guido van Rossum6d204072001-10-21 00:44:31 +00004368 SQSLOT("__len__", sq_length, slot_sq_length, wrap_inquiry,
4369 "x.__len__() <==> len(x)"),
4370 SQSLOT("__add__", sq_concat, slot_sq_concat, wrap_binaryfunc,
4371 "x.__add__(y) <==> x+y"),
4372 SQSLOT("__mul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
4373 "x.__mul__(n) <==> x*n"),
4374 SQSLOT("__rmul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
4375 "x.__rmul__(n) <==> n*x"),
4376 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
4377 "x.__getitem__(y) <==> x[y]"),
4378 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_intintargfunc,
4379 "x.__getslice__(i, j) <==> x[i:j]"),
4380 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
4381 "x.__setitem__(i, y) <==> x[i]=y"),
4382 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
4383 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004384 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Guido van Rossum6d204072001-10-21 00:44:31 +00004385 wrap_intintobjargproc,
4386 "x.__setslice__(i, j, y) <==> x[i:j]=y"),
4387 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
4388 "x.__delslice__(i, j) <==> del x[i:j]"),
4389 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
4390 "x.__contains__(y) <==> y in x"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004391 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat,
Guido van Rossum6d204072001-10-21 00:44:31 +00004392 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004393 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat,
Guido van Rossum6d204072001-10-21 00:44:31 +00004394 wrap_intargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004395
Guido van Rossum6d204072001-10-21 00:44:31 +00004396 MPSLOT("__len__", mp_length, slot_mp_length, wrap_inquiry,
4397 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00004398 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004399 wrap_binaryfunc,
4400 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004401 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004402 wrap_objobjargproc,
4403 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004404 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004405 wrap_delitem,
4406 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004407
Guido van Rossum6d204072001-10-21 00:44:31 +00004408 BINSLOT("__add__", nb_add, slot_nb_add,
4409 "+"),
4410 RBINSLOT("__radd__", nb_add, slot_nb_add,
4411 "+"),
4412 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
4413 "-"),
4414 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
4415 "-"),
4416 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
4417 "*"),
4418 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
4419 "*"),
4420 BINSLOT("__div__", nb_divide, slot_nb_divide,
4421 "/"),
4422 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
4423 "/"),
4424 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
4425 "%"),
4426 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
4427 "%"),
4428 BINSLOT("__divmod__", nb_divmod, slot_nb_divmod,
4429 "divmod(x, y)"),
4430 RBINSLOT("__rdivmod__", nb_divmod, slot_nb_divmod,
4431 "divmod(y, x)"),
4432 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
4433 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
4434 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
4435 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
4436 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
4437 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
4438 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
4439 "abs(x)"),
Guido van Rossumdfce3bf2002-03-10 14:11:16 +00004440 UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquiry,
Guido van Rossum6d204072001-10-21 00:44:31 +00004441 "x != 0"),
4442 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
4443 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
4444 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
4445 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
4446 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
4447 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
4448 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
4449 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
4450 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
4451 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
4452 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
4453 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
4454 "x.__coerce__(y) <==> coerce(x, y)"),
4455 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
4456 "int(x)"),
4457 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
4458 "long(x)"),
4459 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
4460 "float(x)"),
4461 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
4462 "oct(x)"),
4463 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
4464 "hex(x)"),
4465 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
4466 wrap_binaryfunc, "+"),
4467 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
4468 wrap_binaryfunc, "-"),
4469 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
4470 wrap_binaryfunc, "*"),
4471 IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
4472 wrap_binaryfunc, "/"),
4473 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
4474 wrap_binaryfunc, "%"),
4475 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
Guido van Rossum6e5680f2002-10-15 01:01:53 +00004476 wrap_binaryfunc, "**"),
Guido van Rossum6d204072001-10-21 00:44:31 +00004477 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
4478 wrap_binaryfunc, "<<"),
4479 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
4480 wrap_binaryfunc, ">>"),
4481 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
4482 wrap_binaryfunc, "&"),
4483 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
4484 wrap_binaryfunc, "^"),
4485 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
4486 wrap_binaryfunc, "|"),
4487 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
4488 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
4489 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
4490 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
4491 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
4492 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
4493 IBSLOT("__itruediv__", nb_inplace_true_divide,
4494 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004495
Guido van Rossum6d204072001-10-21 00:44:31 +00004496 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
4497 "x.__str__() <==> str(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00004498 TPSLOT("__str__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00004499 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
4500 "x.__repr__() <==> repr(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00004501 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00004502 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
4503 "x.__cmp__(y) <==> cmp(x,y)"),
4504 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
4505 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00004506 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
4507 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004508 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00004509 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
4510 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
4511 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
4512 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
4513 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
4514 "x.__setattr__('name', value) <==> x.name = value"),
4515 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
4516 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
4517 "x.__delattr__('name') <==> del x.name"),
4518 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
4519 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
4520 "x.__lt__(y) <==> x<y"),
4521 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
4522 "x.__le__(y) <==> x<=y"),
4523 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
4524 "x.__eq__(y) <==> x==y"),
4525 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
4526 "x.__ne__(y) <==> x!=y"),
4527 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
4528 "x.__gt__(y) <==> x>y"),
4529 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
4530 "x.__ge__(y) <==> x>=y"),
4531 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
4532 "x.__iter__() <==> iter(x)"),
4533 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
4534 "x.next() -> the next value, or raise StopIteration"),
4535 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
4536 "descr.__get__(obj[, type]) -> value"),
4537 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
4538 "descr.__set__(obj, value)"),
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004539 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
4540 wrap_descr_delete, "descr.__delete__(obj)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00004541 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00004542 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00004543 "see x.__class__.__doc__ for signature",
4544 PyWrapperFlag_KEYWORDS),
4545 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004546 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004547 {NULL}
4548};
4549
Guido van Rossumc334df52002-04-04 23:44:47 +00004550/* Given a type pointer and an offset gotten from a slotdef entry, return a
4551 pointer to the actual slot. This is not quite the same as simply adding
4552 the offset to the type pointer, since it takes care to indirect through the
4553 proper indirection pointer (as_buffer, etc.); it returns NULL if the
4554 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004555static void **
4556slotptr(PyTypeObject *type, int offset)
4557{
4558 char *ptr;
4559
Guido van Rossum09638c12002-06-13 19:17:46 +00004560 /* Note: this depends on the order of the members of etype! */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004561 assert(offset >= 0);
4562 assert(offset < offsetof(etype, as_buffer));
Guido van Rossum09638c12002-06-13 19:17:46 +00004563 if (offset >= offsetof(etype, as_sequence)) {
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004564 ptr = (void *)type->tp_as_sequence;
4565 offset -= offsetof(etype, as_sequence);
4566 }
Guido van Rossum09638c12002-06-13 19:17:46 +00004567 else if (offset >= offsetof(etype, as_mapping)) {
4568 ptr = (void *)type->tp_as_mapping;
4569 offset -= offsetof(etype, as_mapping);
4570 }
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004571 else if (offset >= offsetof(etype, as_number)) {
4572 ptr = (void *)type->tp_as_number;
4573 offset -= offsetof(etype, as_number);
4574 }
4575 else {
4576 ptr = (void *)type;
4577 }
4578 if (ptr != NULL)
4579 ptr += offset;
4580 return (void **)ptr;
4581}
Guido van Rossumf040ede2001-08-07 16:40:56 +00004582
Guido van Rossumc334df52002-04-04 23:44:47 +00004583/* Length of array of slotdef pointers used to store slots with the
4584 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
4585 the same __name__, for any __name__. Since that's a static property, it is
4586 appropriate to declare fixed-size arrays for this. */
4587#define MAX_EQUIV 10
4588
4589/* Return a slot pointer for a given name, but ONLY if the attribute has
4590 exactly one slot function. The name must be an interned string. */
4591static void **
4592resolve_slotdups(PyTypeObject *type, PyObject *name)
4593{
4594 /* XXX Maybe this could be optimized more -- but is it worth it? */
4595
4596 /* pname and ptrs act as a little cache */
4597 static PyObject *pname;
4598 static slotdef *ptrs[MAX_EQUIV];
4599 slotdef *p, **pp;
4600 void **res, **ptr;
4601
4602 if (pname != name) {
4603 /* Collect all slotdefs that match name into ptrs. */
4604 pname = name;
4605 pp = ptrs;
4606 for (p = slotdefs; p->name_strobj; p++) {
4607 if (p->name_strobj == name)
4608 *pp++ = p;
4609 }
4610 *pp = NULL;
4611 }
4612
4613 /* Look in all matching slots of the type; if exactly one of these has
4614 a filled-in slot, return its value. Otherwise return NULL. */
4615 res = NULL;
4616 for (pp = ptrs; *pp; pp++) {
4617 ptr = slotptr(type, (*pp)->offset);
4618 if (ptr == NULL || *ptr == NULL)
4619 continue;
4620 if (res != NULL)
4621 return NULL;
4622 res = ptr;
4623 }
4624 return res;
4625}
4626
4627/* Common code for update_these_slots() and fixup_slot_dispatchers(). This
4628 does some incredibly complex thinking and then sticks something into the
4629 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
4630 interests, and then stores a generic wrapper or a specific function into
4631 the slot.) Return a pointer to the next slotdef with a different offset,
4632 because that's convenient for fixup_slot_dispatchers(). */
4633static slotdef *
4634update_one_slot(PyTypeObject *type, slotdef *p)
4635{
4636 PyObject *descr;
4637 PyWrapperDescrObject *d;
4638 void *generic = NULL, *specific = NULL;
4639 int use_generic = 0;
4640 int offset = p->offset;
4641 void **ptr = slotptr(type, offset);
4642
4643 if (ptr == NULL) {
4644 do {
4645 ++p;
4646 } while (p->offset == offset);
4647 return p;
4648 }
4649 do {
4650 descr = _PyType_Lookup(type, p->name_strobj);
4651 if (descr == NULL)
4652 continue;
4653 if (descr->ob_type == &PyWrapperDescr_Type) {
4654 void **tptr = resolve_slotdups(type, p->name_strobj);
4655 if (tptr == NULL || tptr == ptr)
4656 generic = p->function;
4657 d = (PyWrapperDescrObject *)descr;
4658 if (d->d_base->wrapper == p->wrapper &&
4659 PyType_IsSubtype(type, d->d_type))
4660 {
4661 if (specific == NULL ||
4662 specific == d->d_wrapped)
4663 specific = d->d_wrapped;
4664 else
4665 use_generic = 1;
4666 }
4667 }
Guido van Rossum721f62e2002-08-09 02:14:34 +00004668 else if (descr->ob_type == &PyCFunction_Type &&
4669 PyCFunction_GET_FUNCTION(descr) ==
4670 (PyCFunction)tp_new_wrapper &&
4671 strcmp(p->name, "__new__") == 0)
4672 {
4673 /* The __new__ wrapper is not a wrapper descriptor,
4674 so must be special-cased differently.
4675 If we don't do this, creating an instance will
4676 always use slot_tp_new which will look up
4677 __new__ in the MRO which will call tp_new_wrapper
4678 which will look through the base classes looking
4679 for a static base and call its tp_new (usually
4680 PyType_GenericNew), after performing various
4681 sanity checks and constructing a new argument
4682 list. Cut all that nonsense short -- this speeds
4683 up instance creation tremendously. */
4684 specific = type->tp_new;
4685 /* XXX I'm not 100% sure that there isn't a hole
4686 in this reasoning that requires additional
4687 sanity checks. I'll buy the first person to
4688 point out a bug in this reasoning a beer. */
4689 }
Guido van Rossumc334df52002-04-04 23:44:47 +00004690 else {
4691 use_generic = 1;
4692 generic = p->function;
4693 }
4694 } while ((++p)->offset == offset);
4695 if (specific && !use_generic)
4696 *ptr = specific;
4697 else
4698 *ptr = generic;
4699 return p;
4700}
4701
Guido van Rossum22b13872002-08-06 21:41:44 +00004702static int recurse_down_subclasses(PyTypeObject *type, slotdef **pp,
Jeremy Hylton938ace62002-07-17 16:30:39 +00004703 PyObject *name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004704
Guido van Rossumc334df52002-04-04 23:44:47 +00004705/* In the type, update the slots whose slotdefs are gathered in the pp0 array,
4706 and then do the same for all this type's subtypes. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004707static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004708update_these_slots(PyTypeObject *type, slotdef **pp0, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004709{
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004710 slotdef **pp;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004711
Guido van Rossumc334df52002-04-04 23:44:47 +00004712 for (pp = pp0; *pp; pp++)
4713 update_one_slot(type, *pp);
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004714 return recurse_down_subclasses(type, pp0, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004715}
4716
Guido van Rossumc334df52002-04-04 23:44:47 +00004717/* Update the slots whose slotdefs are gathered in the pp array in all (direct
4718 or indirect) subclasses of type. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004719static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004720recurse_down_subclasses(PyTypeObject *type, slotdef **pp, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004721{
4722 PyTypeObject *subclass;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004723 PyObject *ref, *subclasses, *dict;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004724 int i, n;
4725
4726 subclasses = type->tp_subclasses;
4727 if (subclasses == NULL)
4728 return 0;
4729 assert(PyList_Check(subclasses));
4730 n = PyList_GET_SIZE(subclasses);
4731 for (i = 0; i < n; i++) {
4732 ref = PyList_GET_ITEM(subclasses, i);
4733 assert(PyWeakref_CheckRef(ref));
4734 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
Guido van Rossum59e6c532002-06-14 02:27:07 +00004735 assert(subclass != NULL);
4736 if ((PyObject *)subclass == Py_None)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004737 continue;
4738 assert(PyType_Check(subclass));
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004739 /* Avoid recursing down into unaffected classes */
4740 dict = subclass->tp_dict;
4741 if (dict != NULL && PyDict_Check(dict) &&
4742 PyDict_GetItem(dict, name) != NULL)
4743 continue;
4744 if (update_these_slots(subclass, pp, name) < 0)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004745 return -1;
4746 }
4747 return 0;
4748}
4749
Guido van Rossumc334df52002-04-04 23:44:47 +00004750/* Comparison function for qsort() to compare slotdefs by their offset, and
4751 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004752static int
4753slotdef_cmp(const void *aa, const void *bb)
4754{
4755 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
4756 int c = a->offset - b->offset;
4757 if (c != 0)
4758 return c;
4759 else
4760 return a - b;
4761}
4762
Guido van Rossumc334df52002-04-04 23:44:47 +00004763/* Initialize the slotdefs table by adding interned string objects for the
4764 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004765static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004766init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004767{
4768 slotdef *p;
4769 static int initialized = 0;
4770
4771 if (initialized)
4772 return;
4773 for (p = slotdefs; p->name; p++) {
4774 p->name_strobj = PyString_InternFromString(p->name);
4775 if (!p->name_strobj)
Guido van Rossumc334df52002-04-04 23:44:47 +00004776 Py_FatalError("Out of memory interning slotdef names");
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004777 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004778 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
4779 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004780 initialized = 1;
4781}
4782
Guido van Rossumc334df52002-04-04 23:44:47 +00004783/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004784static int
4785update_slot(PyTypeObject *type, PyObject *name)
4786{
Guido van Rossumc334df52002-04-04 23:44:47 +00004787 slotdef *ptrs[MAX_EQUIV];
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004788 slotdef *p;
4789 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004790 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004791
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004792 init_slotdefs();
4793 pp = ptrs;
4794 for (p = slotdefs; p->name; p++) {
4795 /* XXX assume name is interned! */
4796 if (p->name_strobj == name)
4797 *pp++ = p;
4798 }
4799 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004800 for (pp = ptrs; *pp; pp++) {
4801 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004802 offset = p->offset;
4803 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004804 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004805 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004806 }
Guido van Rossumc334df52002-04-04 23:44:47 +00004807 if (ptrs[0] == NULL)
4808 return 0; /* Not an attribute that affects any slots */
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004809 return update_these_slots(type, ptrs, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004810}
4811
Guido van Rossumc334df52002-04-04 23:44:47 +00004812/* Store the proper functions in the slot dispatches at class (type)
4813 definition time, based upon which operations the class overrides in its
4814 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004815static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004816fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004817{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004818 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004819
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004820 init_slotdefs();
Guido van Rossumc334df52002-04-04 23:44:47 +00004821 for (p = slotdefs; p->name; )
4822 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004823}
Guido van Rossum705f0f52001-08-24 16:47:00 +00004824
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004825static void
4826update_all_slots(PyTypeObject* type)
4827{
4828 slotdef *p;
4829
4830 init_slotdefs();
4831 for (p = slotdefs; p->name; p++) {
4832 /* update_slot returns int but can't actually fail */
4833 update_slot(type, p->name_strobj);
4834 }
4835}
4836
Guido van Rossum6d204072001-10-21 00:44:31 +00004837/* This function is called by PyType_Ready() to populate the type's
4838 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00004839 function slot (like tp_repr) that's defined in the type, one or more
4840 corresponding descriptors are added in the type's tp_dict dictionary
4841 under the appropriate name (like __repr__). Some function slots
4842 cause more than one descriptor to be added (for example, the nb_add
4843 slot adds both __add__ and __radd__ descriptors) and some function
4844 slots compete for the same descriptor (for example both sq_item and
4845 mp_subscript generate a __getitem__ descriptor).
4846
4847 In the latter case, the first slotdef entry encoutered wins. Since
4848 slotdef entries are sorted by the offset of the slot in the etype
4849 struct, this gives us some control over disambiguating between
4850 competing slots: the members of struct etype are listed from most
4851 general to least general, so the most general slot is preferred. In
4852 particular, because as_mapping comes before as_sequence, for a type
4853 that defines both mp_subscript and sq_item, mp_subscript wins.
4854
4855 This only adds new descriptors and doesn't overwrite entries in
4856 tp_dict that were previously defined. The descriptors contain a
4857 reference to the C function they must call, so that it's safe if they
4858 are copied into a subtype's __dict__ and the subtype has a different
4859 C function in its slot -- calling the method defined by the
4860 descriptor will call the C function that was used to create it,
4861 rather than the C function present in the slot when it is called.
4862 (This is important because a subtype may have a C function in the
4863 slot that calls the method from the dictionary, and we want to avoid
4864 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00004865
4866static int
4867add_operators(PyTypeObject *type)
4868{
4869 PyObject *dict = type->tp_dict;
4870 slotdef *p;
4871 PyObject *descr;
4872 void **ptr;
4873
4874 init_slotdefs();
4875 for (p = slotdefs; p->name; p++) {
4876 if (p->wrapper == NULL)
4877 continue;
4878 ptr = slotptr(type, p->offset);
4879 if (!ptr || !*ptr)
4880 continue;
4881 if (PyDict_GetItem(dict, p->name_strobj))
4882 continue;
4883 descr = PyDescr_NewWrapper(type, p, *ptr);
4884 if (descr == NULL)
4885 return -1;
4886 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
4887 return -1;
4888 Py_DECREF(descr);
4889 }
4890 if (type->tp_new != NULL) {
4891 if (add_tp_new_wrapper(type) < 0)
4892 return -1;
4893 }
4894 return 0;
4895}
4896
Guido van Rossum705f0f52001-08-24 16:47:00 +00004897
4898/* Cooperative 'super' */
4899
4900typedef struct {
4901 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00004902 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004903 PyObject *obj;
4904} superobject;
4905
Guido van Rossum6f799372001-09-20 20:46:19 +00004906static PyMemberDef super_members[] = {
4907 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
4908 "the class invoking super()"},
4909 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
4910 "the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004911 {0}
4912};
4913
Guido van Rossum705f0f52001-08-24 16:47:00 +00004914static void
4915super_dealloc(PyObject *self)
4916{
4917 superobject *su = (superobject *)self;
4918
Guido van Rossum048eb752001-10-02 21:24:57 +00004919 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00004920 Py_XDECREF(su->obj);
4921 Py_XDECREF(su->type);
4922 self->ob_type->tp_free(self);
4923}
4924
4925static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004926super_repr(PyObject *self)
4927{
4928 superobject *su = (superobject *)self;
4929
4930 if (su->obj)
4931 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00004932 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004933 su->type ? su->type->tp_name : "NULL",
4934 su->obj->ob_type->tp_name);
4935 else
4936 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00004937 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004938 su->type ? su->type->tp_name : "NULL");
4939}
4940
4941static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00004942super_getattro(PyObject *self, PyObject *name)
4943{
4944 superobject *su = (superobject *)self;
4945
4946 if (su->obj != NULL) {
Tim Petersa91e9642001-11-14 23:32:33 +00004947 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum155db9a2002-04-02 17:53:47 +00004948 PyTypeObject *starttype;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004949 descrgetfunc f;
4950 int i, n;
4951
Guido van Rossum155db9a2002-04-02 17:53:47 +00004952 starttype = su->obj->ob_type;
4953 mro = starttype->tp_mro;
4954
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004955 if (mro == NULL)
4956 n = 0;
4957 else {
4958 assert(PyTuple_Check(mro));
4959 n = PyTuple_GET_SIZE(mro);
4960 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004961 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00004962 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00004963 break;
4964 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004965 if (i >= n && PyType_Check(su->obj)) {
Guido van Rossum155db9a2002-04-02 17:53:47 +00004966 starttype = (PyTypeObject *)(su->obj);
4967 mro = starttype->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004968 if (mro == NULL)
4969 n = 0;
4970 else {
4971 assert(PyTuple_Check(mro));
4972 n = PyTuple_GET_SIZE(mro);
4973 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004974 for (i = 0; i < n; i++) {
4975 if ((PyObject *)(su->type) ==
4976 PyTuple_GET_ITEM(mro, i))
4977 break;
4978 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004979 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004980 i++;
4981 res = NULL;
4982 for (; i < n; i++) {
4983 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00004984 if (PyType_Check(tmp))
4985 dict = ((PyTypeObject *)tmp)->tp_dict;
4986 else if (PyClass_Check(tmp))
4987 dict = ((PyClassObject *)tmp)->cl_dict;
4988 else
4989 continue;
4990 res = PyDict_GetItem(dict, name);
Guido van Rossum5b443c62001-12-03 15:38:28 +00004991 if (res != NULL && !PyDescr_IsData(res)) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00004992 Py_INCREF(res);
4993 f = res->ob_type->tp_descr_get;
4994 if (f != NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00004995 tmp = f(res, su->obj,
4996 (PyObject *)starttype);
Guido van Rossum705f0f52001-08-24 16:47:00 +00004997 Py_DECREF(res);
4998 res = tmp;
4999 }
5000 return res;
5001 }
5002 }
5003 }
5004 return PyObject_GenericGetAttr(self, name);
5005}
5006
Guido van Rossum5b443c62001-12-03 15:38:28 +00005007static int
5008supercheck(PyTypeObject *type, PyObject *obj)
5009{
5010 if (!PyType_IsSubtype(obj->ob_type, type) &&
5011 !(PyType_Check(obj) &&
5012 PyType_IsSubtype((PyTypeObject *)obj, type))) {
5013 PyErr_SetString(PyExc_TypeError,
5014 "super(type, obj): "
5015 "obj must be an instance or subtype of type");
5016 return -1;
5017 }
5018 else
5019 return 0;
5020}
5021
Guido van Rossum705f0f52001-08-24 16:47:00 +00005022static PyObject *
5023super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5024{
5025 superobject *su = (superobject *)self;
5026 superobject *new;
5027
5028 if (obj == NULL || obj == Py_None || su->obj != NULL) {
5029 /* Not binding to an object, or already bound */
5030 Py_INCREF(self);
5031 return self;
5032 }
Guido van Rossum5b443c62001-12-03 15:38:28 +00005033 if (su->ob_type != &PySuper_Type)
5034 /* If su is an instance of a subclass of super,
5035 call its type */
5036 return PyObject_CallFunction((PyObject *)su->ob_type,
5037 "OO", su->type, obj);
5038 else {
5039 /* Inline the common case */
5040 if (supercheck(su->type, obj) < 0)
5041 return NULL;
5042 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
5043 NULL, NULL);
5044 if (new == NULL)
5045 return NULL;
5046 Py_INCREF(su->type);
5047 Py_INCREF(obj);
5048 new->type = su->type;
5049 new->obj = obj;
5050 return (PyObject *)new;
5051 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005052}
5053
5054static int
5055super_init(PyObject *self, PyObject *args, PyObject *kwds)
5056{
5057 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00005058 PyTypeObject *type;
5059 PyObject *obj = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005060
5061 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
5062 return -1;
5063 if (obj == Py_None)
5064 obj = NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005065 if (obj != NULL && supercheck(type, obj) < 0)
Guido van Rossum705f0f52001-08-24 16:47:00 +00005066 return -1;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005067 Py_INCREF(type);
5068 Py_XINCREF(obj);
5069 su->type = type;
5070 su->obj = obj;
5071 return 0;
5072}
5073
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005074PyDoc_STRVAR(super_doc,
Guido van Rossum705f0f52001-08-24 16:47:00 +00005075"super(type) -> unbound super object\n"
5076"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00005077"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00005078"Typical use to call a cooperative superclass method:\n"
5079"class C(B):\n"
5080" def meth(self, arg):\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005081" super(C, self).meth(arg)");
Guido van Rossum705f0f52001-08-24 16:47:00 +00005082
Guido van Rossum048eb752001-10-02 21:24:57 +00005083static int
5084super_traverse(PyObject *self, visitproc visit, void *arg)
5085{
5086 superobject *su = (superobject *)self;
5087 int err;
5088
5089#define VISIT(SLOT) \
5090 if (SLOT) { \
5091 err = visit((PyObject *)(SLOT), arg); \
5092 if (err) \
5093 return err; \
5094 }
5095
5096 VISIT(su->obj);
5097 VISIT(su->type);
5098
5099#undef VISIT
5100
5101 return 0;
5102}
5103
Guido van Rossum705f0f52001-08-24 16:47:00 +00005104PyTypeObject PySuper_Type = {
5105 PyObject_HEAD_INIT(&PyType_Type)
5106 0, /* ob_size */
5107 "super", /* tp_name */
5108 sizeof(superobject), /* tp_basicsize */
5109 0, /* tp_itemsize */
5110 /* methods */
5111 super_dealloc, /* tp_dealloc */
5112 0, /* tp_print */
5113 0, /* tp_getattr */
5114 0, /* tp_setattr */
5115 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005116 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005117 0, /* tp_as_number */
5118 0, /* tp_as_sequence */
5119 0, /* tp_as_mapping */
5120 0, /* tp_hash */
5121 0, /* tp_call */
5122 0, /* tp_str */
5123 super_getattro, /* tp_getattro */
5124 0, /* tp_setattro */
5125 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00005126 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
5127 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005128 super_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00005129 super_traverse, /* tp_traverse */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005130 0, /* tp_clear */
5131 0, /* tp_richcompare */
5132 0, /* tp_weaklistoffset */
5133 0, /* tp_iter */
5134 0, /* tp_iternext */
5135 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005136 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005137 0, /* tp_getset */
5138 0, /* tp_base */
5139 0, /* tp_dict */
5140 super_descr_get, /* tp_descr_get */
5141 0, /* tp_descr_set */
5142 0, /* tp_dictoffset */
5143 super_init, /* tp_init */
5144 PyType_GenericAlloc, /* tp_alloc */
5145 PyType_GenericNew, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00005146 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005147};