blob: 93f34ed1f9c15f68f0e69ee719394085f6a9126f [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
Guido van Rossum6f799372001-09-20 20:46:19 +00008static PyMemberDef type_members[] = {
Tim Peters6d6c1a32001-08-02 04:15:00 +00009 {"__basicsize__", T_INT, offsetof(PyTypeObject,tp_basicsize),READONLY},
10 {"__itemsize__", T_INT, offsetof(PyTypeObject, tp_itemsize), READONLY},
11 {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY},
Guido van Rossum9676b222001-08-17 20:32:36 +000012 {"__weakrefoffset__", T_LONG,
Tim Peters6d6c1a32001-08-02 04:15:00 +000013 offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
14 {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY},
15 {"__dictoffset__", T_LONG,
16 offsetof(PyTypeObject, tp_dictoffset), READONLY},
Tim Peters6d6c1a32001-08-02 04:15:00 +000017 {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY},
18 {0}
19};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000020
Guido van Rossumc0b618a1997-05-02 03:12:38 +000021static PyObject *
Guido van Rossumc3542212001-08-16 09:18:56 +000022type_name(PyTypeObject *type, void *context)
23{
24 char *s;
25
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +000026 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
Guido van Rossume5c691a2003-03-07 15:13:17 +000027 PyHeapTypeObject* et = (PyHeapTypeObject*)type;
Tim Petersea7f75d2002-12-07 21:39:16 +000028
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +000029 Py_INCREF(et->name);
30 return et->name;
31 }
32 else {
33 s = strrchr(type->tp_name, '.');
34 if (s == NULL)
35 s = type->tp_name;
36 else
37 s++;
38 return PyString_FromString(s);
39 }
Guido van Rossumc3542212001-08-16 09:18:56 +000040}
41
Michael W. Hudson98bbc492002-11-26 14:47:27 +000042static int
43type_set_name(PyTypeObject *type, PyObject *value, void *context)
44{
Guido van Rossume5c691a2003-03-07 15:13:17 +000045 PyHeapTypeObject* et;
Michael W. Hudson98bbc492002-11-26 14:47:27 +000046
47 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
48 PyErr_Format(PyExc_TypeError,
49 "can't set %s.__name__", type->tp_name);
50 return -1;
51 }
52 if (!value) {
53 PyErr_Format(PyExc_TypeError,
54 "can't delete %s.__name__", type->tp_name);
55 return -1;
56 }
57 if (!PyString_Check(value)) {
58 PyErr_Format(PyExc_TypeError,
59 "can only assign string to %s.__name__, not '%s'",
60 type->tp_name, value->ob_type->tp_name);
61 return -1;
62 }
Tim Petersea7f75d2002-12-07 21:39:16 +000063 if (strlen(PyString_AS_STRING(value))
Michael W. Hudson98bbc492002-11-26 14:47:27 +000064 != (size_t)PyString_GET_SIZE(value)) {
65 PyErr_Format(PyExc_ValueError,
66 "__name__ must not contain null bytes");
67 return -1;
68 }
69
Guido van Rossume5c691a2003-03-07 15:13:17 +000070 et = (PyHeapTypeObject*)type;
Michael W. Hudson98bbc492002-11-26 14:47:27 +000071
72 Py_INCREF(value);
73
74 Py_DECREF(et->name);
75 et->name = value;
76
77 type->tp_name = PyString_AS_STRING(value);
78
79 return 0;
80}
81
Guido van Rossumc3542212001-08-16 09:18:56 +000082static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +000083type_module(PyTypeObject *type, void *context)
Guido van Rossum29ca26e1995-01-07 11:58:15 +000084{
Guido van Rossumc3542212001-08-16 09:18:56 +000085 PyObject *mod;
86 char *s;
87
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +000088 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
89 mod = PyDict_GetItemString(type->tp_dict, "__module__");
90 Py_XINCREF(mod);
Guido van Rossumc3542212001-08-16 09:18:56 +000091 return mod;
92 }
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +000093 else {
94 s = strrchr(type->tp_name, '.');
95 if (s != NULL)
96 return PyString_FromStringAndSize(
97 type->tp_name, (int)(s - type->tp_name));
98 return PyString_FromString("__builtin__");
99 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000100}
101
Guido van Rossum3926a632001-09-25 16:25:58 +0000102static int
103type_set_module(PyTypeObject *type, PyObject *value, void *context)
104{
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000105 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
Guido van Rossum3926a632001-09-25 16:25:58 +0000106 PyErr_Format(PyExc_TypeError,
107 "can't set %s.__module__", type->tp_name);
108 return -1;
109 }
110 if (!value) {
111 PyErr_Format(PyExc_TypeError,
112 "can't delete %s.__module__", type->tp_name);
113 return -1;
114 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000115
Guido van Rossum3926a632001-09-25 16:25:58 +0000116 return PyDict_SetItemString(type->tp_dict, "__module__", value);
117}
118
Tim Peters6d6c1a32001-08-02 04:15:00 +0000119static PyObject *
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000120type_get_bases(PyTypeObject *type, void *context)
121{
122 Py_INCREF(type->tp_bases);
123 return type->tp_bases;
124}
125
126static PyTypeObject *best_base(PyObject *);
127static int mro_internal(PyTypeObject *);
128static int compatible_for_assignment(PyTypeObject *, PyTypeObject *, char *);
129static int add_subclass(PyTypeObject*, PyTypeObject*);
130static void remove_subclass(PyTypeObject *, PyTypeObject *);
131static void update_all_slots(PyTypeObject *);
132
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000133typedef int (*update_callback)(PyTypeObject *, void *);
134static int update_subclasses(PyTypeObject *type, PyObject *name,
135 update_callback callback, void *data);
136static int recurse_down_subclasses(PyTypeObject *type, PyObject *name,
137 update_callback callback, void *data);
138
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000139static int
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000140mro_subclasses(PyTypeObject *type, PyObject* temp)
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000141{
142 PyTypeObject *subclass;
143 PyObject *ref, *subclasses, *old_mro;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000144 int i, n;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000145
146 subclasses = type->tp_subclasses;
147 if (subclasses == NULL)
148 return 0;
149 assert(PyList_Check(subclasses));
150 n = PyList_GET_SIZE(subclasses);
151 for (i = 0; i < n; i++) {
152 ref = PyList_GET_ITEM(subclasses, i);
153 assert(PyWeakref_CheckRef(ref));
154 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
155 assert(subclass != NULL);
156 if ((PyObject *)subclass == Py_None)
157 continue;
158 assert(PyType_Check(subclass));
159 old_mro = subclass->tp_mro;
160 if (mro_internal(subclass) < 0) {
161 subclass->tp_mro = old_mro;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000162 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000163 }
164 else {
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000165 PyObject* tuple;
166 tuple = Py_BuildValue("OO", subclass, old_mro);
Guido van Rossum19a02ba2003-04-15 22:09:45 +0000167 Py_DECREF(old_mro);
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000168 if (!tuple)
169 return -1;
170 if (PyList_Append(temp, tuple) < 0)
171 return -1;
Guido van Rossum19a02ba2003-04-15 22:09:45 +0000172 Py_DECREF(tuple);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000173 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000174 if (mro_subclasses(subclass, temp) < 0)
175 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000176 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000177 return 0;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000178}
179
180static int
181type_set_bases(PyTypeObject *type, PyObject *value, void *context)
182{
183 int i, r = 0;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000184 PyObject *ob, *temp;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000185 PyTypeObject *new_base, *old_base;
186 PyObject *old_bases, *old_mro;
187
188 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
189 PyErr_Format(PyExc_TypeError,
190 "can't set %s.__bases__", type->tp_name);
191 return -1;
192 }
193 if (!value) {
194 PyErr_Format(PyExc_TypeError,
195 "can't delete %s.__bases__", type->tp_name);
196 return -1;
197 }
198 if (!PyTuple_Check(value)) {
199 PyErr_Format(PyExc_TypeError,
200 "can only assign tuple to %s.__bases__, not %s",
201 type->tp_name, value->ob_type->tp_name);
202 return -1;
203 }
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +0000204 if (PyTuple_GET_SIZE(value) == 0) {
205 PyErr_Format(PyExc_TypeError,
206 "can only assign non-empty tuple to %s.__bases__, not ()",
207 type->tp_name);
208 return -1;
209 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000210 for (i = 0; i < PyTuple_GET_SIZE(value); i++) {
211 ob = PyTuple_GET_ITEM(value, i);
212 if (!PyClass_Check(ob) && !PyType_Check(ob)) {
213 PyErr_Format(
214 PyExc_TypeError,
215 "%s.__bases__ must be tuple of old- or new-style classes, not '%s'",
216 type->tp_name, ob->ob_type->tp_name);
217 return -1;
218 }
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +0000219 if (PyType_Check(ob)) {
220 if (PyType_IsSubtype((PyTypeObject*)ob, type)) {
221 PyErr_SetString(PyExc_TypeError,
222 "a __bases__ item causes an inheritance cycle");
223 return -1;
224 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000225 }
226 }
227
228 new_base = best_base(value);
229
230 if (!new_base) {
231 return -1;
232 }
233
234 if (!compatible_for_assignment(type->tp_base, new_base, "__bases__"))
235 return -1;
236
237 Py_INCREF(new_base);
238 Py_INCREF(value);
239
240 old_bases = type->tp_bases;
241 old_base = type->tp_base;
242 old_mro = type->tp_mro;
243
244 type->tp_bases = value;
245 type->tp_base = new_base;
246
247 if (mro_internal(type) < 0) {
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000248 goto bail;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000249 }
250
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000251 temp = PyList_New(0);
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000252 if (!temp)
253 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000254
255 r = mro_subclasses(type, temp);
256
257 if (r < 0) {
258 for (i = 0; i < PyList_Size(temp); i++) {
259 PyTypeObject* cls;
260 PyObject* mro;
Guido van Rossum19a02ba2003-04-15 22:09:45 +0000261 PyArg_ParseTuple(PyList_GET_ITEM(temp, i),
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000262 "OO", &cls, &mro);
263 Py_DECREF(cls->tp_mro);
264 cls->tp_mro = mro;
265 Py_INCREF(cls->tp_mro);
266 }
267 Py_DECREF(temp);
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000268 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000269 }
270
271 Py_DECREF(temp);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000272
273 /* any base that was in __bases__ but now isn't, we
Raymond Hettingera8285862002-12-14 17:17:56 +0000274 need to remove |type| from its tp_subclasses.
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000275 conversely, any class now in __bases__ that wasn't
Raymond Hettingera8285862002-12-14 17:17:56 +0000276 needs to have |type| added to its subclasses. */
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000277
278 /* for now, sod that: just remove from all old_bases,
279 add to all new_bases */
280
281 for (i = PyTuple_GET_SIZE(old_bases) - 1; i >= 0; i--) {
282 ob = PyTuple_GET_ITEM(old_bases, i);
283 if (PyType_Check(ob)) {
284 remove_subclass(
285 (PyTypeObject*)ob, type);
286 }
287 }
288
289 for (i = PyTuple_GET_SIZE(value) - 1; i >= 0; i--) {
290 ob = PyTuple_GET_ITEM(value, i);
291 if (PyType_Check(ob)) {
292 if (add_subclass((PyTypeObject*)ob, type) < 0)
293 r = -1;
294 }
295 }
296
297 update_all_slots(type);
298
299 Py_DECREF(old_bases);
300 Py_DECREF(old_base);
301 Py_DECREF(old_mro);
302
303 return r;
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000304
305 bail:
306 type->tp_bases = old_bases;
307 type->tp_base = old_base;
308 type->tp_mro = old_mro;
Tim Petersea7f75d2002-12-07 21:39:16 +0000309
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000310 Py_DECREF(value);
311 Py_DECREF(new_base);
Tim Petersea7f75d2002-12-07 21:39:16 +0000312
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000313 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000314}
315
316static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000317type_dict(PyTypeObject *type, void *context)
318{
319 if (type->tp_dict == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000320 Py_INCREF(Py_None);
321 return Py_None;
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000322 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000323 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000324}
325
Tim Peters24008312002-03-17 18:56:20 +0000326static PyObject *
327type_get_doc(PyTypeObject *type, void *context)
328{
329 PyObject *result;
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000330 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL)
Tim Peters24008312002-03-17 18:56:20 +0000331 return PyString_FromString(type->tp_doc);
Tim Peters24008312002-03-17 18:56:20 +0000332 result = PyDict_GetItemString(type->tp_dict, "__doc__");
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000333 if (result == NULL) {
334 result = Py_None;
335 Py_INCREF(result);
336 }
337 else if (result->ob_type->tp_descr_get) {
Tim Peters2b858972002-04-18 04:12:28 +0000338 result = result->ob_type->tp_descr_get(result, NULL,
339 (PyObject *)type);
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000340 }
341 else {
342 Py_INCREF(result);
343 }
Tim Peters24008312002-03-17 18:56:20 +0000344 return result;
345}
346
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000347static PyGetSetDef type_getsets[] = {
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000348 {"__name__", (getter)type_name, (setter)type_set_name, NULL},
349 {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL},
Guido van Rossum3926a632001-09-25 16:25:58 +0000350 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000351 {"__dict__", (getter)type_dict, NULL, NULL},
Tim Peters24008312002-03-17 18:56:20 +0000352 {"__doc__", (getter)type_get_doc, NULL, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000353 {0}
354};
355
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000356static int
357type_compare(PyObject *v, PyObject *w)
358{
359 /* This is called with type objects only. So we
360 can just compare the addresses. */
361 Py_uintptr_t vv = (Py_uintptr_t)v;
362 Py_uintptr_t ww = (Py_uintptr_t)w;
363 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
364}
365
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000366static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000367type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000368{
Barry Warsaw7ce36942001-08-24 18:34:26 +0000369 PyObject *mod, *name, *rtn;
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000370 char *kind;
Guido van Rossumc3542212001-08-16 09:18:56 +0000371
372 mod = type_module(type, NULL);
373 if (mod == NULL)
374 PyErr_Clear();
375 else if (!PyString_Check(mod)) {
376 Py_DECREF(mod);
377 mod = NULL;
378 }
379 name = type_name(type, NULL);
380 if (name == NULL)
381 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000382
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000383 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
384 kind = "class";
385 else
386 kind = "type";
387
Barry Warsaw7ce36942001-08-24 18:34:26 +0000388 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__")) {
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000389 rtn = PyString_FromFormat("<%s '%s.%s'>",
390 kind,
Barry Warsaw7ce36942001-08-24 18:34:26 +0000391 PyString_AS_STRING(mod),
392 PyString_AS_STRING(name));
393 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000394 else
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000395 rtn = PyString_FromFormat("<%s '%s'>", kind, type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000396
Guido van Rossumc3542212001-08-16 09:18:56 +0000397 Py_XDECREF(mod);
398 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000399 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000400}
401
Tim Peters6d6c1a32001-08-02 04:15:00 +0000402static PyObject *
403type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
404{
405 PyObject *obj;
406
407 if (type->tp_new == NULL) {
408 PyErr_Format(PyExc_TypeError,
409 "cannot create '%.100s' instances",
410 type->tp_name);
411 return NULL;
412 }
413
Tim Peters3f996e72001-09-13 19:18:27 +0000414 obj = type->tp_new(type, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000415 if (obj != NULL) {
Guido van Rossumf76de622001-10-18 15:49:21 +0000416 /* Ugly exception: when the call was type(something),
417 don't call tp_init on the result. */
418 if (type == &PyType_Type &&
419 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
420 (kwds == NULL ||
421 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
422 return obj;
Guido van Rossum8ace1ab2002-04-06 01:05:01 +0000423 /* If the returned object is not an instance of type,
424 it won't be initialized. */
425 if (!PyType_IsSubtype(obj->ob_type, type))
426 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000427 type = obj->ob_type;
Jeremy Hylton719841e2002-07-16 19:39:38 +0000428 if (PyType_HasFeature(type, Py_TPFLAGS_HAVE_CLASS) &&
429 type->tp_init != NULL &&
Tim Peters6d6c1a32001-08-02 04:15:00 +0000430 type->tp_init(obj, args, kwds) < 0) {
431 Py_DECREF(obj);
432 obj = NULL;
433 }
434 }
435 return obj;
436}
437
438PyObject *
439PyType_GenericAlloc(PyTypeObject *type, int nitems)
440{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000441 PyObject *obj;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000442 const size_t size = _PyObject_VAR_SIZE(type, nitems+1);
443 /* note that we need to add one, for the sentinel */
Tim Peters406fe3b2001-10-06 19:04:01 +0000444
445 if (PyType_IS_GC(type))
Neil Schemenauer09a2ae52002-04-12 03:06:53 +0000446 obj = _PyObject_GC_Malloc(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000447 else
Neil Schemenauerc806c882001-08-29 23:54:54 +0000448 obj = PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000449
Neil Schemenauerc806c882001-08-29 23:54:54 +0000450 if (obj == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000451 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000452
Neil Schemenauerc806c882001-08-29 23:54:54 +0000453 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000454
Tim Peters6d6c1a32001-08-02 04:15:00 +0000455 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
456 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000457
Tim Peters6d6c1a32001-08-02 04:15:00 +0000458 if (type->tp_itemsize == 0)
459 PyObject_INIT(obj, type);
460 else
461 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000462
Tim Peters6d6c1a32001-08-02 04:15:00 +0000463 if (PyType_IS_GC(type))
Neil Schemenauerc806c882001-08-29 23:54:54 +0000464 _PyObject_GC_TRACK(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000465 return obj;
466}
467
468PyObject *
469PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
470{
471 return type->tp_alloc(type, 0);
472}
473
Guido van Rossum9475a232001-10-05 20:51:39 +0000474/* Helpers for subtyping */
475
476static int
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000477traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
478{
479 int i, n;
480 PyMemberDef *mp;
481
482 n = type->ob_size;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000483 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000484 for (i = 0; i < n; i++, mp++) {
485 if (mp->type == T_OBJECT_EX) {
486 char *addr = (char *)self + mp->offset;
487 PyObject *obj = *(PyObject **)addr;
488 if (obj != NULL) {
489 int err = visit(obj, arg);
490 if (err)
491 return err;
492 }
493 }
494 }
495 return 0;
496}
497
498static int
Guido van Rossum9475a232001-10-05 20:51:39 +0000499subtype_traverse(PyObject *self, visitproc visit, void *arg)
500{
501 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000502 traverseproc basetraverse;
Guido van Rossum9475a232001-10-05 20:51:39 +0000503
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000504 /* Find the nearest base with a different tp_traverse,
505 and traverse slots while we're at it */
Guido van Rossum9475a232001-10-05 20:51:39 +0000506 type = self->ob_type;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000507 base = type;
508 while ((basetraverse = base->tp_traverse) == subtype_traverse) {
509 if (base->ob_size) {
510 int err = traverse_slots(base, self, visit, arg);
511 if (err)
512 return err;
513 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000514 base = base->tp_base;
515 assert(base);
516 }
517
518 if (type->tp_dictoffset != base->tp_dictoffset) {
519 PyObject **dictptr = _PyObject_GetDictPtr(self);
520 if (dictptr && *dictptr) {
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000521 int err = visit(*dictptr, arg);
Guido van Rossum9475a232001-10-05 20:51:39 +0000522 if (err)
523 return err;
524 }
525 }
526
Guido van Rossuma3862092002-06-10 15:24:42 +0000527 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
528 /* For a heaptype, the instances count as references
529 to the type. Traverse the type so the collector
530 can find cycles involving this link. */
531 int err = visit((PyObject *)type, arg);
532 if (err)
533 return err;
534 }
535
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000536 if (basetraverse)
537 return basetraverse(self, visit, arg);
538 return 0;
539}
540
541static void
542clear_slots(PyTypeObject *type, PyObject *self)
543{
544 int i, n;
545 PyMemberDef *mp;
546
547 n = type->ob_size;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000548 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000549 for (i = 0; i < n; i++, mp++) {
550 if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
551 char *addr = (char *)self + mp->offset;
552 PyObject *obj = *(PyObject **)addr;
553 if (obj != NULL) {
554 Py_DECREF(obj);
555 *(PyObject **)addr = NULL;
556 }
557 }
558 }
559}
560
561static int
562subtype_clear(PyObject *self)
563{
564 PyTypeObject *type, *base;
565 inquiry baseclear;
566
567 /* Find the nearest base with a different tp_clear
568 and clear slots while we're at it */
569 type = self->ob_type;
570 base = type;
571 while ((baseclear = base->tp_clear) == subtype_clear) {
572 if (base->ob_size)
573 clear_slots(base, self);
574 base = base->tp_base;
575 assert(base);
576 }
577
Guido van Rossuma3862092002-06-10 15:24:42 +0000578 /* There's no need to clear the instance dict (if any);
579 the collector will call its tp_clear handler. */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000580
581 if (baseclear)
582 return baseclear(self);
Guido van Rossum9475a232001-10-05 20:51:39 +0000583 return 0;
584}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000585
586static void
587subtype_dealloc(PyObject *self)
588{
Guido van Rossum14227b42001-12-06 02:35:58 +0000589 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000590 destructor basedealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000591
Guido van Rossum22b13872002-08-06 21:41:44 +0000592 /* Extract the type; we expect it to be a heap type */
593 type = self->ob_type;
594 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000595
Guido van Rossum22b13872002-08-06 21:41:44 +0000596 /* Test whether the type has GC exactly once */
597
598 if (!PyType_IS_GC(type)) {
599 /* It's really rare to find a dynamic type that doesn't have
600 GC; it can only happen when deriving from 'object' and not
601 adding any slots or instance variables. This allows
602 certain simplifications: there's no need to call
603 clear_slots(), or DECREF the dict, or clear weakrefs. */
604
605 /* Maybe call finalizer; exit early if resurrected */
Guido van Rossumfebd61d2002-08-08 20:55:20 +0000606 if (type->tp_del) {
607 type->tp_del(self);
608 if (self->ob_refcnt > 0)
609 return;
610 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000611
612 /* Find the nearest base with a different tp_dealloc */
613 base = type;
614 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
615 assert(base->ob_size == 0);
616 base = base->tp_base;
617 assert(base);
618 }
619
620 /* Call the base tp_dealloc() */
621 assert(basedealloc);
622 basedealloc(self);
623
624 /* Can't reference self beyond this point */
625 Py_DECREF(type);
626
627 /* Done */
628 return;
629 }
630
631 /* We get here only if the type has GC */
632
633 /* UnTrack and re-Track around the trashcan macro, alas */
Andrew M. Kuchlingc9172d32003-02-06 15:22:49 +0000634 /* See explanation at end of function for full disclosure */
Guido van Rossum0906e072002-08-07 20:42:09 +0000635 PyObject_GC_UnTrack(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000636 ++_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000637 Py_TRASHCAN_SAFE_BEGIN(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000638 --_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000639 _PyObject_GC_TRACK(self); /* We'll untrack for real later */
640
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000641 /* Find the nearest base with a different tp_dealloc
642 and clear slots while we're at it */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000643 base = type;
644 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
645 if (base->ob_size)
646 clear_slots(base, self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000647 base = base->tp_base;
648 assert(base);
Guido van Rossum14227b42001-12-06 02:35:58 +0000649 }
650
Guido van Rossum1987c662003-05-29 14:29:23 +0000651 /* If we added a weaklist, we clear it. Do this *before* calling
652 the finalizer (__del__) or clearing the instance dict. */
653 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
654 PyObject_ClearWeakRefs(self);
655
656 /* Maybe call finalizer; exit early if resurrected */
657 if (type->tp_del) {
658 type->tp_del(self);
659 if (self->ob_refcnt > 0)
660 goto endlabel;
661 }
662
Tim Peters6d6c1a32001-08-02 04:15:00 +0000663 /* If we added a dict, DECREF it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000664 if (type->tp_dictoffset && !base->tp_dictoffset) {
665 PyObject **dictptr = _PyObject_GetDictPtr(self);
666 if (dictptr != NULL) {
667 PyObject *dict = *dictptr;
668 if (dict != NULL) {
669 Py_DECREF(dict);
670 *dictptr = NULL;
671 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000672 }
673 }
674
675 /* Finalize GC if the base doesn't do GC and we do */
Guido van Rossum22b13872002-08-06 21:41:44 +0000676 if (!PyType_IS_GC(base))
Guido van Rossum048eb752001-10-02 21:24:57 +0000677 _PyObject_GC_UNTRACK(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000678
679 /* Call the base tp_dealloc() */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000680 assert(basedealloc);
681 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000682
683 /* Can't reference self beyond this point */
Guido van Rossum22b13872002-08-06 21:41:44 +0000684 Py_DECREF(type);
685
Guido van Rossum0906e072002-08-07 20:42:09 +0000686 endlabel:
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000687 ++_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000688 Py_TRASHCAN_SAFE_END(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000689 --_PyTrash_delete_nesting;
690
691 /* Explanation of the weirdness around the trashcan macros:
692
693 Q. What do the trashcan macros do?
694
695 A. Read the comment titled "Trashcan mechanism" in object.h.
696 For one, this explains why there must be a call to GC-untrack
697 before the trashcan begin macro. Without understanding the
698 trashcan code, the answers to the following questions don't make
699 sense.
700
701 Q. Why do we GC-untrack before the trashcan and then immediately
702 GC-track again afterward?
703
704 A. In the case that the base class is GC-aware, the base class
705 probably GC-untracks the object. If it does that using the
706 UNTRACK macro, this will crash when the object is already
707 untracked. Because we don't know what the base class does, the
708 only safe thing is to make sure the object is tracked when we
709 call the base class dealloc. But... The trashcan begin macro
710 requires that the object is *untracked* before it is called. So
711 the dance becomes:
712
713 GC untrack
714 trashcan begin
715 GC track
716
717 Q. Why the bizarre (net-zero) manipulation of
718 _PyTrash_delete_nesting around the trashcan macros?
719
720 A. Some base classes (e.g. list) also use the trashcan mechanism.
721 The following scenario used to be possible:
722
723 - suppose the trashcan level is one below the trashcan limit
724
725 - subtype_dealloc() is called
726
727 - the trashcan limit is not yet reached, so the trashcan level
728 is incremented and the code between trashcan begin and end is
729 executed
730
731 - this destroys much of the object's contents, including its
732 slots and __dict__
733
734 - basedealloc() is called; this is really list_dealloc(), or
735 some other type which also uses the trashcan macros
736
737 - the trashcan limit is now reached, so the object is put on the
738 trashcan's to-be-deleted-later list
739
740 - basedealloc() returns
741
742 - subtype_dealloc() decrefs the object's type
743
744 - subtype_dealloc() returns
745
746 - later, the trashcan code starts deleting the objects from its
747 to-be-deleted-later list
748
749 - subtype_dealloc() is called *AGAIN* for the same object
750
751 - at the very least (if the destroyed slots and __dict__ don't
752 cause problems) the object's type gets decref'ed a second
753 time, which is *BAD*!!!
754
755 The remedy is to make sure that if the code between trashcan
756 begin and end in subtype_dealloc() is called, the code between
757 trashcan begin and end in basedealloc() will also be called.
758 This is done by decrementing the level after passing into the
759 trashcan block, and incrementing it just before leaving the
760 block.
761
762 But now it's possible that a chain of objects consisting solely
763 of objects whose deallocator is subtype_dealloc() will defeat
764 the trashcan mechanism completely: the decremented level means
765 that the effective level never reaches the limit. Therefore, we
766 *increment* the level *before* entering the trashcan block, and
767 matchingly decrement it after leaving. This means the trashcan
768 code will trigger a little early, but that's no big deal.
769
770 Q. Are there any live examples of code in need of all this
771 complexity?
772
773 A. Yes. See SF bug 668433 for code that crashed (when Python was
774 compiled in debug mode) before the trashcan level manipulations
775 were added. For more discussion, see SF patches 581742, 575073
776 and bug 574207.
777 */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000778}
779
Jeremy Hylton938ace62002-07-17 16:30:39 +0000780static PyTypeObject *solid_base(PyTypeObject *type);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000781
Tim Peters6d6c1a32001-08-02 04:15:00 +0000782/* type test with subclassing support */
783
784int
785PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
786{
787 PyObject *mro;
788
Guido van Rossum9478d072001-09-07 18:52:13 +0000789 if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
790 return b == a || b == &PyBaseObject_Type;
791
Tim Peters6d6c1a32001-08-02 04:15:00 +0000792 mro = a->tp_mro;
793 if (mro != NULL) {
794 /* Deal with multiple inheritance without recursion
795 by walking the MRO tuple */
796 int i, n;
797 assert(PyTuple_Check(mro));
798 n = PyTuple_GET_SIZE(mro);
799 for (i = 0; i < n; i++) {
800 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
801 return 1;
802 }
803 return 0;
804 }
805 else {
806 /* a is not completely initilized yet; follow tp_base */
807 do {
808 if (a == b)
809 return 1;
810 a = a->tp_base;
811 } while (a != NULL);
812 return b == &PyBaseObject_Type;
813 }
814}
815
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000816/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +0000817 without looking in the instance dictionary
818 (so we can't use PyObject_GetAttr) but still binding
819 it to the instance. The arguments are the object,
820 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000821 static variable used to cache the interned Python string.
822
823 Two variants:
824
825 - lookup_maybe() returns NULL without raising an exception
826 when the _PyType_Lookup() call fails;
827
828 - lookup_method() always raises an exception upon errors.
829*/
Guido van Rossum60718732001-08-28 17:47:51 +0000830
831static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000832lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +0000833{
834 PyObject *res;
835
836 if (*attrobj == NULL) {
837 *attrobj = PyString_InternFromString(attrstr);
838 if (*attrobj == NULL)
839 return NULL;
840 }
841 res = _PyType_Lookup(self->ob_type, *attrobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000842 if (res != NULL) {
Guido van Rossum60718732001-08-28 17:47:51 +0000843 descrgetfunc f;
844 if ((f = res->ob_type->tp_descr_get) == NULL)
845 Py_INCREF(res);
846 else
847 res = f(res, self, (PyObject *)(self->ob_type));
848 }
849 return res;
850}
851
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000852static PyObject *
853lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
854{
855 PyObject *res = lookup_maybe(self, attrstr, attrobj);
856 if (res == NULL && !PyErr_Occurred())
857 PyErr_SetObject(PyExc_AttributeError, *attrobj);
858 return res;
859}
860
Guido van Rossum2730b132001-08-28 18:22:14 +0000861/* A variation of PyObject_CallMethod that uses lookup_method()
862 instead of PyObject_GetAttrString(). This uses the same convention
863 as lookup_method to cache the interned name string object. */
864
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000865static PyObject *
Guido van Rossum2730b132001-08-28 18:22:14 +0000866call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
867{
868 va_list va;
869 PyObject *args, *func = 0, *retval;
Guido van Rossum2730b132001-08-28 18:22:14 +0000870 va_start(va, format);
871
Guido van Rossumda21c012001-10-03 00:50:18 +0000872 func = lookup_maybe(o, name, nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000873 if (func == NULL) {
874 va_end(va);
875 if (!PyErr_Occurred())
Guido van Rossumda21c012001-10-03 00:50:18 +0000876 PyErr_SetObject(PyExc_AttributeError, *nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000877 return NULL;
878 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000879
880 if (format && *format)
881 args = Py_VaBuildValue(format, va);
882 else
883 args = PyTuple_New(0);
884
885 va_end(va);
886
887 if (args == NULL)
888 return NULL;
889
890 assert(PyTuple_Check(args));
891 retval = PyObject_Call(func, args, NULL);
892
893 Py_DECREF(args);
894 Py_DECREF(func);
895
896 return retval;
897}
898
899/* Clone of call_method() that returns NotImplemented when the lookup fails. */
900
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000901static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000902call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
903{
904 va_list va;
905 PyObject *args, *func = 0, *retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000906 va_start(va, format);
907
Guido van Rossumda21c012001-10-03 00:50:18 +0000908 func = lookup_maybe(o, name, nameobj);
Guido van Rossum2730b132001-08-28 18:22:14 +0000909 if (func == NULL) {
910 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000911 if (!PyErr_Occurred()) {
912 Py_INCREF(Py_NotImplemented);
913 return Py_NotImplemented;
914 }
Guido van Rossum717ce002001-09-14 16:58:08 +0000915 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +0000916 }
917
918 if (format && *format)
919 args = Py_VaBuildValue(format, va);
920 else
921 args = PyTuple_New(0);
922
923 va_end(va);
924
Guido van Rossum717ce002001-09-14 16:58:08 +0000925 if (args == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +0000926 return NULL;
927
Guido van Rossum717ce002001-09-14 16:58:08 +0000928 assert(PyTuple_Check(args));
929 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +0000930
931 Py_DECREF(args);
932 Py_DECREF(func);
933
934 return retval;
935}
936
Tim Petersa91e9642001-11-14 23:32:33 +0000937static int
938fill_classic_mro(PyObject *mro, PyObject *cls)
939{
940 PyObject *bases, *base;
941 int i, n;
942
943 assert(PyList_Check(mro));
944 assert(PyClass_Check(cls));
945 i = PySequence_Contains(mro, cls);
946 if (i < 0)
947 return -1;
948 if (!i) {
949 if (PyList_Append(mro, cls) < 0)
950 return -1;
951 }
952 bases = ((PyClassObject *)cls)->cl_bases;
953 assert(bases && PyTuple_Check(bases));
954 n = PyTuple_GET_SIZE(bases);
955 for (i = 0; i < n; i++) {
956 base = PyTuple_GET_ITEM(bases, i);
957 if (fill_classic_mro(mro, base) < 0)
958 return -1;
959 }
960 return 0;
961}
962
963static PyObject *
964classic_mro(PyObject *cls)
965{
966 PyObject *mro;
967
968 assert(PyClass_Check(cls));
969 mro = PyList_New(0);
970 if (mro != NULL) {
971 if (fill_classic_mro(mro, cls) == 0)
972 return mro;
973 Py_DECREF(mro);
974 }
975 return NULL;
976}
977
Tim Petersea7f75d2002-12-07 21:39:16 +0000978/*
Guido van Rossum1f121312002-11-14 19:49:16 +0000979 Method resolution order algorithm C3 described in
980 "A Monotonic Superclass Linearization for Dylan",
981 by Kim Barrett, Bob Cassel, Paul Haahr,
Tim Petersea7f75d2002-12-07 21:39:16 +0000982 David A. Moon, Keith Playford, and P. Tucker Withington.
Guido van Rossum1f121312002-11-14 19:49:16 +0000983 (OOPSLA 1996)
984
Guido van Rossum98f33732002-11-25 21:36:54 +0000985 Some notes about the rules implied by C3:
986
Tim Petersea7f75d2002-12-07 21:39:16 +0000987 No duplicate bases.
Guido van Rossum98f33732002-11-25 21:36:54 +0000988 It isn't legal to repeat a class in a list of base classes.
989
990 The next three properties are the 3 constraints in "C3".
991
Tim Petersea7f75d2002-12-07 21:39:16 +0000992 Local precendece order.
Guido van Rossum98f33732002-11-25 21:36:54 +0000993 If A precedes B in C's MRO, then A will precede B in the MRO of all
994 subclasses of C.
995
996 Monotonicity.
997 The MRO of a class must be an extension without reordering of the
998 MRO of each of its superclasses.
999
1000 Extended Precedence Graph (EPG).
1001 Linearization is consistent if there is a path in the EPG from
1002 each class to all its successors in the linearization. See
1003 the paper for definition of EPG.
Guido van Rossum1f121312002-11-14 19:49:16 +00001004 */
1005
Tim Petersea7f75d2002-12-07 21:39:16 +00001006static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001007tail_contains(PyObject *list, int whence, PyObject *o) {
1008 int j, size;
1009 size = PyList_GET_SIZE(list);
1010
1011 for (j = whence+1; j < size; j++) {
1012 if (PyList_GET_ITEM(list, j) == o)
1013 return 1;
1014 }
1015 return 0;
1016}
1017
Guido van Rossum98f33732002-11-25 21:36:54 +00001018static PyObject *
1019class_name(PyObject *cls)
1020{
1021 PyObject *name = PyObject_GetAttrString(cls, "__name__");
1022 if (name == NULL) {
1023 PyErr_Clear();
1024 Py_XDECREF(name);
1025 name = PyObject_Repr(cls);
1026 }
1027 if (name == NULL)
1028 return NULL;
1029 if (!PyString_Check(name)) {
1030 Py_DECREF(name);
1031 return NULL;
1032 }
1033 return name;
1034}
1035
1036static int
1037check_duplicates(PyObject *list)
1038{
1039 int i, j, n;
1040 /* Let's use a quadratic time algorithm,
1041 assuming that the bases lists is short.
1042 */
1043 n = PyList_GET_SIZE(list);
1044 for (i = 0; i < n; i++) {
1045 PyObject *o = PyList_GET_ITEM(list, i);
1046 for (j = i + 1; j < n; j++) {
1047 if (PyList_GET_ITEM(list, j) == o) {
1048 o = class_name(o);
1049 PyErr_Format(PyExc_TypeError,
1050 "duplicate base class %s",
1051 o ? PyString_AS_STRING(o) : "?");
1052 Py_XDECREF(o);
1053 return -1;
1054 }
1055 }
1056 }
1057 return 0;
1058}
1059
1060/* Raise a TypeError for an MRO order disagreement.
1061
1062 It's hard to produce a good error message. In the absence of better
1063 insight into error reporting, report the classes that were candidates
1064 to be put next into the MRO. There is some conflict between the
1065 order in which they should be put in the MRO, but it's hard to
1066 diagnose what constraint can't be satisfied.
1067*/
1068
1069static void
1070set_mro_error(PyObject *to_merge, int *remain)
1071{
1072 int i, n, off, to_merge_size;
1073 char buf[1000];
1074 PyObject *k, *v;
1075 PyObject *set = PyDict_New();
1076
1077 to_merge_size = PyList_GET_SIZE(to_merge);
1078 for (i = 0; i < to_merge_size; i++) {
1079 PyObject *L = PyList_GET_ITEM(to_merge, i);
1080 if (remain[i] < PyList_GET_SIZE(L)) {
1081 PyObject *c = PyList_GET_ITEM(L, remain[i]);
1082 if (PyDict_SetItem(set, c, Py_None) < 0)
1083 return;
1084 }
1085 }
1086 n = PyDict_Size(set);
1087
Raymond Hettingerf394df42003-04-06 19:13:41 +00001088 off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \
1089consistent method resolution\norder (MRO) for bases");
Guido van Rossum98f33732002-11-25 21:36:54 +00001090 i = 0;
1091 while (PyDict_Next(set, &i, &k, &v) && off < sizeof(buf)) {
1092 PyObject *name = class_name(k);
1093 off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s",
1094 name ? PyString_AS_STRING(name) : "?");
1095 Py_XDECREF(name);
1096 if (--n && off+1 < sizeof(buf)) {
1097 buf[off++] = ',';
1098 buf[off] = '\0';
1099 }
1100 }
1101 PyErr_SetString(PyExc_TypeError, buf);
1102 Py_DECREF(set);
1103}
1104
Tim Petersea7f75d2002-12-07 21:39:16 +00001105static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001106pmerge(PyObject *acc, PyObject* to_merge) {
1107 int i, j, to_merge_size;
1108 int *remain;
1109 int ok, empty_cnt;
Tim Petersea7f75d2002-12-07 21:39:16 +00001110
Guido van Rossum1f121312002-11-14 19:49:16 +00001111 to_merge_size = PyList_GET_SIZE(to_merge);
1112
Guido van Rossum98f33732002-11-25 21:36:54 +00001113 /* remain stores an index into each sublist of to_merge.
1114 remain[i] is the index of the next base in to_merge[i]
1115 that is not included in acc.
1116 */
Guido van Rossum1f121312002-11-14 19:49:16 +00001117 remain = PyMem_MALLOC(SIZEOF_INT*to_merge_size);
1118 if (remain == NULL)
1119 return -1;
1120 for (i = 0; i < to_merge_size; i++)
1121 remain[i] = 0;
1122
1123 again:
1124 empty_cnt = 0;
1125 for (i = 0; i < to_merge_size; i++) {
1126 PyObject *candidate;
Tim Petersea7f75d2002-12-07 21:39:16 +00001127
Guido van Rossum1f121312002-11-14 19:49:16 +00001128 PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
1129
1130 if (remain[i] >= PyList_GET_SIZE(cur_list)) {
1131 empty_cnt++;
1132 continue;
1133 }
1134
Guido van Rossum98f33732002-11-25 21:36:54 +00001135 /* Choose next candidate for MRO.
1136
1137 The input sequences alone can determine the choice.
1138 If not, choose the class which appears in the MRO
1139 of the earliest direct superclass of the new class.
1140 */
1141
Guido van Rossum1f121312002-11-14 19:49:16 +00001142 candidate = PyList_GET_ITEM(cur_list, remain[i]);
1143 for (j = 0; j < to_merge_size; j++) {
1144 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum98f33732002-11-25 21:36:54 +00001145 if (tail_contains(j_lst, remain[j], candidate)) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001146 goto skip; /* continue outer loop */
Guido van Rossum98f33732002-11-25 21:36:54 +00001147 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001148 }
1149 ok = PyList_Append(acc, candidate);
1150 if (ok < 0) {
1151 PyMem_Free(remain);
1152 return -1;
1153 }
1154 for (j = 0; j < to_merge_size; j++) {
1155 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum768158c2002-12-31 16:33:01 +00001156 if (remain[j] < PyList_GET_SIZE(j_lst) &&
1157 PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001158 remain[j]++;
1159 }
1160 }
1161 goto again;
Tim Peters9a6b8d82002-11-14 23:22:33 +00001162 skip: ;
Guido van Rossum1f121312002-11-14 19:49:16 +00001163 }
1164
Guido van Rossum98f33732002-11-25 21:36:54 +00001165 if (empty_cnt == to_merge_size) {
1166 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001167 return 0;
Guido van Rossum98f33732002-11-25 21:36:54 +00001168 }
1169 set_mro_error(to_merge, remain);
1170 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001171 return -1;
1172}
1173
Tim Peters6d6c1a32001-08-02 04:15:00 +00001174static PyObject *
1175mro_implementation(PyTypeObject *type)
1176{
1177 int i, n, ok;
1178 PyObject *bases, *result;
Guido van Rossum1f121312002-11-14 19:49:16 +00001179 PyObject *to_merge, *bases_aslist;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001180
Guido van Rossum63517572002-06-18 16:44:57 +00001181 if(type->tp_dict == NULL) {
1182 if(PyType_Ready(type) < 0)
1183 return NULL;
1184 }
1185
Guido van Rossum98f33732002-11-25 21:36:54 +00001186 /* Find a superclass linearization that honors the constraints
1187 of the explicit lists of bases and the constraints implied by
Tim Petersea7f75d2002-12-07 21:39:16 +00001188 each base class.
Guido van Rossum98f33732002-11-25 21:36:54 +00001189
1190 to_merge is a list of lists, where each list is a superclass
1191 linearization implied by a base class. The last element of
1192 to_merge is the declared list of bases.
1193 */
1194
Tim Peters6d6c1a32001-08-02 04:15:00 +00001195 bases = type->tp_bases;
1196 n = PyTuple_GET_SIZE(bases);
Guido van Rossum1f121312002-11-14 19:49:16 +00001197
1198 to_merge = PyList_New(n+1);
1199 if (to_merge == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001200 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001201
Tim Peters6d6c1a32001-08-02 04:15:00 +00001202 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001203 PyObject *base = PyTuple_GET_ITEM(bases, i);
1204 PyObject *parentMRO;
1205 if (PyType_Check(base))
1206 parentMRO = PySequence_List(
1207 ((PyTypeObject*)base)->tp_mro);
1208 else
1209 parentMRO = classic_mro(base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001210 if (parentMRO == NULL) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001211 Py_DECREF(to_merge);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001212 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001213 }
1214
1215 PyList_SET_ITEM(to_merge, i, parentMRO);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001216 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001217
1218 bases_aslist = PySequence_List(bases);
1219 if (bases_aslist == NULL) {
1220 Py_DECREF(to_merge);
1221 return NULL;
1222 }
Guido van Rossum98f33732002-11-25 21:36:54 +00001223 /* This is just a basic sanity check. */
1224 if (check_duplicates(bases_aslist) < 0) {
1225 Py_DECREF(to_merge);
1226 Py_DECREF(bases_aslist);
1227 return NULL;
1228 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001229 PyList_SET_ITEM(to_merge, n, bases_aslist);
1230
1231 result = Py_BuildValue("[O]", (PyObject *)type);
1232 if (result == NULL) {
1233 Py_DECREF(to_merge);
1234 return NULL;
1235 }
1236
1237 ok = pmerge(result, to_merge);
1238 Py_DECREF(to_merge);
1239 if (ok < 0) {
1240 Py_DECREF(result);
1241 return NULL;
1242 }
1243
Tim Peters6d6c1a32001-08-02 04:15:00 +00001244 return result;
1245}
1246
1247static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001248mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001249{
1250 PyTypeObject *type = (PyTypeObject *)self;
1251
Tim Peters6d6c1a32001-08-02 04:15:00 +00001252 return mro_implementation(type);
1253}
1254
1255static int
1256mro_internal(PyTypeObject *type)
1257{
1258 PyObject *mro, *result, *tuple;
1259
1260 if (type->ob_type == &PyType_Type) {
1261 result = mro_implementation(type);
1262 }
1263 else {
Guido van Rossum60718732001-08-28 17:47:51 +00001264 static PyObject *mro_str;
1265 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001266 if (mro == NULL)
1267 return -1;
1268 result = PyObject_CallObject(mro, NULL);
1269 Py_DECREF(mro);
1270 }
1271 if (result == NULL)
1272 return -1;
1273 tuple = PySequence_Tuple(result);
1274 Py_DECREF(result);
1275 type->tp_mro = tuple;
1276 return 0;
1277}
1278
1279
1280/* Calculate the best base amongst multiple base classes.
1281 This is the first one that's on the path to the "solid base". */
1282
1283static PyTypeObject *
1284best_base(PyObject *bases)
1285{
1286 int i, n;
1287 PyTypeObject *base, *winner, *candidate, *base_i;
Tim Petersa91e9642001-11-14 23:32:33 +00001288 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001289
1290 assert(PyTuple_Check(bases));
1291 n = PyTuple_GET_SIZE(bases);
1292 assert(n > 0);
Tim Petersa91e9642001-11-14 23:32:33 +00001293 base = NULL;
1294 winner = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001295 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001296 base_proto = PyTuple_GET_ITEM(bases, i);
1297 if (PyClass_Check(base_proto))
1298 continue;
1299 if (!PyType_Check(base_proto)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001300 PyErr_SetString(
1301 PyExc_TypeError,
1302 "bases must be types");
1303 return NULL;
1304 }
Tim Petersa91e9642001-11-14 23:32:33 +00001305 base_i = (PyTypeObject *)base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001306 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001307 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001308 return NULL;
1309 }
1310 candidate = solid_base(base_i);
Tim Petersa91e9642001-11-14 23:32:33 +00001311 if (winner == NULL) {
1312 winner = candidate;
1313 base = base_i;
1314 }
1315 else if (PyType_IsSubtype(winner, candidate))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001316 ;
1317 else if (PyType_IsSubtype(candidate, winner)) {
1318 winner = candidate;
1319 base = base_i;
1320 }
1321 else {
1322 PyErr_SetString(
1323 PyExc_TypeError,
1324 "multiple bases have "
1325 "instance lay-out conflict");
1326 return NULL;
1327 }
1328 }
Guido van Rossume54616c2001-12-14 04:19:56 +00001329 if (base == NULL)
1330 PyErr_SetString(PyExc_TypeError,
1331 "a new-style class can't have only classic bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001332 return base;
1333}
1334
1335static int
1336extra_ivars(PyTypeObject *type, PyTypeObject *base)
1337{
Neil Schemenauerc806c882001-08-29 23:54:54 +00001338 size_t t_size = type->tp_basicsize;
1339 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001340
Guido van Rossum9676b222001-08-17 20:32:36 +00001341 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001342 if (type->tp_itemsize || base->tp_itemsize) {
1343 /* If itemsize is involved, stricter rules */
1344 return t_size != b_size ||
1345 type->tp_itemsize != base->tp_itemsize;
1346 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001347 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
1348 type->tp_weaklistoffset + sizeof(PyObject *) == t_size)
1349 t_size -= sizeof(PyObject *);
1350 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
1351 type->tp_dictoffset + sizeof(PyObject *) == t_size)
1352 t_size -= sizeof(PyObject *);
1353
1354 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001355}
1356
1357static PyTypeObject *
1358solid_base(PyTypeObject *type)
1359{
1360 PyTypeObject *base;
1361
1362 if (type->tp_base)
1363 base = solid_base(type->tp_base);
1364 else
1365 base = &PyBaseObject_Type;
1366 if (extra_ivars(type, base))
1367 return type;
1368 else
1369 return base;
1370}
1371
Jeremy Hylton938ace62002-07-17 16:30:39 +00001372static void object_dealloc(PyObject *);
1373static int object_init(PyObject *, PyObject *, PyObject *);
1374static int update_slot(PyTypeObject *, PyObject *);
1375static void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001376
1377static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001378subtype_dict(PyObject *obj, void *context)
1379{
1380 PyObject **dictptr = _PyObject_GetDictPtr(obj);
1381 PyObject *dict;
1382
1383 if (dictptr == NULL) {
1384 PyErr_SetString(PyExc_AttributeError,
1385 "This object has no __dict__");
1386 return NULL;
1387 }
1388 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +00001389 if (dict == NULL)
1390 *dictptr = dict = PyDict_New();
1391 Py_XINCREF(dict);
1392 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001393}
1394
Guido van Rossum6661be32001-10-26 04:26:12 +00001395static int
1396subtype_setdict(PyObject *obj, PyObject *value, void *context)
1397{
1398 PyObject **dictptr = _PyObject_GetDictPtr(obj);
1399 PyObject *dict;
1400
1401 if (dictptr == NULL) {
1402 PyErr_SetString(PyExc_AttributeError,
1403 "This object has no __dict__");
1404 return -1;
1405 }
Guido van Rossumd331cb52001-12-05 19:46:42 +00001406 if (value != NULL && !PyDict_Check(value)) {
Guido van Rossum6661be32001-10-26 04:26:12 +00001407 PyErr_SetString(PyExc_TypeError,
1408 "__dict__ must be set to a dictionary");
1409 return -1;
1410 }
1411 dict = *dictptr;
Guido van Rossumd331cb52001-12-05 19:46:42 +00001412 Py_XINCREF(value);
Guido van Rossum6661be32001-10-26 04:26:12 +00001413 *dictptr = value;
1414 Py_XDECREF(dict);
1415 return 0;
1416}
1417
Guido van Rossumad47da02002-08-12 19:05:44 +00001418static PyObject *
1419subtype_getweakref(PyObject *obj, void *context)
1420{
1421 PyObject **weaklistptr;
1422 PyObject *result;
1423
1424 if (obj->ob_type->tp_weaklistoffset == 0) {
1425 PyErr_SetString(PyExc_AttributeError,
1426 "This object has no __weaklist__");
1427 return NULL;
1428 }
1429 assert(obj->ob_type->tp_weaklistoffset > 0);
1430 assert(obj->ob_type->tp_weaklistoffset + sizeof(PyObject *) <=
Guido van Rossum3747a0f2002-08-12 19:25:08 +00001431 (size_t)(obj->ob_type->tp_basicsize));
Guido van Rossumad47da02002-08-12 19:05:44 +00001432 weaklistptr = (PyObject **)
Guido van Rossum3747a0f2002-08-12 19:25:08 +00001433 ((char *)obj + obj->ob_type->tp_weaklistoffset);
Guido van Rossumad47da02002-08-12 19:05:44 +00001434 if (*weaklistptr == NULL)
1435 result = Py_None;
1436 else
1437 result = *weaklistptr;
1438 Py_INCREF(result);
1439 return result;
1440}
1441
Guido van Rossum373c7412003-01-07 13:41:37 +00001442/* Three variants on the subtype_getsets list. */
1443
1444static PyGetSetDef subtype_getsets_full[] = {
Guido van Rossumad47da02002-08-12 19:05:44 +00001445 {"__dict__", subtype_dict, subtype_setdict,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001446 PyDoc_STR("dictionary for instance variables (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001447 {"__weakref__", subtype_getweakref, NULL,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001448 PyDoc_STR("list of weak references to the object (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001449 {0}
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001450};
1451
Guido van Rossum373c7412003-01-07 13:41:37 +00001452static PyGetSetDef subtype_getsets_dict_only[] = {
1453 {"__dict__", subtype_dict, subtype_setdict,
1454 PyDoc_STR("dictionary for instance variables (if defined)")},
1455 {0}
1456};
1457
1458static PyGetSetDef subtype_getsets_weakref_only[] = {
1459 {"__weakref__", subtype_getweakref, NULL,
1460 PyDoc_STR("list of weak references to the object (if defined)")},
1461 {0}
1462};
1463
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001464static int
1465valid_identifier(PyObject *s)
1466{
Guido van Rossum03013a02002-07-16 14:30:28 +00001467 unsigned char *p;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001468 int i, n;
1469
1470 if (!PyString_Check(s)) {
1471 PyErr_SetString(PyExc_TypeError,
1472 "__slots__ must be strings");
1473 return 0;
1474 }
Guido van Rossum03013a02002-07-16 14:30:28 +00001475 p = (unsigned char *) PyString_AS_STRING(s);
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001476 n = PyString_GET_SIZE(s);
1477 /* We must reject an empty name. As a hack, we bump the
1478 length to 1 so that the loop will balk on the trailing \0. */
1479 if (n == 0)
1480 n = 1;
1481 for (i = 0; i < n; i++, p++) {
1482 if (!(i == 0 ? isalpha(*p) : isalnum(*p)) && *p != '_') {
1483 PyErr_SetString(PyExc_TypeError,
1484 "__slots__ must be identifiers");
1485 return 0;
1486 }
1487 }
1488 return 1;
1489}
1490
Martin v. Löwisd919a592002-10-14 21:07:28 +00001491#ifdef Py_USING_UNICODE
1492/* Replace Unicode objects in slots. */
1493
1494static PyObject *
1495_unicode_to_string(PyObject *slots, int nslots)
1496{
1497 PyObject *tmp = slots;
1498 PyObject *o, *o1;
1499 int i;
1500 intintargfunc copy = slots->ob_type->tp_as_sequence->sq_slice;
1501 for (i = 0; i < nslots; i++) {
1502 if (PyUnicode_Check(o = PyTuple_GET_ITEM(tmp, i))) {
1503 if (tmp == slots) {
1504 tmp = copy(slots, 0, PyTuple_GET_SIZE(slots));
1505 if (tmp == NULL)
1506 return NULL;
1507 }
1508 o1 = _PyUnicode_AsDefaultEncodedString
1509 (o, NULL);
1510 if (o1 == NULL) {
1511 Py_DECREF(tmp);
1512 return 0;
1513 }
1514 Py_INCREF(o1);
1515 Py_DECREF(o);
1516 PyTuple_SET_ITEM(tmp, i, o1);
1517 }
1518 }
1519 return tmp;
1520}
1521#endif
1522
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001523static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001524type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
1525{
1526 PyObject *name, *bases, *dict;
1527 static char *kwlist[] = {"name", "bases", "dict", 0};
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001528 PyObject *slots, *tmp, *newslots;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001529 PyTypeObject *type, *base, *tmptype, *winner;
Guido van Rossume5c691a2003-03-07 15:13:17 +00001530 PyHeapTypeObject *et;
Guido van Rossum6f799372001-09-20 20:46:19 +00001531 PyMemberDef *mp;
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001532 int i, nbases, nslots, slotoffset, add_dict, add_weak;
Guido van Rossumad47da02002-08-12 19:05:44 +00001533 int j, may_add_dict, may_add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001534
Tim Peters3abca122001-10-27 19:37:48 +00001535 assert(args != NULL && PyTuple_Check(args));
1536 assert(kwds == NULL || PyDict_Check(kwds));
1537
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001538 /* Special case: type(x) should return x->ob_type */
Tim Peters3abca122001-10-27 19:37:48 +00001539 {
1540 const int nargs = PyTuple_GET_SIZE(args);
1541 const int nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
1542
1543 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
1544 PyObject *x = PyTuple_GET_ITEM(args, 0);
1545 Py_INCREF(x->ob_type);
1546 return (PyObject *) x->ob_type;
1547 }
1548
1549 /* SF bug 475327 -- if that didn't trigger, we need 3
1550 arguments. but PyArg_ParseTupleAndKeywords below may give
1551 a msg saying type() needs exactly 3. */
1552 if (nargs + nkwds != 3) {
1553 PyErr_SetString(PyExc_TypeError,
1554 "type() takes 1 or 3 arguments");
1555 return NULL;
1556 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001557 }
1558
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001559 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001560 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
1561 &name,
1562 &PyTuple_Type, &bases,
1563 &PyDict_Type, &dict))
1564 return NULL;
1565
1566 /* Determine the proper metatype to deal with this,
1567 and check for metatype conflicts while we're at it.
1568 Note that if some other metatype wins to contract,
1569 it's possible that its instances are not types. */
1570 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001571 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001572 for (i = 0; i < nbases; i++) {
1573 tmp = PyTuple_GET_ITEM(bases, i);
1574 tmptype = tmp->ob_type;
Tim Petersa91e9642001-11-14 23:32:33 +00001575 if (tmptype == &PyClass_Type)
1576 continue; /* Special case classic classes */
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001577 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001578 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001579 if (PyType_IsSubtype(tmptype, winner)) {
1580 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001581 continue;
1582 }
1583 PyErr_SetString(PyExc_TypeError,
Guido van Rossum636688d2003-04-23 12:07:22 +00001584 "metaclass conflict: "
1585 "the metaclass of a derived class "
1586 "must be a (non-strict) subclass "
1587 "of the metaclasses of all its bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001588 return NULL;
1589 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001590 if (winner != metatype) {
1591 if (winner->tp_new != type_new) /* Pass it to the winner */
1592 return winner->tp_new(winner, args, kwds);
1593 metatype = winner;
1594 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001595
1596 /* Adjust for empty tuple bases */
1597 if (nbases == 0) {
1598 bases = Py_BuildValue("(O)", &PyBaseObject_Type);
1599 if (bases == NULL)
1600 return NULL;
1601 nbases = 1;
1602 }
1603 else
1604 Py_INCREF(bases);
1605
1606 /* XXX From here until type is allocated, "return NULL" leaks bases! */
1607
1608 /* Calculate best base, and check that all bases are type objects */
1609 base = best_base(bases);
1610 if (base == NULL)
1611 return NULL;
1612 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
1613 PyErr_Format(PyExc_TypeError,
1614 "type '%.100s' is not an acceptable base type",
1615 base->tp_name);
1616 return NULL;
1617 }
1618
Tim Peters6d6c1a32001-08-02 04:15:00 +00001619 /* Check for a __slots__ sequence variable in dict, and count it */
1620 slots = PyDict_GetItemString(dict, "__slots__");
1621 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +00001622 add_dict = 0;
1623 add_weak = 0;
Guido van Rossumad47da02002-08-12 19:05:44 +00001624 may_add_dict = base->tp_dictoffset == 0;
1625 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
1626 if (slots == NULL) {
1627 if (may_add_dict) {
1628 add_dict++;
1629 }
1630 if (may_add_weak) {
1631 add_weak++;
1632 }
1633 }
1634 else {
1635 /* Have slots */
1636
Tim Peters6d6c1a32001-08-02 04:15:00 +00001637 /* Make it into a tuple */
1638 if (PyString_Check(slots))
1639 slots = Py_BuildValue("(O)", slots);
1640 else
1641 slots = PySequence_Tuple(slots);
1642 if (slots == NULL)
1643 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00001644 assert(PyTuple_Check(slots));
1645
1646 /* Are slots allowed? */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001647 nslots = PyTuple_GET_SIZE(slots);
Guido van Rossume5c691a2003-03-07 15:13:17 +00001648 if (nslots > 0 && base->tp_itemsize != 0 && !PyType_Check(base)) {
1649 /* for the special case of meta types, allow slots */
Guido van Rossumc4141872001-08-30 04:43:35 +00001650 PyErr_Format(PyExc_TypeError,
1651 "nonempty __slots__ "
1652 "not supported for subtype of '%s'",
1653 base->tp_name);
Guido van Rossumad47da02002-08-12 19:05:44 +00001654 bad_slots:
1655 Py_DECREF(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +00001656 return NULL;
1657 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001658
Martin v. Löwisd919a592002-10-14 21:07:28 +00001659#ifdef Py_USING_UNICODE
1660 tmp = _unicode_to_string(slots, nslots);
Martin v. Löwis13b1a5c2002-10-14 21:11:34 +00001661 if (tmp != slots) {
1662 Py_DECREF(slots);
1663 slots = tmp;
1664 }
Martin v. Löwisd919a592002-10-14 21:07:28 +00001665 if (!tmp)
1666 return NULL;
1667#endif
Guido van Rossumad47da02002-08-12 19:05:44 +00001668 /* Check for valid slot names and two special cases */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001669 for (i = 0; i < nslots; i++) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001670 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
1671 char *s;
1672 if (!valid_identifier(tmp))
1673 goto bad_slots;
1674 assert(PyString_Check(tmp));
1675 s = PyString_AS_STRING(tmp);
1676 if (strcmp(s, "__dict__") == 0) {
1677 if (!may_add_dict || add_dict) {
1678 PyErr_SetString(PyExc_TypeError,
1679 "__dict__ slot disallowed: "
1680 "we already got one");
1681 goto bad_slots;
1682 }
1683 add_dict++;
1684 }
1685 if (strcmp(s, "__weakref__") == 0) {
1686 if (!may_add_weak || add_weak) {
1687 PyErr_SetString(PyExc_TypeError,
1688 "__weakref__ slot disallowed: "
1689 "either we already got one, "
1690 "or __itemsize__ != 0");
1691 goto bad_slots;
1692 }
1693 add_weak++;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001694 }
1695 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001696
Guido van Rossumad47da02002-08-12 19:05:44 +00001697 /* Copy slots into yet another tuple, demangling names */
1698 newslots = PyTuple_New(nslots - add_dict - add_weak);
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001699 if (newslots == NULL)
Guido van Rossumad47da02002-08-12 19:05:44 +00001700 goto bad_slots;
1701 for (i = j = 0; i < nslots; i++) {
1702 char *s;
Guido van Rossum8e829202002-08-16 03:47:49 +00001703 char buffer[256];
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001704 tmp = PyTuple_GET_ITEM(slots, i);
Guido van Rossumad47da02002-08-12 19:05:44 +00001705 s = PyString_AS_STRING(tmp);
1706 if ((add_dict && strcmp(s, "__dict__") == 0) ||
1707 (add_weak && strcmp(s, "__weakref__") == 0))
1708 continue;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001709 if (_Py_Mangle(PyString_AS_STRING(name),
Guido van Rossumad47da02002-08-12 19:05:44 +00001710 PyString_AS_STRING(tmp),
1711 buffer, sizeof(buffer)))
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001712 {
1713 tmp = PyString_FromString(buffer);
1714 } else {
1715 Py_INCREF(tmp);
1716 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001717 PyTuple_SET_ITEM(newslots, j, tmp);
1718 j++;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001719 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001720 assert(j == nslots - add_dict - add_weak);
1721 nslots = j;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001722 Py_DECREF(slots);
1723 slots = newslots;
1724
Guido van Rossumad47da02002-08-12 19:05:44 +00001725 /* Secondary bases may provide weakrefs or dict */
1726 if (nbases > 1 &&
1727 ((may_add_dict && !add_dict) ||
1728 (may_add_weak && !add_weak))) {
1729 for (i = 0; i < nbases; i++) {
1730 tmp = PyTuple_GET_ITEM(bases, i);
1731 if (tmp == (PyObject *)base)
1732 continue; /* Skip primary base */
1733 if (PyClass_Check(tmp)) {
1734 /* Classic base class provides both */
1735 if (may_add_dict && !add_dict)
1736 add_dict++;
1737 if (may_add_weak && !add_weak)
1738 add_weak++;
1739 break;
1740 }
1741 assert(PyType_Check(tmp));
1742 tmptype = (PyTypeObject *)tmp;
1743 if (may_add_dict && !add_dict &&
1744 tmptype->tp_dictoffset != 0)
1745 add_dict++;
1746 if (may_add_weak && !add_weak &&
1747 tmptype->tp_weaklistoffset != 0)
1748 add_weak++;
1749 if (may_add_dict && !add_dict)
1750 continue;
1751 if (may_add_weak && !add_weak)
1752 continue;
1753 /* Nothing more to check */
1754 break;
1755 }
1756 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001757 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001758
1759 /* XXX From here until type is safely allocated,
1760 "return NULL" may leak slots! */
1761
1762 /* Allocate the type object */
1763 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
Guido van Rossumad47da02002-08-12 19:05:44 +00001764 if (type == NULL) {
1765 Py_XDECREF(slots);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001766 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00001767 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001768
1769 /* Keep name and slots alive in the extended type object */
Guido van Rossume5c691a2003-03-07 15:13:17 +00001770 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001771 Py_INCREF(name);
1772 et->name = name;
1773 et->slots = slots;
1774
Guido van Rossumdc91b992001-08-08 22:26:22 +00001775 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001776 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
1777 Py_TPFLAGS_BASETYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00001778 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
1779 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00001780
1781 /* It's a new-style number unless it specifically inherits any
1782 old-style numeric behavior */
1783 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
1784 (base->tp_as_number == NULL))
1785 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
1786
1787 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001788 type->tp_as_number = &et->as_number;
1789 type->tp_as_sequence = &et->as_sequence;
1790 type->tp_as_mapping = &et->as_mapping;
1791 type->tp_as_buffer = &et->as_buffer;
1792 type->tp_name = PyString_AS_STRING(name);
1793
1794 /* Set tp_base and tp_bases */
1795 type->tp_bases = bases;
1796 Py_INCREF(base);
1797 type->tp_base = base;
1798
Guido van Rossum687ae002001-10-15 22:03:32 +00001799 /* Initialize tp_dict from passed-in dict */
1800 type->tp_dict = dict = PyDict_Copy(dict);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001801 if (dict == NULL) {
1802 Py_DECREF(type);
1803 return NULL;
1804 }
1805
Guido van Rossumc3542212001-08-16 09:18:56 +00001806 /* Set __module__ in the dict */
1807 if (PyDict_GetItemString(dict, "__module__") == NULL) {
1808 tmp = PyEval_GetGlobals();
1809 if (tmp != NULL) {
1810 tmp = PyDict_GetItemString(tmp, "__name__");
1811 if (tmp != NULL) {
1812 if (PyDict_SetItemString(dict, "__module__",
1813 tmp) < 0)
1814 return NULL;
1815 }
1816 }
1817 }
1818
Tim Peters2f93e282001-10-04 05:27:00 +00001819 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
Tim Peters24008312002-03-17 18:56:20 +00001820 and is a string. The __doc__ accessor will first look for tp_doc;
1821 if that fails, it will still look into __dict__.
Tim Peters2f93e282001-10-04 05:27:00 +00001822 */
1823 {
1824 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
1825 if (doc != NULL && PyString_Check(doc)) {
1826 const size_t n = (size_t)PyString_GET_SIZE(doc);
Tim Peters59f809d2001-10-04 05:43:02 +00001827 type->tp_doc = (char *)PyObject_MALLOC(n+1);
Tim Peters2f93e282001-10-04 05:27:00 +00001828 if (type->tp_doc == NULL) {
1829 Py_DECREF(type);
1830 return NULL;
1831 }
1832 memcpy(type->tp_doc, PyString_AS_STRING(doc), n+1);
1833 }
1834 }
1835
Tim Peters6d6c1a32001-08-02 04:15:00 +00001836 /* Special-case __new__: if it's a plain function,
1837 make it a static function */
1838 tmp = PyDict_GetItemString(dict, "__new__");
1839 if (tmp != NULL && PyFunction_Check(tmp)) {
1840 tmp = PyStaticMethod_New(tmp);
1841 if (tmp == NULL) {
1842 Py_DECREF(type);
1843 return NULL;
1844 }
1845 PyDict_SetItemString(dict, "__new__", tmp);
1846 Py_DECREF(tmp);
1847 }
1848
1849 /* Add descriptors for custom slots from __slots__, or for __dict__ */
Guido van Rossume5c691a2003-03-07 15:13:17 +00001850 mp = PyHeapType_GET_MEMBERS(et);
Neil Schemenauerc806c882001-08-29 23:54:54 +00001851 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001852 if (slots != NULL) {
1853 for (i = 0; i < nslots; i++, mp++) {
1854 mp->name = PyString_AS_STRING(
1855 PyTuple_GET_ITEM(slots, i));
Guido van Rossum64b206c2001-12-04 17:13:22 +00001856 mp->type = T_OBJECT_EX;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001857 mp->offset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +00001858 if (base->tp_weaklistoffset == 0 &&
Guido van Rossum64b206c2001-12-04 17:13:22 +00001859 strcmp(mp->name, "__weakref__") == 0) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001860 add_weak++;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001861 mp->type = T_OBJECT;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001862 mp->flags = READONLY;
Guido van Rossum9676b222001-08-17 20:32:36 +00001863 type->tp_weaklistoffset = slotoffset;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001864 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001865 slotoffset += sizeof(PyObject *);
1866 }
1867 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001868 if (add_dict) {
1869 if (base->tp_itemsize)
1870 type->tp_dictoffset = -(long)sizeof(PyObject *);
1871 else
1872 type->tp_dictoffset = slotoffset;
1873 slotoffset += sizeof(PyObject *);
1874 }
1875 if (add_weak) {
1876 assert(!base->tp_itemsize);
1877 type->tp_weaklistoffset = slotoffset;
1878 slotoffset += sizeof(PyObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001879 }
1880 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001881 type->tp_itemsize = base->tp_itemsize;
Guido van Rossume5c691a2003-03-07 15:13:17 +00001882 type->tp_members = PyHeapType_GET_MEMBERS(et);
Guido van Rossum373c7412003-01-07 13:41:37 +00001883
1884 if (type->tp_weaklistoffset && type->tp_dictoffset)
1885 type->tp_getset = subtype_getsets_full;
1886 else if (type->tp_weaklistoffset && !type->tp_dictoffset)
1887 type->tp_getset = subtype_getsets_weakref_only;
1888 else if (!type->tp_weaklistoffset && type->tp_dictoffset)
1889 type->tp_getset = subtype_getsets_dict_only;
1890 else
1891 type->tp_getset = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001892
1893 /* Special case some slots */
1894 if (type->tp_dictoffset != 0 || nslots > 0) {
1895 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
1896 type->tp_getattro = PyObject_GenericGetAttr;
1897 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
1898 type->tp_setattro = PyObject_GenericSetAttr;
1899 }
1900 type->tp_dealloc = subtype_dealloc;
1901
Guido van Rossum9475a232001-10-05 20:51:39 +00001902 /* Enable GC unless there are really no instance variables possible */
1903 if (!(type->tp_basicsize == sizeof(PyObject) &&
1904 type->tp_itemsize == 0))
1905 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
1906
Tim Peters6d6c1a32001-08-02 04:15:00 +00001907 /* Always override allocation strategy to use regular heap */
1908 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00001909 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001910 type->tp_free = PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00001911 type->tp_traverse = subtype_traverse;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001912 type->tp_clear = subtype_clear;
Guido van Rossum048eb752001-10-02 21:24:57 +00001913 }
1914 else
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001915 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001916
1917 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001918 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001919 Py_DECREF(type);
1920 return NULL;
1921 }
1922
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001923 /* Put the proper slots in place */
1924 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00001925
Tim Peters6d6c1a32001-08-02 04:15:00 +00001926 return (PyObject *)type;
1927}
1928
1929/* Internal API to look for a name through the MRO.
1930 This returns a borrowed reference, and doesn't set an exception! */
1931PyObject *
1932_PyType_Lookup(PyTypeObject *type, PyObject *name)
1933{
1934 int i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00001935 PyObject *mro, *res, *base, *dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001936
Guido van Rossum687ae002001-10-15 22:03:32 +00001937 /* Look in tp_dict of types in MRO */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001938 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00001939
1940 /* If mro is NULL, the type is either not yet initialized
1941 by PyType_Ready(), or already cleared by type_clear().
1942 Either way the safest thing to do is to return NULL. */
1943 if (mro == NULL)
1944 return NULL;
1945
Tim Peters6d6c1a32001-08-02 04:15:00 +00001946 assert(PyTuple_Check(mro));
1947 n = PyTuple_GET_SIZE(mro);
1948 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001949 base = PyTuple_GET_ITEM(mro, i);
1950 if (PyClass_Check(base))
1951 dict = ((PyClassObject *)base)->cl_dict;
1952 else {
1953 assert(PyType_Check(base));
1954 dict = ((PyTypeObject *)base)->tp_dict;
1955 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001956 assert(dict && PyDict_Check(dict));
1957 res = PyDict_GetItem(dict, name);
1958 if (res != NULL)
1959 return res;
1960 }
1961 return NULL;
1962}
1963
1964/* This is similar to PyObject_GenericGetAttr(),
1965 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
1966static PyObject *
1967type_getattro(PyTypeObject *type, PyObject *name)
1968{
1969 PyTypeObject *metatype = type->ob_type;
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001970 PyObject *meta_attribute, *attribute;
1971 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001972
1973 /* Initialize this type (we'll assume the metatype is initialized) */
1974 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001975 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001976 return NULL;
1977 }
1978
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001979 /* No readable descriptor found yet */
1980 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00001981
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001982 /* Look for the attribute in the metatype */
1983 meta_attribute = _PyType_Lookup(metatype, name);
1984
1985 if (meta_attribute != NULL) {
1986 meta_get = meta_attribute->ob_type->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00001987
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001988 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
1989 /* Data descriptors implement tp_descr_set to intercept
1990 * writes. Assume the attribute is not overridden in
1991 * type's tp_dict (and bases): call the descriptor now.
1992 */
1993 return meta_get(meta_attribute, (PyObject *)type,
1994 (PyObject *)metatype);
1995 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001996 }
1997
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001998 /* No data descriptor found on metatype. Look in tp_dict of this
1999 * type and its bases */
2000 attribute = _PyType_Lookup(type, name);
2001 if (attribute != NULL) {
2002 /* Implement descriptor functionality, if any */
2003 descrgetfunc local_get = attribute->ob_type->tp_descr_get;
2004 if (local_get != NULL) {
2005 /* NULL 2nd argument indicates the descriptor was
2006 * found on the target object itself (or a base) */
2007 return local_get(attribute, (PyObject *)NULL,
2008 (PyObject *)type);
2009 }
Tim Peters34592512002-07-11 06:23:50 +00002010
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002011 Py_INCREF(attribute);
2012 return attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002013 }
2014
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002015 /* No attribute found in local __dict__ (or bases): use the
2016 * descriptor from the metatype, if any */
2017 if (meta_get != NULL)
2018 return meta_get(meta_attribute, (PyObject *)type,
2019 (PyObject *)metatype);
2020
2021 /* If an ordinary attribute was found on the metatype, return it now */
2022 if (meta_attribute != NULL) {
2023 Py_INCREF(meta_attribute);
2024 return meta_attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002025 }
2026
2027 /* Give up */
2028 PyErr_Format(PyExc_AttributeError,
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002029 "type object '%.50s' has no attribute '%.400s'",
2030 type->tp_name, PyString_AS_STRING(name));
Tim Peters6d6c1a32001-08-02 04:15:00 +00002031 return NULL;
2032}
2033
2034static int
2035type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
2036{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002037 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2038 PyErr_Format(
2039 PyExc_TypeError,
2040 "can't set attributes of built-in/extension type '%s'",
2041 type->tp_name);
2042 return -1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002043 }
Guido van Rossum8d24ee92003-03-24 23:49:49 +00002044 /* XXX Example of how I expect this to be used...
2045 if (update_subclasses(type, name, invalidate_cache, NULL) < 0)
2046 return -1;
2047 */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002048 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
2049 return -1;
2050 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002051}
2052
2053static void
2054type_dealloc(PyTypeObject *type)
2055{
Guido van Rossume5c691a2003-03-07 15:13:17 +00002056 PyHeapTypeObject *et;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002057
2058 /* Assert this is a heap-allocated type object */
2059 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002060 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00002061 PyObject_ClearWeakRefs((PyObject *)type);
Guido van Rossume5c691a2003-03-07 15:13:17 +00002062 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002063 Py_XDECREF(type->tp_base);
2064 Py_XDECREF(type->tp_dict);
2065 Py_XDECREF(type->tp_bases);
2066 Py_XDECREF(type->tp_mro);
Guido van Rossum687ae002001-10-15 22:03:32 +00002067 Py_XDECREF(type->tp_cache);
Guido van Rossum1c450732001-10-08 15:18:27 +00002068 Py_XDECREF(type->tp_subclasses);
Neal Norwitzcee5ca02002-07-30 00:42:06 +00002069 PyObject_Free(type->tp_doc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002070 Py_XDECREF(et->name);
2071 Py_XDECREF(et->slots);
2072 type->ob_type->tp_free((PyObject *)type);
2073}
2074
Guido van Rossum1c450732001-10-08 15:18:27 +00002075static PyObject *
2076type_subclasses(PyTypeObject *type, PyObject *args_ignored)
2077{
2078 PyObject *list, *raw, *ref;
2079 int i, n;
2080
2081 list = PyList_New(0);
2082 if (list == NULL)
2083 return NULL;
2084 raw = type->tp_subclasses;
2085 if (raw == NULL)
2086 return list;
2087 assert(PyList_Check(raw));
2088 n = PyList_GET_SIZE(raw);
2089 for (i = 0; i < n; i++) {
2090 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00002091 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00002092 ref = PyWeakref_GET_OBJECT(ref);
2093 if (ref != Py_None) {
2094 if (PyList_Append(list, ref) < 0) {
2095 Py_DECREF(list);
2096 return NULL;
2097 }
2098 }
2099 }
2100 return list;
2101}
2102
Tim Peters6d6c1a32001-08-02 04:15:00 +00002103static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002104 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002105 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
Guido van Rossum1c450732001-10-08 15:18:27 +00002106 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002107 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002108 {0}
2109};
2110
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002111PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002112"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002113"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002114
Guido van Rossum048eb752001-10-02 21:24:57 +00002115static int
2116type_traverse(PyTypeObject *type, visitproc visit, void *arg)
2117{
Guido van Rossum048eb752001-10-02 21:24:57 +00002118 int err;
2119
Guido van Rossuma3862092002-06-10 15:24:42 +00002120 /* Because of type_is_gc(), the collector only calls this
2121 for heaptypes. */
2122 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002123
2124#define VISIT(SLOT) \
2125 if (SLOT) { \
2126 err = visit((PyObject *)(SLOT), arg); \
2127 if (err) \
2128 return err; \
2129 }
2130
2131 VISIT(type->tp_dict);
Guido van Rossum687ae002001-10-15 22:03:32 +00002132 VISIT(type->tp_cache);
Guido van Rossum048eb752001-10-02 21:24:57 +00002133 VISIT(type->tp_mro);
2134 VISIT(type->tp_bases);
2135 VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00002136
2137 /* There's no need to visit type->tp_subclasses or
Guido van Rossume5c691a2003-03-07 15:13:17 +00002138 ((PyHeapTypeObject *)type)->slots, because they can't be involved
Guido van Rossuma3862092002-06-10 15:24:42 +00002139 in cycles; tp_subclasses is a list of weak references,
2140 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00002141
2142#undef VISIT
2143
2144 return 0;
2145}
2146
2147static int
2148type_clear(PyTypeObject *type)
2149{
Guido van Rossum048eb752001-10-02 21:24:57 +00002150 PyObject *tmp;
2151
Guido van Rossuma3862092002-06-10 15:24:42 +00002152 /* Because of type_is_gc(), the collector only calls this
2153 for heaptypes. */
2154 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002155
2156#define CLEAR(SLOT) \
2157 if (SLOT) { \
2158 tmp = (PyObject *)(SLOT); \
2159 SLOT = NULL; \
2160 Py_DECREF(tmp); \
2161 }
2162
Guido van Rossuma3862092002-06-10 15:24:42 +00002163 /* The only field we need to clear is tp_mro, which is part of a
2164 hard cycle (its first element is the class itself) that won't
2165 be broken otherwise (it's a tuple and tuples don't have a
2166 tp_clear handler). None of the other fields need to be
2167 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00002168
Guido van Rossuma3862092002-06-10 15:24:42 +00002169 tp_dict:
2170 It is a dict, so the collector will call its tp_clear.
2171
2172 tp_cache:
2173 Not used; if it were, it would be a dict.
2174
2175 tp_bases, tp_base:
2176 If these are involved in a cycle, there must be at least
2177 one other, mutable object in the cycle, e.g. a base
2178 class's dict; the cycle will be broken that way.
2179
2180 tp_subclasses:
2181 A list of weak references can't be part of a cycle; and
2182 lists have their own tp_clear.
2183
Guido van Rossume5c691a2003-03-07 15:13:17 +00002184 slots (in PyHeapTypeObject):
Guido van Rossuma3862092002-06-10 15:24:42 +00002185 A tuple of strings can't be part of a cycle.
2186 */
2187
2188 CLEAR(type->tp_mro);
Tim Peters2f93e282001-10-04 05:27:00 +00002189
Guido van Rossum048eb752001-10-02 21:24:57 +00002190#undef CLEAR
2191
2192 return 0;
2193}
2194
2195static int
2196type_is_gc(PyTypeObject *type)
2197{
2198 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
2199}
2200
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002201PyTypeObject PyType_Type = {
2202 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002203 0, /* ob_size */
2204 "type", /* tp_name */
Guido van Rossume5c691a2003-03-07 15:13:17 +00002205 sizeof(PyHeapTypeObject), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00002206 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002207 (destructor)type_dealloc, /* tp_dealloc */
2208 0, /* tp_print */
2209 0, /* tp_getattr */
2210 0, /* tp_setattr */
2211 type_compare, /* tp_compare */
2212 (reprfunc)type_repr, /* tp_repr */
2213 0, /* tp_as_number */
2214 0, /* tp_as_sequence */
2215 0, /* tp_as_mapping */
2216 (hashfunc)_Py_HashPointer, /* tp_hash */
2217 (ternaryfunc)type_call, /* tp_call */
2218 0, /* tp_str */
2219 (getattrofunc)type_getattro, /* tp_getattro */
2220 (setattrofunc)type_setattro, /* tp_setattro */
2221 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00002222 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2223 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002224 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00002225 (traverseproc)type_traverse, /* tp_traverse */
2226 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002227 0, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00002228 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002229 0, /* tp_iter */
2230 0, /* tp_iternext */
2231 type_methods, /* tp_methods */
2232 type_members, /* tp_members */
2233 type_getsets, /* tp_getset */
2234 0, /* tp_base */
2235 0, /* tp_dict */
2236 0, /* tp_descr_get */
2237 0, /* tp_descr_set */
2238 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
2239 0, /* tp_init */
2240 0, /* tp_alloc */
2241 type_new, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002242 PyObject_GC_Del, /* tp_free */
Guido van Rossum048eb752001-10-02 21:24:57 +00002243 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002244};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002245
2246
2247/* The base type of all types (eventually)... except itself. */
2248
2249static int
2250object_init(PyObject *self, PyObject *args, PyObject *kwds)
2251{
2252 return 0;
2253}
2254
Guido van Rossum298e4212003-02-13 16:30:16 +00002255/* If we don't have a tp_new for a new-style class, new will use this one.
2256 Therefore this should take no arguments/keywords. However, this new may
2257 also be inherited by objects that define a tp_init but no tp_new. These
2258 objects WILL pass argumets to tp_new, because it gets the same args as
2259 tp_init. So only allow arguments if we aren't using the default init, in
2260 which case we expect init to handle argument parsing. */
2261static PyObject *
2262object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2263{
2264 if (type->tp_init == object_init && (PyTuple_GET_SIZE(args) ||
2265 (kwds && PyDict_Check(kwds) && PyDict_Size(kwds)))) {
2266 PyErr_SetString(PyExc_TypeError,
2267 "default __new__ takes no parameters");
2268 return NULL;
2269 }
2270 return type->tp_alloc(type, 0);
2271}
2272
Tim Peters6d6c1a32001-08-02 04:15:00 +00002273static void
2274object_dealloc(PyObject *self)
2275{
2276 self->ob_type->tp_free(self);
2277}
2278
Guido van Rossum8e248182001-08-12 05:17:56 +00002279static PyObject *
2280object_repr(PyObject *self)
2281{
Guido van Rossum76e69632001-08-16 18:52:43 +00002282 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00002283 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002284
Guido van Rossum76e69632001-08-16 18:52:43 +00002285 type = self->ob_type;
2286 mod = type_module(type, NULL);
2287 if (mod == NULL)
2288 PyErr_Clear();
2289 else if (!PyString_Check(mod)) {
2290 Py_DECREF(mod);
2291 mod = NULL;
2292 }
2293 name = type_name(type, NULL);
2294 if (name == NULL)
2295 return NULL;
2296 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002297 rtn = PyString_FromFormat("<%s.%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002298 PyString_AS_STRING(mod),
2299 PyString_AS_STRING(name),
2300 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002301 else
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002302 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002303 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002304 Py_XDECREF(mod);
2305 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00002306 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002307}
2308
Guido van Rossumb8f63662001-08-15 23:57:02 +00002309static PyObject *
2310object_str(PyObject *self)
2311{
2312 unaryfunc f;
2313
2314 f = self->ob_type->tp_repr;
2315 if (f == NULL)
2316 f = object_repr;
2317 return f(self);
2318}
2319
Guido van Rossum8e248182001-08-12 05:17:56 +00002320static long
2321object_hash(PyObject *self)
2322{
2323 return _Py_HashPointer(self);
2324}
Guido van Rossum8e248182001-08-12 05:17:56 +00002325
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002326static PyObject *
2327object_get_class(PyObject *self, void *closure)
2328{
2329 Py_INCREF(self->ob_type);
2330 return (PyObject *)(self->ob_type);
2331}
2332
2333static int
2334equiv_structs(PyTypeObject *a, PyTypeObject *b)
2335{
2336 return a == b ||
2337 (a != NULL &&
2338 b != NULL &&
2339 a->tp_basicsize == b->tp_basicsize &&
2340 a->tp_itemsize == b->tp_itemsize &&
2341 a->tp_dictoffset == b->tp_dictoffset &&
2342 a->tp_weaklistoffset == b->tp_weaklistoffset &&
2343 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
2344 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
2345}
2346
2347static int
2348same_slots_added(PyTypeObject *a, PyTypeObject *b)
2349{
2350 PyTypeObject *base = a->tp_base;
2351 int size;
2352
2353 if (base != b->tp_base)
2354 return 0;
2355 if (equiv_structs(a, base) && equiv_structs(b, base))
2356 return 1;
2357 size = base->tp_basicsize;
2358 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
2359 size += sizeof(PyObject *);
2360 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
2361 size += sizeof(PyObject *);
2362 return size == a->tp_basicsize && size == b->tp_basicsize;
2363}
2364
2365static int
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002366compatible_for_assignment(PyTypeObject* old, PyTypeObject* new, char* attr)
2367{
2368 PyTypeObject *newbase, *oldbase;
2369
2370 if (new->tp_dealloc != old->tp_dealloc ||
2371 new->tp_free != old->tp_free)
2372 {
2373 PyErr_Format(PyExc_TypeError,
2374 "%s assignment: "
2375 "'%s' deallocator differs from '%s'",
2376 attr,
2377 new->tp_name,
2378 old->tp_name);
2379 return 0;
2380 }
2381 newbase = new;
2382 oldbase = old;
2383 while (equiv_structs(newbase, newbase->tp_base))
2384 newbase = newbase->tp_base;
2385 while (equiv_structs(oldbase, oldbase->tp_base))
2386 oldbase = oldbase->tp_base;
2387 if (newbase != oldbase &&
2388 (newbase->tp_base != oldbase->tp_base ||
2389 !same_slots_added(newbase, oldbase))) {
2390 PyErr_Format(PyExc_TypeError,
2391 "%s assignment: "
2392 "'%s' object layout differs from '%s'",
2393 attr,
2394 new->tp_name,
2395 old->tp_name);
2396 return 0;
2397 }
Tim Petersea7f75d2002-12-07 21:39:16 +00002398
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002399 return 1;
2400}
2401
2402static int
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002403object_set_class(PyObject *self, PyObject *value, void *closure)
2404{
2405 PyTypeObject *old = self->ob_type;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002406 PyTypeObject *new;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002407
Guido van Rossumb6b89422002-04-15 01:03:30 +00002408 if (value == NULL) {
2409 PyErr_SetString(PyExc_TypeError,
2410 "can't delete __class__ attribute");
2411 return -1;
2412 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002413 if (!PyType_Check(value)) {
2414 PyErr_Format(PyExc_TypeError,
2415 "__class__ must be set to new-style class, not '%s' object",
2416 value->ob_type->tp_name);
2417 return -1;
2418 }
2419 new = (PyTypeObject *)value;
Guido van Rossum40af8892002-08-10 05:42:07 +00002420 if (!(new->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
2421 !(old->tp_flags & Py_TPFLAGS_HEAPTYPE))
2422 {
2423 PyErr_Format(PyExc_TypeError,
2424 "__class__ assignment: only for heap types");
2425 return -1;
2426 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002427 if (compatible_for_assignment(new, old, "__class__")) {
2428 Py_INCREF(new);
2429 self->ob_type = new;
2430 Py_DECREF(old);
2431 return 0;
2432 }
2433 else {
Guido van Rossum9ee4b942002-05-24 18:47:47 +00002434 return -1;
2435 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002436}
2437
2438static PyGetSetDef object_getsets[] = {
2439 {"__class__", object_get_class, object_set_class,
Neal Norwitz858e34f2002-08-13 17:18:45 +00002440 PyDoc_STR("the object's class")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002441 {0}
2442};
2443
Guido van Rossumc53f0092003-02-18 22:05:12 +00002444
Guido van Rossum036f9992003-02-21 22:02:54 +00002445/* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
2446 We fall back to helpers in copy_reg for:
2447 - pickle protocols < 2
2448 - calculating the list of slot names (done only once per class)
2449 - the __newobj__ function (which is used as a token but never called)
2450*/
2451
2452static PyObject *
2453import_copy_reg(void)
2454{
2455 static PyObject *copy_reg_str;
Guido van Rossum3926a632001-09-25 16:25:58 +00002456
2457 if (!copy_reg_str) {
2458 copy_reg_str = PyString_InternFromString("copy_reg");
2459 if (copy_reg_str == NULL)
2460 return NULL;
2461 }
Guido van Rossum036f9992003-02-21 22:02:54 +00002462
2463 return PyImport_Import(copy_reg_str);
2464}
2465
2466static PyObject *
2467slotnames(PyObject *cls)
2468{
2469 PyObject *clsdict;
2470 PyObject *copy_reg;
2471 PyObject *slotnames;
2472
2473 if (!PyType_Check(cls)) {
2474 Py_INCREF(Py_None);
2475 return Py_None;
2476 }
2477
2478 clsdict = ((PyTypeObject *)cls)->tp_dict;
2479 slotnames = PyDict_GetItemString(clsdict, "__slotnames__");
2480 if (slotnames != NULL) {
2481 Py_INCREF(slotnames);
2482 return slotnames;
2483 }
2484
2485 copy_reg = import_copy_reg();
2486 if (copy_reg == NULL)
2487 return NULL;
2488
2489 slotnames = PyObject_CallMethod(copy_reg, "_slotnames", "O", cls);
2490 Py_DECREF(copy_reg);
2491 if (slotnames != NULL &&
2492 slotnames != Py_None &&
2493 !PyList_Check(slotnames))
2494 {
2495 PyErr_SetString(PyExc_TypeError,
2496 "copy_reg._slotnames didn't return a list or None");
2497 Py_DECREF(slotnames);
2498 slotnames = NULL;
2499 }
2500
2501 return slotnames;
2502}
2503
2504static PyObject *
2505reduce_2(PyObject *obj)
2506{
2507 PyObject *cls, *getnewargs;
2508 PyObject *args = NULL, *args2 = NULL;
2509 PyObject *getstate = NULL, *state = NULL, *names = NULL;
2510 PyObject *slots = NULL, *listitems = NULL, *dictitems = NULL;
2511 PyObject *copy_reg = NULL, *newobj = NULL, *res = NULL;
2512 int i, n;
2513
2514 cls = PyObject_GetAttrString(obj, "__class__");
2515 if (cls == NULL)
2516 return NULL;
2517
2518 getnewargs = PyObject_GetAttrString(obj, "__getnewargs__");
2519 if (getnewargs != NULL) {
2520 args = PyObject_CallObject(getnewargs, NULL);
2521 Py_DECREF(getnewargs);
2522 if (args != NULL && !PyTuple_Check(args)) {
2523 PyErr_SetString(PyExc_TypeError,
2524 "__getnewargs__ should return a tuple");
2525 goto end;
2526 }
2527 }
2528 else {
2529 PyErr_Clear();
2530 args = PyTuple_New(0);
2531 }
2532 if (args == NULL)
2533 goto end;
2534
2535 getstate = PyObject_GetAttrString(obj, "__getstate__");
2536 if (getstate != NULL) {
2537 state = PyObject_CallObject(getstate, NULL);
2538 Py_DECREF(getstate);
2539 }
2540 else {
2541 state = PyObject_GetAttrString(obj, "__dict__");
2542 if (state == NULL) {
2543 PyErr_Clear();
2544 state = Py_None;
2545 Py_INCREF(state);
2546 }
2547 names = slotnames(cls);
2548 if (names == NULL)
2549 goto end;
2550 if (names != Py_None) {
2551 assert(PyList_Check(names));
2552 slots = PyDict_New();
2553 if (slots == NULL)
2554 goto end;
2555 n = 0;
2556 /* Can't pre-compute the list size; the list
2557 is stored on the class so accessible to other
2558 threads, which may be run by DECREF */
2559 for (i = 0; i < PyList_GET_SIZE(names); i++) {
2560 PyObject *name, *value;
2561 name = PyList_GET_ITEM(names, i);
2562 value = PyObject_GetAttr(obj, name);
2563 if (value == NULL)
2564 PyErr_Clear();
2565 else {
2566 int err = PyDict_SetItem(slots, name,
2567 value);
2568 Py_DECREF(value);
2569 if (err)
2570 goto end;
2571 n++;
2572 }
2573 }
2574 if (n) {
2575 state = Py_BuildValue("(NO)", state, slots);
2576 if (state == NULL)
2577 goto end;
2578 }
2579 }
2580 }
2581
2582 if (!PyList_Check(obj)) {
2583 listitems = Py_None;
2584 Py_INCREF(listitems);
2585 }
2586 else {
2587 listitems = PyObject_GetIter(obj);
2588 if (listitems == NULL)
2589 goto end;
2590 }
2591
2592 if (!PyDict_Check(obj)) {
2593 dictitems = Py_None;
2594 Py_INCREF(dictitems);
2595 }
2596 else {
2597 dictitems = PyObject_CallMethod(obj, "iteritems", "");
2598 if (dictitems == NULL)
2599 goto end;
2600 }
2601
2602 copy_reg = import_copy_reg();
2603 if (copy_reg == NULL)
2604 goto end;
2605 newobj = PyObject_GetAttrString(copy_reg, "__newobj__");
2606 if (newobj == NULL)
2607 goto end;
2608
2609 n = PyTuple_GET_SIZE(args);
2610 args2 = PyTuple_New(n+1);
2611 if (args2 == NULL)
2612 goto end;
2613 PyTuple_SET_ITEM(args2, 0, cls);
2614 cls = NULL;
2615 for (i = 0; i < n; i++) {
2616 PyObject *v = PyTuple_GET_ITEM(args, i);
2617 Py_INCREF(v);
2618 PyTuple_SET_ITEM(args2, i+1, v);
2619 }
2620
2621 res = Py_BuildValue("(OOOOO)",
2622 newobj, args2, state, listitems, dictitems);
2623
2624 end:
2625 Py_XDECREF(cls);
2626 Py_XDECREF(args);
2627 Py_XDECREF(args2);
Jeremy Hyltond06483c2003-04-09 21:01:42 +00002628 Py_XDECREF(slots);
Guido van Rossum036f9992003-02-21 22:02:54 +00002629 Py_XDECREF(state);
2630 Py_XDECREF(names);
2631 Py_XDECREF(listitems);
2632 Py_XDECREF(dictitems);
2633 Py_XDECREF(copy_reg);
2634 Py_XDECREF(newobj);
2635 return res;
2636}
2637
2638static PyObject *
2639object_reduce_ex(PyObject *self, PyObject *args)
2640{
2641 /* Call copy_reg._reduce_ex(self, proto) */
2642 PyObject *reduce, *copy_reg, *res;
2643 int proto = 0;
2644
2645 if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
2646 return NULL;
2647
2648 reduce = PyObject_GetAttrString(self, "__reduce__");
2649 if (reduce == NULL)
2650 PyErr_Clear();
2651 else {
2652 PyObject *cls, *clsreduce, *objreduce;
2653 int override;
2654 cls = PyObject_GetAttrString(self, "__class__");
2655 if (cls == NULL) {
2656 Py_DECREF(reduce);
2657 return NULL;
2658 }
2659 clsreduce = PyObject_GetAttrString(cls, "__reduce__");
2660 Py_DECREF(cls);
2661 if (clsreduce == NULL) {
2662 Py_DECREF(reduce);
2663 return NULL;
2664 }
2665 objreduce = PyDict_GetItemString(PyBaseObject_Type.tp_dict,
2666 "__reduce__");
2667 override = (clsreduce != objreduce);
2668 Py_DECREF(clsreduce);
2669 if (override) {
2670 res = PyObject_CallObject(reduce, NULL);
2671 Py_DECREF(reduce);
2672 return res;
2673 }
2674 else
2675 Py_DECREF(reduce);
2676 }
2677
2678 if (proto >= 2)
2679 return reduce_2(self);
2680
2681 copy_reg = import_copy_reg();
Guido van Rossum3926a632001-09-25 16:25:58 +00002682 if (!copy_reg)
2683 return NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00002684
Guido van Rossumc53f0092003-02-18 22:05:12 +00002685 res = PyEval_CallMethod(copy_reg, "_reduce_ex", "(Oi)", self, proto);
Guido van Rossum3926a632001-09-25 16:25:58 +00002686 Py_DECREF(copy_reg);
Guido van Rossum036f9992003-02-21 22:02:54 +00002687
Guido van Rossum3926a632001-09-25 16:25:58 +00002688 return res;
2689}
2690
2691static PyMethodDef object_methods[] = {
Guido van Rossumc53f0092003-02-18 22:05:12 +00002692 {"__reduce_ex__", object_reduce_ex, METH_VARARGS,
2693 PyDoc_STR("helper for pickle")},
2694 {"__reduce__", object_reduce_ex, METH_VARARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002695 PyDoc_STR("helper for pickle")},
Guido van Rossum3926a632001-09-25 16:25:58 +00002696 {0}
2697};
2698
Guido van Rossum036f9992003-02-21 22:02:54 +00002699
Tim Peters6d6c1a32001-08-02 04:15:00 +00002700PyTypeObject PyBaseObject_Type = {
2701 PyObject_HEAD_INIT(&PyType_Type)
2702 0, /* ob_size */
2703 "object", /* tp_name */
2704 sizeof(PyObject), /* tp_basicsize */
2705 0, /* tp_itemsize */
2706 (destructor)object_dealloc, /* tp_dealloc */
2707 0, /* tp_print */
2708 0, /* tp_getattr */
2709 0, /* tp_setattr */
2710 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002711 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002712 0, /* tp_as_number */
2713 0, /* tp_as_sequence */
2714 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002715 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002716 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002717 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002718 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002719 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002720 0, /* tp_as_buffer */
2721 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002722 PyDoc_STR("The most base type"), /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002723 0, /* tp_traverse */
2724 0, /* tp_clear */
2725 0, /* tp_richcompare */
2726 0, /* tp_weaklistoffset */
2727 0, /* tp_iter */
2728 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00002729 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002730 0, /* tp_members */
2731 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002732 0, /* tp_base */
2733 0, /* tp_dict */
2734 0, /* tp_descr_get */
2735 0, /* tp_descr_set */
2736 0, /* tp_dictoffset */
2737 object_init, /* tp_init */
2738 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossum298e4212003-02-13 16:30:16 +00002739 object_new, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002740 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002741};
2742
2743
2744/* Initialize the __dict__ in a type object */
2745
2746static int
2747add_methods(PyTypeObject *type, PyMethodDef *meth)
2748{
Guido van Rossum687ae002001-10-15 22:03:32 +00002749 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002750
2751 for (; meth->ml_name != NULL; meth++) {
2752 PyObject *descr;
2753 if (PyDict_GetItemString(dict, meth->ml_name))
2754 continue;
Fred Drake7bf97152002-03-28 05:33:33 +00002755 if (meth->ml_flags & METH_CLASS) {
2756 if (meth->ml_flags & METH_STATIC) {
2757 PyErr_SetString(PyExc_ValueError,
2758 "method cannot be both class and static");
2759 return -1;
2760 }
Tim Petersbca1cbc2002-12-09 22:56:13 +00002761 descr = PyDescr_NewClassMethod(type, meth);
Fred Drake7bf97152002-03-28 05:33:33 +00002762 }
2763 else if (meth->ml_flags & METH_STATIC) {
Guido van Rossum9af48ff2003-02-11 17:12:46 +00002764 PyObject *cfunc = PyCFunction_New(meth, NULL);
2765 if (cfunc == NULL)
2766 return -1;
2767 descr = PyStaticMethod_New(cfunc);
2768 Py_DECREF(cfunc);
Fred Drake7bf97152002-03-28 05:33:33 +00002769 }
2770 else {
2771 descr = PyDescr_NewMethod(type, meth);
2772 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002773 if (descr == NULL)
2774 return -1;
Fred Drake7bf97152002-03-28 05:33:33 +00002775 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002776 return -1;
2777 Py_DECREF(descr);
2778 }
2779 return 0;
2780}
2781
2782static int
Guido van Rossum6f799372001-09-20 20:46:19 +00002783add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002784{
Guido van Rossum687ae002001-10-15 22:03:32 +00002785 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002786
2787 for (; memb->name != NULL; memb++) {
2788 PyObject *descr;
2789 if (PyDict_GetItemString(dict, memb->name))
2790 continue;
2791 descr = PyDescr_NewMember(type, memb);
2792 if (descr == NULL)
2793 return -1;
2794 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
2795 return -1;
2796 Py_DECREF(descr);
2797 }
2798 return 0;
2799}
2800
2801static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00002802add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002803{
Guido van Rossum687ae002001-10-15 22:03:32 +00002804 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002805
2806 for (; gsp->name != NULL; gsp++) {
2807 PyObject *descr;
2808 if (PyDict_GetItemString(dict, gsp->name))
2809 continue;
2810 descr = PyDescr_NewGetSet(type, gsp);
2811
2812 if (descr == NULL)
2813 return -1;
2814 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
2815 return -1;
2816 Py_DECREF(descr);
2817 }
2818 return 0;
2819}
2820
Guido van Rossum13d52f02001-08-10 21:24:08 +00002821static void
2822inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002823{
2824 int oldsize, newsize;
2825
Guido van Rossum13d52f02001-08-10 21:24:08 +00002826 /* Special flag magic */
2827 if (!type->tp_as_buffer && base->tp_as_buffer) {
2828 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
2829 type->tp_flags |=
2830 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
2831 }
2832 if (!type->tp_as_sequence && base->tp_as_sequence) {
2833 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
2834 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
2835 }
2836 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
2837 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
2838 if ((!type->tp_as_number && base->tp_as_number) ||
2839 (!type->tp_as_sequence && base->tp_as_sequence)) {
2840 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
2841 if (!type->tp_as_number && !type->tp_as_sequence) {
2842 type->tp_flags |= base->tp_flags &
2843 Py_TPFLAGS_HAVE_INPLACEOPS;
2844 }
2845 }
2846 /* Wow */
2847 }
2848 if (!type->tp_as_number && base->tp_as_number) {
2849 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
2850 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
2851 }
2852
2853 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00002854 oldsize = base->tp_basicsize;
2855 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
2856 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
2857 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00002858 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
2859 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00002860 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00002861 if (type->tp_traverse == NULL)
2862 type->tp_traverse = base->tp_traverse;
2863 if (type->tp_clear == NULL)
2864 type->tp_clear = base->tp_clear;
2865 }
2866 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
Guido van Rossumf884b742001-12-17 17:14:22 +00002867 /* The condition below could use some explanation.
2868 It appears that tp_new is not inherited for static types
2869 whose base class is 'object'; this seems to be a precaution
2870 so that old extension types don't suddenly become
2871 callable (object.__new__ wouldn't insure the invariants
2872 that the extension type's own factory function ensures).
2873 Heap types, of course, are under our control, so they do
2874 inherit tp_new; static extension types that specify some
2875 other built-in type as the default are considered
2876 new-style-aware so they also inherit object.__new__. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002877 if (base != &PyBaseObject_Type ||
2878 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2879 if (type->tp_new == NULL)
2880 type->tp_new = base->tp_new;
2881 }
2882 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00002883 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00002884
2885 /* Copy other non-function slots */
2886
2887#undef COPYVAL
2888#define COPYVAL(SLOT) \
2889 if (type->SLOT == 0) type->SLOT = base->SLOT
2890
2891 COPYVAL(tp_itemsize);
2892 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
2893 COPYVAL(tp_weaklistoffset);
2894 }
2895 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2896 COPYVAL(tp_dictoffset);
2897 }
Guido van Rossum13d52f02001-08-10 21:24:08 +00002898}
2899
2900static void
2901inherit_slots(PyTypeObject *type, PyTypeObject *base)
2902{
2903 PyTypeObject *basebase;
2904
2905#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00002906#undef COPYSLOT
2907#undef COPYNUM
2908#undef COPYSEQ
2909#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00002910#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00002911
2912#define SLOTDEFINED(SLOT) \
2913 (base->SLOT != 0 && \
2914 (basebase == NULL || base->SLOT != basebase->SLOT))
2915
Tim Peters6d6c1a32001-08-02 04:15:00 +00002916#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00002917 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00002918
2919#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
2920#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
2921#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00002922#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002923
Guido van Rossum13d52f02001-08-10 21:24:08 +00002924 /* This won't inherit indirect slots (from tp_as_number etc.)
2925 if type doesn't provide the space. */
2926
2927 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
2928 basebase = base->tp_base;
2929 if (basebase->tp_as_number == NULL)
2930 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002931 COPYNUM(nb_add);
2932 COPYNUM(nb_subtract);
2933 COPYNUM(nb_multiply);
2934 COPYNUM(nb_divide);
2935 COPYNUM(nb_remainder);
2936 COPYNUM(nb_divmod);
2937 COPYNUM(nb_power);
2938 COPYNUM(nb_negative);
2939 COPYNUM(nb_positive);
2940 COPYNUM(nb_absolute);
2941 COPYNUM(nb_nonzero);
2942 COPYNUM(nb_invert);
2943 COPYNUM(nb_lshift);
2944 COPYNUM(nb_rshift);
2945 COPYNUM(nb_and);
2946 COPYNUM(nb_xor);
2947 COPYNUM(nb_or);
2948 COPYNUM(nb_coerce);
2949 COPYNUM(nb_int);
2950 COPYNUM(nb_long);
2951 COPYNUM(nb_float);
2952 COPYNUM(nb_oct);
2953 COPYNUM(nb_hex);
2954 COPYNUM(nb_inplace_add);
2955 COPYNUM(nb_inplace_subtract);
2956 COPYNUM(nb_inplace_multiply);
2957 COPYNUM(nb_inplace_divide);
2958 COPYNUM(nb_inplace_remainder);
2959 COPYNUM(nb_inplace_power);
2960 COPYNUM(nb_inplace_lshift);
2961 COPYNUM(nb_inplace_rshift);
2962 COPYNUM(nb_inplace_and);
2963 COPYNUM(nb_inplace_xor);
2964 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00002965 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
2966 COPYNUM(nb_true_divide);
2967 COPYNUM(nb_floor_divide);
2968 COPYNUM(nb_inplace_true_divide);
2969 COPYNUM(nb_inplace_floor_divide);
2970 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002971 }
2972
Guido van Rossum13d52f02001-08-10 21:24:08 +00002973 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
2974 basebase = base->tp_base;
2975 if (basebase->tp_as_sequence == NULL)
2976 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002977 COPYSEQ(sq_length);
2978 COPYSEQ(sq_concat);
2979 COPYSEQ(sq_repeat);
2980 COPYSEQ(sq_item);
2981 COPYSEQ(sq_slice);
2982 COPYSEQ(sq_ass_item);
2983 COPYSEQ(sq_ass_slice);
2984 COPYSEQ(sq_contains);
2985 COPYSEQ(sq_inplace_concat);
2986 COPYSEQ(sq_inplace_repeat);
2987 }
2988
Guido van Rossum13d52f02001-08-10 21:24:08 +00002989 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
2990 basebase = base->tp_base;
2991 if (basebase->tp_as_mapping == NULL)
2992 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002993 COPYMAP(mp_length);
2994 COPYMAP(mp_subscript);
2995 COPYMAP(mp_ass_subscript);
2996 }
2997
Tim Petersfc57ccb2001-10-12 02:38:24 +00002998 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
2999 basebase = base->tp_base;
3000 if (basebase->tp_as_buffer == NULL)
3001 basebase = NULL;
3002 COPYBUF(bf_getreadbuffer);
3003 COPYBUF(bf_getwritebuffer);
3004 COPYBUF(bf_getsegcount);
3005 COPYBUF(bf_getcharbuffer);
3006 }
3007
Guido van Rossum13d52f02001-08-10 21:24:08 +00003008 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003009
Tim Peters6d6c1a32001-08-02 04:15:00 +00003010 COPYSLOT(tp_dealloc);
3011 COPYSLOT(tp_print);
3012 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
3013 type->tp_getattr = base->tp_getattr;
3014 type->tp_getattro = base->tp_getattro;
3015 }
3016 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
3017 type->tp_setattr = base->tp_setattr;
3018 type->tp_setattro = base->tp_setattro;
3019 }
3020 /* tp_compare see tp_richcompare */
3021 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003022 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003023 COPYSLOT(tp_call);
3024 COPYSLOT(tp_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003025 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003026 if (type->tp_compare == NULL &&
3027 type->tp_richcompare == NULL &&
3028 type->tp_hash == NULL)
3029 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003030 type->tp_compare = base->tp_compare;
3031 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003032 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003033 }
3034 }
3035 else {
3036 COPYSLOT(tp_compare);
3037 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003038 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
3039 COPYSLOT(tp_iter);
3040 COPYSLOT(tp_iternext);
3041 }
3042 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
3043 COPYSLOT(tp_descr_get);
3044 COPYSLOT(tp_descr_set);
3045 COPYSLOT(tp_dictoffset);
3046 COPYSLOT(tp_init);
3047 COPYSLOT(tp_alloc);
Guido van Rossumcc8fe042002-04-05 17:10:16 +00003048 COPYSLOT(tp_is_gc);
Tim Peters3cfe7542003-05-21 21:29:48 +00003049 if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) ==
3050 (base->tp_flags & Py_TPFLAGS_HAVE_GC)) {
3051 /* They agree about gc. */
3052 COPYSLOT(tp_free);
3053 }
3054 else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3055 type->tp_free == NULL &&
3056 base->tp_free == _PyObject_Del) {
3057 /* A bit of magic to plug in the correct default
3058 * tp_free function when a derived class adds gc,
3059 * didn't define tp_free, and the base uses the
3060 * default non-gc tp_free.
3061 */
3062 type->tp_free = PyObject_GC_Del;
3063 }
3064 /* else they didn't agree about gc, and there isn't something
3065 * obvious to be done -- the type is on its own.
3066 */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003067 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003068}
3069
Jeremy Hylton938ace62002-07-17 16:30:39 +00003070static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00003071
Tim Peters6d6c1a32001-08-02 04:15:00 +00003072int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00003073PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003074{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003075 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003076 PyTypeObject *base;
3077 int i, n;
3078
Guido van Rossumcab05802002-06-10 15:29:03 +00003079 if (type->tp_flags & Py_TPFLAGS_READY) {
3080 assert(type->tp_dict != NULL);
Guido van Rossumd614f972001-08-10 17:39:49 +00003081 return 0;
Guido van Rossumcab05802002-06-10 15:29:03 +00003082 }
Guido van Rossumd614f972001-08-10 17:39:49 +00003083 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00003084
3085 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003086
Tim Peters36eb4df2003-03-23 03:33:13 +00003087#ifdef Py_TRACE_REFS
3088 /* PyType_Ready is the closest thing we have to a choke point
3089 * for type objects, so is the best place I can think of to try
3090 * to get type objects into the doubly-linked list of all objects.
3091 * Still, not all type objects go thru PyType_Ready.
3092 */
Tim Peters7571a0f2003-03-23 17:52:28 +00003093 _Py_AddToAllObjects((PyObject *)type, 0);
Tim Peters36eb4df2003-03-23 03:33:13 +00003094#endif
3095
Tim Peters6d6c1a32001-08-02 04:15:00 +00003096 /* Initialize tp_base (defaults to BaseObject unless that's us) */
3097 base = type->tp_base;
3098 if (base == NULL && type != &PyBaseObject_Type)
3099 base = type->tp_base = &PyBaseObject_Type;
3100
Guido van Rossum323a9cf2002-08-14 17:26:30 +00003101 /* Initialize the base class */
3102 if (base && base->tp_dict == NULL) {
3103 if (PyType_Ready(base) < 0)
3104 goto error;
3105 }
3106
Guido van Rossum0986d822002-04-08 01:38:42 +00003107 /* Initialize ob_type if NULL. This means extensions that want to be
3108 compilable separately on Windows can call PyType_Ready() instead of
3109 initializing the ob_type field of their type objects. */
3110 if (type->ob_type == NULL)
3111 type->ob_type = base->ob_type;
3112
Tim Peters6d6c1a32001-08-02 04:15:00 +00003113 /* Initialize tp_bases */
3114 bases = type->tp_bases;
3115 if (bases == NULL) {
3116 if (base == NULL)
3117 bases = PyTuple_New(0);
3118 else
3119 bases = Py_BuildValue("(O)", base);
3120 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003121 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003122 type->tp_bases = bases;
3123 }
3124
Guido van Rossum687ae002001-10-15 22:03:32 +00003125 /* Initialize tp_dict */
3126 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003127 if (dict == NULL) {
3128 dict = PyDict_New();
3129 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003130 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00003131 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003132 }
3133
Guido van Rossum687ae002001-10-15 22:03:32 +00003134 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003135 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003136 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003137 if (type->tp_methods != NULL) {
3138 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003139 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003140 }
3141 if (type->tp_members != NULL) {
3142 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003143 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003144 }
3145 if (type->tp_getset != NULL) {
3146 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003147 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003148 }
3149
Tim Peters6d6c1a32001-08-02 04:15:00 +00003150 /* Calculate method resolution order */
3151 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00003152 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003153 }
3154
Guido van Rossum13d52f02001-08-10 21:24:08 +00003155 /* Inherit special flags from dominant base */
3156 if (type->tp_base != NULL)
3157 inherit_special(type, type->tp_base);
3158
Tim Peters6d6c1a32001-08-02 04:15:00 +00003159 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003160 bases = type->tp_mro;
3161 assert(bases != NULL);
3162 assert(PyTuple_Check(bases));
3163 n = PyTuple_GET_SIZE(bases);
3164 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003165 PyObject *b = PyTuple_GET_ITEM(bases, i);
3166 if (PyType_Check(b))
3167 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003168 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003169
Tim Peters3cfe7542003-05-21 21:29:48 +00003170 /* Sanity check for tp_free. */
3171 if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) &&
3172 (type->tp_free == NULL || type->tp_free == PyObject_Del)) {
3173 /* This base class needs to call tp_free, but doesn't have
3174 * one, or its tp_free is for non-gc'ed objects.
3175 */
3176 PyErr_Format(PyExc_TypeError, "type '%.100s' participates in "
3177 "gc and is a base type but has inappropriate "
3178 "tp_free slot",
3179 type->tp_name);
3180 goto error;
3181 }
3182
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003183 /* if the type dictionary doesn't contain a __doc__, set it from
3184 the tp_doc slot.
3185 */
3186 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
3187 if (type->tp_doc != NULL) {
3188 PyObject *doc = PyString_FromString(type->tp_doc);
3189 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
3190 Py_DECREF(doc);
3191 } else {
Guido van Rossumd4641072002-04-03 02:13:37 +00003192 PyDict_SetItemString(type->tp_dict,
3193 "__doc__", Py_None);
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003194 }
3195 }
3196
Guido van Rossum13d52f02001-08-10 21:24:08 +00003197 /* Some more special stuff */
3198 base = type->tp_base;
3199 if (base != NULL) {
3200 if (type->tp_as_number == NULL)
3201 type->tp_as_number = base->tp_as_number;
3202 if (type->tp_as_sequence == NULL)
3203 type->tp_as_sequence = base->tp_as_sequence;
3204 if (type->tp_as_mapping == NULL)
3205 type->tp_as_mapping = base->tp_as_mapping;
Guido van Rossumeea47182003-02-11 20:39:59 +00003206 if (type->tp_as_buffer == NULL)
3207 type->tp_as_buffer = base->tp_as_buffer;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003208 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003209
Guido van Rossum1c450732001-10-08 15:18:27 +00003210 /* Link into each base class's list of subclasses */
3211 bases = type->tp_bases;
3212 n = PyTuple_GET_SIZE(bases);
3213 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003214 PyObject *b = PyTuple_GET_ITEM(bases, i);
3215 if (PyType_Check(b) &&
3216 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00003217 goto error;
3218 }
3219
Guido van Rossum13d52f02001-08-10 21:24:08 +00003220 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00003221 assert(type->tp_dict != NULL);
3222 type->tp_flags =
3223 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003224 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00003225
3226 error:
3227 type->tp_flags &= ~Py_TPFLAGS_READYING;
3228 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003229}
3230
Guido van Rossum1c450732001-10-08 15:18:27 +00003231static int
3232add_subclass(PyTypeObject *base, PyTypeObject *type)
3233{
3234 int i;
3235 PyObject *list, *ref, *new;
3236
3237 list = base->tp_subclasses;
3238 if (list == NULL) {
3239 base->tp_subclasses = list = PyList_New(0);
3240 if (list == NULL)
3241 return -1;
3242 }
3243 assert(PyList_Check(list));
3244 new = PyWeakref_NewRef((PyObject *)type, NULL);
3245 i = PyList_GET_SIZE(list);
3246 while (--i >= 0) {
3247 ref = PyList_GET_ITEM(list, i);
3248 assert(PyWeakref_CheckRef(ref));
Guido van Rossum3930bc32002-10-18 13:51:49 +00003249 if (PyWeakref_GET_OBJECT(ref) == Py_None)
3250 return PyList_SetItem(list, i, new);
Guido van Rossum1c450732001-10-08 15:18:27 +00003251 }
3252 i = PyList_Append(list, new);
3253 Py_DECREF(new);
3254 return i;
3255}
3256
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003257static void
3258remove_subclass(PyTypeObject *base, PyTypeObject *type)
3259{
3260 int i;
3261 PyObject *list, *ref;
3262
3263 list = base->tp_subclasses;
3264 if (list == NULL) {
3265 return;
3266 }
3267 assert(PyList_Check(list));
3268 i = PyList_GET_SIZE(list);
3269 while (--i >= 0) {
3270 ref = PyList_GET_ITEM(list, i);
3271 assert(PyWeakref_CheckRef(ref));
3272 if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
3273 /* this can't fail, right? */
3274 PySequence_DelItem(list, i);
3275 return;
3276 }
3277 }
3278}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003279
3280/* Generic wrappers for overloadable 'operators' such as __getitem__ */
3281
3282/* There's a wrapper *function* for each distinct function typedef used
3283 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
3284 wrapper *table* for each distinct operation (e.g. __len__, __add__).
3285 Most tables have only one entry; the tables for binary operators have two
3286 entries, one regular and one with reversed arguments. */
3287
3288static PyObject *
3289wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
3290{
3291 inquiry func = (inquiry)wrapped;
3292 int res;
3293
3294 if (!PyArg_ParseTuple(args, ""))
3295 return NULL;
3296 res = (*func)(self);
3297 if (res == -1 && PyErr_Occurred())
3298 return NULL;
3299 return PyInt_FromLong((long)res);
3300}
3301
Tim Peters6d6c1a32001-08-02 04:15:00 +00003302static PyObject *
3303wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
3304{
3305 binaryfunc func = (binaryfunc)wrapped;
3306 PyObject *other;
3307
3308 if (!PyArg_ParseTuple(args, "O", &other))
3309 return NULL;
3310 return (*func)(self, other);
3311}
3312
3313static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003314wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
3315{
3316 binaryfunc func = (binaryfunc)wrapped;
3317 PyObject *other;
3318
3319 if (!PyArg_ParseTuple(args, "O", &other))
3320 return NULL;
3321 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003322 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003323 Py_INCREF(Py_NotImplemented);
3324 return Py_NotImplemented;
3325 }
3326 return (*func)(self, other);
3327}
3328
3329static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003330wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3331{
3332 binaryfunc func = (binaryfunc)wrapped;
3333 PyObject *other;
3334
3335 if (!PyArg_ParseTuple(args, "O", &other))
3336 return NULL;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003337 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003338 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003339 Py_INCREF(Py_NotImplemented);
3340 return Py_NotImplemented;
3341 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003342 return (*func)(other, self);
3343}
3344
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003345static PyObject *
3346wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
3347{
3348 coercion func = (coercion)wrapped;
3349 PyObject *other, *res;
3350 int ok;
3351
3352 if (!PyArg_ParseTuple(args, "O", &other))
3353 return NULL;
3354 ok = func(&self, &other);
3355 if (ok < 0)
3356 return NULL;
3357 if (ok > 0) {
3358 Py_INCREF(Py_NotImplemented);
3359 return Py_NotImplemented;
3360 }
3361 res = PyTuple_New(2);
3362 if (res == NULL) {
3363 Py_DECREF(self);
3364 Py_DECREF(other);
3365 return NULL;
3366 }
3367 PyTuple_SET_ITEM(res, 0, self);
3368 PyTuple_SET_ITEM(res, 1, other);
3369 return res;
3370}
3371
Tim Peters6d6c1a32001-08-02 04:15:00 +00003372static PyObject *
3373wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
3374{
3375 ternaryfunc func = (ternaryfunc)wrapped;
3376 PyObject *other;
3377 PyObject *third = Py_None;
3378
3379 /* Note: This wrapper only works for __pow__() */
3380
3381 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
3382 return NULL;
3383 return (*func)(self, other, third);
3384}
3385
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00003386static PyObject *
3387wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3388{
3389 ternaryfunc func = (ternaryfunc)wrapped;
3390 PyObject *other;
3391 PyObject *third = Py_None;
3392
3393 /* Note: This wrapper only works for __pow__() */
3394
3395 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
3396 return NULL;
3397 return (*func)(other, self, third);
3398}
3399
Tim Peters6d6c1a32001-08-02 04:15:00 +00003400static PyObject *
3401wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
3402{
3403 unaryfunc func = (unaryfunc)wrapped;
3404
3405 if (!PyArg_ParseTuple(args, ""))
3406 return NULL;
3407 return (*func)(self);
3408}
3409
Tim Peters6d6c1a32001-08-02 04:15:00 +00003410static PyObject *
3411wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
3412{
3413 intargfunc func = (intargfunc)wrapped;
3414 int i;
3415
3416 if (!PyArg_ParseTuple(args, "i", &i))
3417 return NULL;
3418 return (*func)(self, i);
3419}
3420
Guido van Rossum5d815f32001-08-17 21:57:47 +00003421static int
3422getindex(PyObject *self, PyObject *arg)
3423{
3424 int i;
3425
3426 i = PyInt_AsLong(arg);
3427 if (i == -1 && PyErr_Occurred())
3428 return -1;
3429 if (i < 0) {
3430 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
3431 if (sq && sq->sq_length) {
3432 int n = (*sq->sq_length)(self);
3433 if (n < 0)
3434 return -1;
3435 i += n;
3436 }
3437 }
3438 return i;
3439}
3440
3441static PyObject *
3442wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
3443{
3444 intargfunc func = (intargfunc)wrapped;
3445 PyObject *arg;
3446 int i;
3447
Guido van Rossumf4593e02001-10-03 12:09:30 +00003448 if (PyTuple_GET_SIZE(args) == 1) {
3449 arg = PyTuple_GET_ITEM(args, 0);
3450 i = getindex(self, arg);
3451 if (i == -1 && PyErr_Occurred())
3452 return NULL;
3453 return (*func)(self, i);
3454 }
3455 PyArg_ParseTuple(args, "O", &arg);
3456 assert(PyErr_Occurred());
3457 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003458}
3459
Tim Peters6d6c1a32001-08-02 04:15:00 +00003460static PyObject *
3461wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
3462{
3463 intintargfunc func = (intintargfunc)wrapped;
3464 int i, j;
3465
3466 if (!PyArg_ParseTuple(args, "ii", &i, &j))
3467 return NULL;
3468 return (*func)(self, i, j);
3469}
3470
Tim Peters6d6c1a32001-08-02 04:15:00 +00003471static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003472wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003473{
3474 intobjargproc func = (intobjargproc)wrapped;
3475 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003476 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003477
Guido van Rossum5d815f32001-08-17 21:57:47 +00003478 if (!PyArg_ParseTuple(args, "OO", &arg, &value))
3479 return NULL;
3480 i = getindex(self, arg);
3481 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00003482 return NULL;
3483 res = (*func)(self, i, value);
3484 if (res == -1 && PyErr_Occurred())
3485 return NULL;
3486 Py_INCREF(Py_None);
3487 return Py_None;
3488}
3489
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003490static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003491wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003492{
3493 intobjargproc func = (intobjargproc)wrapped;
3494 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003495 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003496
Guido van Rossum5d815f32001-08-17 21:57:47 +00003497 if (!PyArg_ParseTuple(args, "O", &arg))
3498 return NULL;
3499 i = getindex(self, arg);
3500 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003501 return NULL;
3502 res = (*func)(self, i, NULL);
3503 if (res == -1 && PyErr_Occurred())
3504 return NULL;
3505 Py_INCREF(Py_None);
3506 return Py_None;
3507}
3508
Tim Peters6d6c1a32001-08-02 04:15:00 +00003509static PyObject *
3510wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
3511{
3512 intintobjargproc func = (intintobjargproc)wrapped;
3513 int i, j, res;
3514 PyObject *value;
3515
3516 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
3517 return NULL;
3518 res = (*func)(self, i, j, value);
3519 if (res == -1 && PyErr_Occurred())
3520 return NULL;
3521 Py_INCREF(Py_None);
3522 return Py_None;
3523}
3524
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003525static PyObject *
3526wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
3527{
3528 intintobjargproc func = (intintobjargproc)wrapped;
3529 int i, j, res;
3530
3531 if (!PyArg_ParseTuple(args, "ii", &i, &j))
3532 return NULL;
3533 res = (*func)(self, i, j, NULL);
3534 if (res == -1 && PyErr_Occurred())
3535 return NULL;
3536 Py_INCREF(Py_None);
3537 return Py_None;
3538}
3539
Tim Peters6d6c1a32001-08-02 04:15:00 +00003540/* XXX objobjproc is a misnomer; should be objargpred */
3541static PyObject *
3542wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
3543{
3544 objobjproc func = (objobjproc)wrapped;
3545 int res;
3546 PyObject *value;
3547
3548 if (!PyArg_ParseTuple(args, "O", &value))
3549 return NULL;
3550 res = (*func)(self, value);
3551 if (res == -1 && PyErr_Occurred())
3552 return NULL;
3553 return PyInt_FromLong((long)res);
3554}
3555
Tim Peters6d6c1a32001-08-02 04:15:00 +00003556static PyObject *
3557wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
3558{
3559 objobjargproc func = (objobjargproc)wrapped;
3560 int res;
3561 PyObject *key, *value;
3562
3563 if (!PyArg_ParseTuple(args, "OO", &key, &value))
3564 return NULL;
3565 res = (*func)(self, key, value);
3566 if (res == -1 && PyErr_Occurred())
3567 return NULL;
3568 Py_INCREF(Py_None);
3569 return Py_None;
3570}
3571
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003572static PyObject *
3573wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
3574{
3575 objobjargproc func = (objobjargproc)wrapped;
3576 int res;
3577 PyObject *key;
3578
3579 if (!PyArg_ParseTuple(args, "O", &key))
3580 return NULL;
3581 res = (*func)(self, key, NULL);
3582 if (res == -1 && PyErr_Occurred())
3583 return NULL;
3584 Py_INCREF(Py_None);
3585 return Py_None;
3586}
3587
Tim Peters6d6c1a32001-08-02 04:15:00 +00003588static PyObject *
3589wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
3590{
3591 cmpfunc func = (cmpfunc)wrapped;
3592 int res;
3593 PyObject *other;
3594
3595 if (!PyArg_ParseTuple(args, "O", &other))
3596 return NULL;
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00003597 if (other->ob_type->tp_compare != func &&
3598 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00003599 PyErr_Format(
3600 PyExc_TypeError,
3601 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
3602 self->ob_type->tp_name,
3603 self->ob_type->tp_name,
3604 other->ob_type->tp_name);
3605 return NULL;
3606 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003607 res = (*func)(self, other);
3608 if (PyErr_Occurred())
3609 return NULL;
3610 return PyInt_FromLong((long)res);
3611}
3612
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003613/* Helper to check for object.__setattr__ or __delattr__ applied to a type.
Guido van Rossum52b27052003-04-15 20:05:10 +00003614 This is called the Carlo Verre hack after its discoverer. */
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003615static int
3616hackcheck(PyObject *self, setattrofunc func, char *what)
3617{
3618 PyTypeObject *type = self->ob_type;
3619 while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE)
3620 type = type->tp_base;
3621 if (type->tp_setattro != func) {
3622 PyErr_Format(PyExc_TypeError,
3623 "can't apply this %s to %s object",
3624 what,
3625 type->tp_name);
3626 return 0;
3627 }
3628 return 1;
3629}
3630
Tim Peters6d6c1a32001-08-02 04:15:00 +00003631static PyObject *
3632wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
3633{
3634 setattrofunc func = (setattrofunc)wrapped;
3635 int res;
3636 PyObject *name, *value;
3637
3638 if (!PyArg_ParseTuple(args, "OO", &name, &value))
3639 return NULL;
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003640 if (!hackcheck(self, func, "__setattr__"))
3641 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003642 res = (*func)(self, name, value);
3643 if (res < 0)
3644 return NULL;
3645 Py_INCREF(Py_None);
3646 return Py_None;
3647}
3648
3649static PyObject *
3650wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
3651{
3652 setattrofunc func = (setattrofunc)wrapped;
3653 int res;
3654 PyObject *name;
3655
3656 if (!PyArg_ParseTuple(args, "O", &name))
3657 return NULL;
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003658 if (!hackcheck(self, func, "__delattr__"))
3659 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003660 res = (*func)(self, name, NULL);
3661 if (res < 0)
3662 return NULL;
3663 Py_INCREF(Py_None);
3664 return Py_None;
3665}
3666
Tim Peters6d6c1a32001-08-02 04:15:00 +00003667static PyObject *
3668wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
3669{
3670 hashfunc func = (hashfunc)wrapped;
3671 long res;
3672
3673 if (!PyArg_ParseTuple(args, ""))
3674 return NULL;
3675 res = (*func)(self);
3676 if (res == -1 && PyErr_Occurred())
3677 return NULL;
3678 return PyInt_FromLong(res);
3679}
3680
Tim Peters6d6c1a32001-08-02 04:15:00 +00003681static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00003682wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003683{
3684 ternaryfunc func = (ternaryfunc)wrapped;
3685
Guido van Rossumc8e56452001-10-22 00:43:43 +00003686 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003687}
3688
Tim Peters6d6c1a32001-08-02 04:15:00 +00003689static PyObject *
3690wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
3691{
3692 richcmpfunc func = (richcmpfunc)wrapped;
3693 PyObject *other;
3694
3695 if (!PyArg_ParseTuple(args, "O", &other))
3696 return NULL;
3697 return (*func)(self, other, op);
3698}
3699
3700#undef RICHCMP_WRAPPER
3701#define RICHCMP_WRAPPER(NAME, OP) \
3702static PyObject * \
3703richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
3704{ \
3705 return wrap_richcmpfunc(self, args, wrapped, OP); \
3706}
3707
Jack Jansen8e938b42001-08-08 15:29:49 +00003708RICHCMP_WRAPPER(lt, Py_LT)
3709RICHCMP_WRAPPER(le, Py_LE)
3710RICHCMP_WRAPPER(eq, Py_EQ)
3711RICHCMP_WRAPPER(ne, Py_NE)
3712RICHCMP_WRAPPER(gt, Py_GT)
3713RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003714
Tim Peters6d6c1a32001-08-02 04:15:00 +00003715static PyObject *
3716wrap_next(PyObject *self, PyObject *args, void *wrapped)
3717{
3718 unaryfunc func = (unaryfunc)wrapped;
3719 PyObject *res;
3720
3721 if (!PyArg_ParseTuple(args, ""))
3722 return NULL;
3723 res = (*func)(self);
3724 if (res == NULL && !PyErr_Occurred())
3725 PyErr_SetNone(PyExc_StopIteration);
3726 return res;
3727}
3728
Tim Peters6d6c1a32001-08-02 04:15:00 +00003729static PyObject *
3730wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
3731{
3732 descrgetfunc func = (descrgetfunc)wrapped;
3733 PyObject *obj;
3734 PyObject *type = NULL;
3735
3736 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
3737 return NULL;
Guido van Rossum82ed25c2003-02-11 16:25:43 +00003738 if (obj == Py_None)
3739 obj = NULL;
3740 if (type == Py_None)
3741 type = NULL;
3742 if (type == NULL &&obj == NULL) {
3743 PyErr_SetString(PyExc_TypeError,
3744 "__get__(None, None) is invalid");
3745 return NULL;
3746 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003747 return (*func)(self, obj, type);
3748}
3749
Tim Peters6d6c1a32001-08-02 04:15:00 +00003750static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003751wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003752{
3753 descrsetfunc func = (descrsetfunc)wrapped;
3754 PyObject *obj, *value;
3755 int ret;
3756
3757 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
3758 return NULL;
3759 ret = (*func)(self, obj, value);
3760 if (ret < 0)
3761 return NULL;
3762 Py_INCREF(Py_None);
3763 return Py_None;
3764}
Guido van Rossum22b13872002-08-06 21:41:44 +00003765
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00003766static PyObject *
3767wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
3768{
3769 descrsetfunc func = (descrsetfunc)wrapped;
3770 PyObject *obj;
3771 int ret;
3772
3773 if (!PyArg_ParseTuple(args, "O", &obj))
3774 return NULL;
3775 ret = (*func)(self, obj, NULL);
3776 if (ret < 0)
3777 return NULL;
3778 Py_INCREF(Py_None);
3779 return Py_None;
3780}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003781
Tim Peters6d6c1a32001-08-02 04:15:00 +00003782static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00003783wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003784{
3785 initproc func = (initproc)wrapped;
3786
Guido van Rossumc8e56452001-10-22 00:43:43 +00003787 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003788 return NULL;
3789 Py_INCREF(Py_None);
3790 return Py_None;
3791}
3792
Tim Peters6d6c1a32001-08-02 04:15:00 +00003793static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003794tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003795{
Barry Warsaw60f01882001-08-22 19:24:42 +00003796 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003797 PyObject *arg0, *res;
3798
3799 if (self == NULL || !PyType_Check(self))
3800 Py_FatalError("__new__() called with non-type 'self'");
3801 type = (PyTypeObject *)self;
3802 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003803 PyErr_Format(PyExc_TypeError,
3804 "%s.__new__(): not enough arguments",
3805 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003806 return NULL;
3807 }
3808 arg0 = PyTuple_GET_ITEM(args, 0);
3809 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003810 PyErr_Format(PyExc_TypeError,
3811 "%s.__new__(X): X is not a type object (%s)",
3812 type->tp_name,
3813 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003814 return NULL;
3815 }
3816 subtype = (PyTypeObject *)arg0;
3817 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003818 PyErr_Format(PyExc_TypeError,
3819 "%s.__new__(%s): %s is not a subtype of %s",
3820 type->tp_name,
3821 subtype->tp_name,
3822 subtype->tp_name,
3823 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003824 return NULL;
3825 }
Barry Warsaw60f01882001-08-22 19:24:42 +00003826
3827 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00003828 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00003829 most derived base that's not a heap type is this type. */
3830 staticbase = subtype;
3831 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
3832 staticbase = staticbase->tp_base;
Guido van Rossuma8c60f42001-09-14 19:43:36 +00003833 if (staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003834 PyErr_Format(PyExc_TypeError,
3835 "%s.__new__(%s) is not safe, use %s.__new__()",
3836 type->tp_name,
3837 subtype->tp_name,
3838 staticbase == NULL ? "?" : staticbase->tp_name);
3839 return NULL;
3840 }
3841
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003842 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
3843 if (args == NULL)
3844 return NULL;
3845 res = type->tp_new(subtype, args, kwds);
3846 Py_DECREF(args);
3847 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003848}
3849
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003850static struct PyMethodDef tp_new_methoddef[] = {
3851 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00003852 PyDoc_STR("T.__new__(S, ...) -> "
3853 "a new object with type S, a subtype of T")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00003854 {0}
3855};
3856
3857static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003858add_tp_new_wrapper(PyTypeObject *type)
3859{
Guido van Rossumf040ede2001-08-07 16:40:56 +00003860 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003861
Guido van Rossum687ae002001-10-15 22:03:32 +00003862 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00003863 return 0;
3864 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003865 if (func == NULL)
3866 return -1;
Guido van Rossum687ae002001-10-15 22:03:32 +00003867 return PyDict_SetItemString(type->tp_dict, "__new__", func);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003868}
3869
Guido van Rossumf040ede2001-08-07 16:40:56 +00003870/* Slot wrappers that call the corresponding __foo__ slot. See comments
3871 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003872
Guido van Rossumdc91b992001-08-08 22:26:22 +00003873#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003874static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003875FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003876{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00003877 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003878 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003879}
3880
Guido van Rossumdc91b992001-08-08 22:26:22 +00003881#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003882static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003883FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003884{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003885 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003886 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003887}
3888
Guido van Rossumcd118802003-01-06 22:57:47 +00003889/* Boolean helper for SLOT1BINFULL().
3890 right.__class__ is a nontrivial subclass of left.__class__. */
3891static int
3892method_is_overloaded(PyObject *left, PyObject *right, char *name)
3893{
3894 PyObject *a, *b;
3895 int ok;
3896
3897 b = PyObject_GetAttrString((PyObject *)(right->ob_type), name);
3898 if (b == NULL) {
3899 PyErr_Clear();
3900 /* If right doesn't have it, it's not overloaded */
3901 return 0;
3902 }
3903
3904 a = PyObject_GetAttrString((PyObject *)(left->ob_type), name);
3905 if (a == NULL) {
3906 PyErr_Clear();
3907 Py_DECREF(b);
3908 /* If right has it but left doesn't, it's overloaded */
3909 return 1;
3910 }
3911
3912 ok = PyObject_RichCompareBool(a, b, Py_NE);
3913 Py_DECREF(a);
3914 Py_DECREF(b);
3915 if (ok < 0) {
3916 PyErr_Clear();
3917 return 0;
3918 }
3919
3920 return ok;
3921}
3922
Guido van Rossumdc91b992001-08-08 22:26:22 +00003923
3924#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003925static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003926FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003927{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003928 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00003929 int do_other = self->ob_type != other->ob_type && \
3930 other->ob_type->tp_as_number != NULL && \
3931 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003932 if (self->ob_type->tp_as_number != NULL && \
3933 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
3934 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00003935 if (do_other && \
Guido van Rossumcd118802003-01-06 22:57:47 +00003936 PyType_IsSubtype(other->ob_type, self->ob_type) && \
3937 method_is_overloaded(self, other, ROPSTR)) { \
Guido van Rossum55f20992001-10-01 17:18:22 +00003938 r = call_maybe( \
3939 other, ROPSTR, &rcache_str, "(O)", self); \
3940 if (r != Py_NotImplemented) \
3941 return r; \
3942 Py_DECREF(r); \
3943 do_other = 0; \
3944 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00003945 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00003946 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003947 if (r != Py_NotImplemented || \
3948 other->ob_type == self->ob_type) \
3949 return r; \
3950 Py_DECREF(r); \
3951 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00003952 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00003953 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00003954 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003955 } \
3956 Py_INCREF(Py_NotImplemented); \
3957 return Py_NotImplemented; \
3958}
3959
3960#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
3961 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
3962
3963#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
3964static PyObject * \
3965FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
3966{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003967 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003968 return call_method(self, OPSTR, &cache_str, \
3969 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003970}
3971
3972static int
3973slot_sq_length(PyObject *self)
3974{
Guido van Rossum2730b132001-08-28 18:22:14 +00003975 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00003976 PyObject *res = call_method(self, "__len__", &len_str, "()");
Guido van Rossum26111622001-10-01 16:42:49 +00003977 int len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003978
3979 if (res == NULL)
3980 return -1;
Guido van Rossum26111622001-10-01 16:42:49 +00003981 len = (int)PyInt_AsLong(res);
3982 Py_DECREF(res);
Jeremy Hylton73a088e2002-07-25 16:43:29 +00003983 if (len == -1 && PyErr_Occurred())
3984 return -1;
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00003985 if (len < 0) {
Guido van Rossum22b13872002-08-06 21:41:44 +00003986 PyErr_SetString(PyExc_ValueError,
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00003987 "__len__() should return >= 0");
3988 return -1;
3989 }
Guido van Rossum26111622001-10-01 16:42:49 +00003990 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003991}
3992
Guido van Rossumdc91b992001-08-08 22:26:22 +00003993SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
3994SLOT1(slot_sq_repeat, "__mul__", int, "i")
Guido van Rossumf4593e02001-10-03 12:09:30 +00003995
3996/* Super-optimized version of slot_sq_item.
3997 Other slots could do the same... */
3998static PyObject *
3999slot_sq_item(PyObject *self, int i)
4000{
4001 static PyObject *getitem_str;
4002 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
4003 descrgetfunc f;
4004
4005 if (getitem_str == NULL) {
4006 getitem_str = PyString_InternFromString("__getitem__");
4007 if (getitem_str == NULL)
4008 return NULL;
4009 }
4010 func = _PyType_Lookup(self->ob_type, getitem_str);
4011 if (func != NULL) {
Guido van Rossumf4593e02001-10-03 12:09:30 +00004012 if ((f = func->ob_type->tp_descr_get) == NULL)
4013 Py_INCREF(func);
Neal Norwitz673cd822002-10-18 16:33:13 +00004014 else {
Guido van Rossumf4593e02001-10-03 12:09:30 +00004015 func = f(func, self, (PyObject *)(self->ob_type));
Neal Norwitz673cd822002-10-18 16:33:13 +00004016 if (func == NULL) {
4017 return NULL;
4018 }
4019 }
Guido van Rossumf4593e02001-10-03 12:09:30 +00004020 ival = PyInt_FromLong(i);
4021 if (ival != NULL) {
4022 args = PyTuple_New(1);
4023 if (args != NULL) {
4024 PyTuple_SET_ITEM(args, 0, ival);
4025 retval = PyObject_Call(func, args, NULL);
4026 Py_XDECREF(args);
4027 Py_XDECREF(func);
4028 return retval;
4029 }
4030 }
4031 }
4032 else {
4033 PyErr_SetObject(PyExc_AttributeError, getitem_str);
4034 }
4035 Py_XDECREF(args);
4036 Py_XDECREF(ival);
4037 Py_XDECREF(func);
4038 return NULL;
4039}
4040
Guido van Rossumdc91b992001-08-08 22:26:22 +00004041SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004042
4043static int
4044slot_sq_ass_item(PyObject *self, int index, PyObject *value)
4045{
4046 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004047 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004048
4049 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004050 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004051 "(i)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004052 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004053 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004054 "(iO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004055 if (res == NULL)
4056 return -1;
4057 Py_DECREF(res);
4058 return 0;
4059}
4060
4061static int
4062slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
4063{
4064 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004065 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004066
4067 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004068 res = call_method(self, "__delslice__", &delslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004069 "(ii)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004070 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004071 res = call_method(self, "__setslice__", &setslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004072 "(iiO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004073 if (res == NULL)
4074 return -1;
4075 Py_DECREF(res);
4076 return 0;
4077}
4078
4079static int
4080slot_sq_contains(PyObject *self, PyObject *value)
4081{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004082 PyObject *func, *res, *args;
Tim Petersbf9b2442003-03-23 05:35:36 +00004083 int result = -1;
4084
Guido van Rossum60718732001-08-28 17:47:51 +00004085 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004086
Guido van Rossum55f20992001-10-01 17:18:22 +00004087 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004088 if (func != NULL) {
4089 args = Py_BuildValue("(O)", value);
4090 if (args == NULL)
4091 res = NULL;
4092 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004093 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004094 Py_DECREF(args);
4095 }
4096 Py_DECREF(func);
Tim Petersbf9b2442003-03-23 05:35:36 +00004097 if (res != NULL) {
4098 result = PyObject_IsTrue(res);
4099 Py_DECREF(res);
4100 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004101 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004102 else if (! PyErr_Occurred()) {
4103 result = _PySequence_IterSearch(self, value,
4104 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004105 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004106 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004107}
4108
Guido van Rossumdc91b992001-08-08 22:26:22 +00004109SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
4110SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004111
4112#define slot_mp_length slot_sq_length
4113
Guido van Rossumdc91b992001-08-08 22:26:22 +00004114SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004115
4116static int
4117slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
4118{
4119 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004120 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004121
4122 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004123 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004124 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004125 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004126 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004127 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004128 if (res == NULL)
4129 return -1;
4130 Py_DECREF(res);
4131 return 0;
4132}
4133
Guido van Rossumdc91b992001-08-08 22:26:22 +00004134SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
4135SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
4136SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
4137SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
4138SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
4139SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
4140
Jeremy Hylton938ace62002-07-17 16:30:39 +00004141static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00004142
4143SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
4144 nb_power, "__pow__", "__rpow__")
4145
4146static PyObject *
4147slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
4148{
Guido van Rossum2730b132001-08-28 18:22:14 +00004149 static PyObject *pow_str;
4150
Guido van Rossumdc91b992001-08-08 22:26:22 +00004151 if (modulus == Py_None)
4152 return slot_nb_power_binary(self, other);
Guido van Rossum23094982002-06-10 14:30:43 +00004153 /* Three-arg power doesn't use __rpow__. But ternary_op
4154 can call this when the second argument's type uses
4155 slot_nb_power, so check before calling self.__pow__. */
4156 if (self->ob_type->tp_as_number != NULL &&
4157 self->ob_type->tp_as_number->nb_power == slot_nb_power) {
4158 return call_method(self, "__pow__", &pow_str,
4159 "(OO)", other, modulus);
4160 }
4161 Py_INCREF(Py_NotImplemented);
4162 return Py_NotImplemented;
Guido van Rossumdc91b992001-08-08 22:26:22 +00004163}
4164
4165SLOT0(slot_nb_negative, "__neg__")
4166SLOT0(slot_nb_positive, "__pos__")
4167SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004168
4169static int
4170slot_nb_nonzero(PyObject *self)
4171{
Tim Petersea7f75d2002-12-07 21:39:16 +00004172 PyObject *func, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00004173 static PyObject *nonzero_str, *len_str;
Tim Petersea7f75d2002-12-07 21:39:16 +00004174 int result = -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004175
Guido van Rossum55f20992001-10-01 17:18:22 +00004176 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004177 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00004178 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00004179 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00004180 func = lookup_maybe(self, "__len__", &len_str);
Tim Petersea7f75d2002-12-07 21:39:16 +00004181 if (func == NULL)
4182 return PyErr_Occurred() ? -1 : 1;
4183 }
4184 args = PyTuple_New(0);
4185 if (args != NULL) {
4186 PyObject *temp = PyObject_Call(func, args, NULL);
4187 Py_DECREF(args);
4188 if (temp != NULL) {
4189 result = PyObject_IsTrue(temp);
4190 Py_DECREF(temp);
Guido van Rossum55f20992001-10-01 17:18:22 +00004191 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004192 }
Guido van Rossum55f20992001-10-01 17:18:22 +00004193 Py_DECREF(func);
Tim Petersea7f75d2002-12-07 21:39:16 +00004194 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004195}
4196
Guido van Rossumdc91b992001-08-08 22:26:22 +00004197SLOT0(slot_nb_invert, "__invert__")
4198SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
4199SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
4200SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
4201SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
4202SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004203
4204static int
4205slot_nb_coerce(PyObject **a, PyObject **b)
4206{
4207 static PyObject *coerce_str;
4208 PyObject *self = *a, *other = *b;
4209
4210 if (self->ob_type->tp_as_number != NULL &&
4211 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
4212 PyObject *r;
4213 r = call_maybe(
4214 self, "__coerce__", &coerce_str, "(O)", other);
4215 if (r == NULL)
4216 return -1;
4217 if (r == Py_NotImplemented) {
4218 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004219 }
Guido van Rossum55f20992001-10-01 17:18:22 +00004220 else {
4221 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
4222 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004223 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00004224 Py_DECREF(r);
4225 return -1;
4226 }
4227 *a = PyTuple_GET_ITEM(r, 0);
4228 Py_INCREF(*a);
4229 *b = PyTuple_GET_ITEM(r, 1);
4230 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004231 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00004232 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004233 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004234 }
4235 if (other->ob_type->tp_as_number != NULL &&
4236 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
4237 PyObject *r;
4238 r = call_maybe(
4239 other, "__coerce__", &coerce_str, "(O)", self);
4240 if (r == NULL)
4241 return -1;
4242 if (r == Py_NotImplemented) {
4243 Py_DECREF(r);
4244 return 1;
4245 }
4246 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
4247 PyErr_SetString(PyExc_TypeError,
4248 "__coerce__ didn't return a 2-tuple");
4249 Py_DECREF(r);
4250 return -1;
4251 }
4252 *a = PyTuple_GET_ITEM(r, 1);
4253 Py_INCREF(*a);
4254 *b = PyTuple_GET_ITEM(r, 0);
4255 Py_INCREF(*b);
4256 Py_DECREF(r);
4257 return 0;
4258 }
4259 return 1;
4260}
4261
Guido van Rossumdc91b992001-08-08 22:26:22 +00004262SLOT0(slot_nb_int, "__int__")
4263SLOT0(slot_nb_long, "__long__")
4264SLOT0(slot_nb_float, "__float__")
4265SLOT0(slot_nb_oct, "__oct__")
4266SLOT0(slot_nb_hex, "__hex__")
4267SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
4268SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
4269SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
4270SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
4271SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Guido van Rossum6e5680f2002-10-15 01:01:53 +00004272SLOT1(slot_nb_inplace_power, "__ipow__", PyObject *, "O")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004273SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
4274SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
4275SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
4276SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
4277SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
4278SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
4279 "__floordiv__", "__rfloordiv__")
4280SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
4281SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
4282SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004283
4284static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00004285half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004286{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004287 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004288 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004289 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004290
Guido van Rossum60718732001-08-28 17:47:51 +00004291 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004292 if (func == NULL) {
4293 PyErr_Clear();
4294 }
4295 else {
4296 args = Py_BuildValue("(O)", other);
4297 if (args == NULL)
4298 res = NULL;
4299 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004300 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004301 Py_DECREF(args);
4302 }
Raymond Hettingerab5dae32002-06-24 13:08:16 +00004303 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004304 if (res != Py_NotImplemented) {
4305 if (res == NULL)
4306 return -2;
4307 c = PyInt_AsLong(res);
4308 Py_DECREF(res);
4309 if (c == -1 && PyErr_Occurred())
4310 return -2;
4311 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
4312 }
4313 Py_DECREF(res);
4314 }
4315 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004316}
4317
Guido van Rossumab3b0342001-09-18 20:38:53 +00004318/* This slot is published for the benefit of try_3way_compare in object.c */
4319int
4320_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00004321{
4322 int c;
4323
Guido van Rossumab3b0342001-09-18 20:38:53 +00004324 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004325 c = half_compare(self, other);
4326 if (c <= 1)
4327 return c;
4328 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00004329 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004330 c = half_compare(other, self);
4331 if (c < -1)
4332 return -2;
4333 if (c <= 1)
4334 return -c;
4335 }
4336 return (void *)self < (void *)other ? -1 :
4337 (void *)self > (void *)other ? 1 : 0;
4338}
4339
4340static PyObject *
4341slot_tp_repr(PyObject *self)
4342{
4343 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004344 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004345
Guido van Rossum60718732001-08-28 17:47:51 +00004346 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004347 if (func != NULL) {
4348 res = PyEval_CallObject(func, NULL);
4349 Py_DECREF(func);
4350 return res;
4351 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00004352 PyErr_Clear();
4353 return PyString_FromFormat("<%s object at %p>",
4354 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004355}
4356
4357static PyObject *
4358slot_tp_str(PyObject *self)
4359{
4360 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004361 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004362
Guido van Rossum60718732001-08-28 17:47:51 +00004363 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004364 if (func != NULL) {
4365 res = PyEval_CallObject(func, NULL);
4366 Py_DECREF(func);
4367 return res;
4368 }
4369 else {
4370 PyErr_Clear();
4371 return slot_tp_repr(self);
4372 }
4373}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004374
4375static long
4376slot_tp_hash(PyObject *self)
4377{
Tim Peters61ce0a92002-12-06 23:38:02 +00004378 PyObject *func;
Guido van Rossum60718732001-08-28 17:47:51 +00004379 static PyObject *hash_str, *eq_str, *cmp_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004380 long h;
4381
Guido van Rossum60718732001-08-28 17:47:51 +00004382 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004383
4384 if (func != NULL) {
Tim Peters61ce0a92002-12-06 23:38:02 +00004385 PyObject *res = PyEval_CallObject(func, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004386 Py_DECREF(func);
4387 if (res == NULL)
4388 return -1;
4389 h = PyInt_AsLong(res);
Tim Peters61ce0a92002-12-06 23:38:02 +00004390 Py_DECREF(res);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004391 }
4392 else {
4393 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004394 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004395 if (func == NULL) {
4396 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004397 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004398 }
4399 if (func != NULL) {
4400 Py_DECREF(func);
4401 PyErr_SetString(PyExc_TypeError, "unhashable type");
4402 return -1;
4403 }
4404 PyErr_Clear();
4405 h = _Py_HashPointer((void *)self);
4406 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004407 if (h == -1 && !PyErr_Occurred())
4408 h = -2;
4409 return h;
4410}
4411
4412static PyObject *
4413slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
4414{
Guido van Rossum60718732001-08-28 17:47:51 +00004415 static PyObject *call_str;
4416 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004417 PyObject *res;
4418
4419 if (meth == NULL)
4420 return NULL;
4421 res = PyObject_Call(meth, args, kwds);
4422 Py_DECREF(meth);
4423 return res;
4424}
4425
Guido van Rossum14a6f832001-10-17 13:59:09 +00004426/* There are two slot dispatch functions for tp_getattro.
4427
4428 - slot_tp_getattro() is used when __getattribute__ is overridden
4429 but no __getattr__ hook is present;
4430
4431 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
4432
Guido van Rossumc334df52002-04-04 23:44:47 +00004433 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
4434 detects the absence of __getattr__ and then installs the simpler slot if
4435 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00004436
Tim Peters6d6c1a32001-08-02 04:15:00 +00004437static PyObject *
4438slot_tp_getattro(PyObject *self, PyObject *name)
4439{
Guido van Rossum14a6f832001-10-17 13:59:09 +00004440 static PyObject *getattribute_str = NULL;
4441 return call_method(self, "__getattribute__", &getattribute_str,
4442 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004443}
4444
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004445static PyObject *
4446slot_tp_getattr_hook(PyObject *self, PyObject *name)
4447{
4448 PyTypeObject *tp = self->ob_type;
4449 PyObject *getattr, *getattribute, *res;
4450 static PyObject *getattribute_str = NULL;
4451 static PyObject *getattr_str = NULL;
4452
4453 if (getattr_str == NULL) {
4454 getattr_str = PyString_InternFromString("__getattr__");
4455 if (getattr_str == NULL)
4456 return NULL;
4457 }
4458 if (getattribute_str == NULL) {
4459 getattribute_str =
4460 PyString_InternFromString("__getattribute__");
4461 if (getattribute_str == NULL)
4462 return NULL;
4463 }
4464 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004465 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004466 /* No __getattr__ hook: use a simpler dispatcher */
4467 tp->tp_getattro = slot_tp_getattro;
4468 return slot_tp_getattro(self, name);
4469 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004470 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004471 if (getattribute == NULL ||
4472 (getattribute->ob_type == &PyWrapperDescr_Type &&
4473 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
4474 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004475 res = PyObject_GenericGetAttr(self, name);
4476 else
4477 res = PyObject_CallFunction(getattribute, "OO", self, name);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004478 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004479 PyErr_Clear();
4480 res = PyObject_CallFunction(getattr, "OO", self, name);
4481 }
4482 return res;
4483}
4484
Tim Peters6d6c1a32001-08-02 04:15:00 +00004485static int
4486slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
4487{
4488 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004489 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004490
4491 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004492 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004493 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004494 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004495 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004496 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004497 if (res == NULL)
4498 return -1;
4499 Py_DECREF(res);
4500 return 0;
4501}
4502
4503/* Map rich comparison operators to their __xx__ namesakes */
4504static char *name_op[] = {
4505 "__lt__",
4506 "__le__",
4507 "__eq__",
4508 "__ne__",
4509 "__gt__",
4510 "__ge__",
4511};
4512
4513static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00004514half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004515{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004516 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004517 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00004518
Guido van Rossum60718732001-08-28 17:47:51 +00004519 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004520 if (func == NULL) {
4521 PyErr_Clear();
4522 Py_INCREF(Py_NotImplemented);
4523 return Py_NotImplemented;
4524 }
4525 args = Py_BuildValue("(O)", other);
4526 if (args == NULL)
4527 res = NULL;
4528 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004529 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004530 Py_DECREF(args);
4531 }
4532 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004533 return res;
4534}
4535
Guido van Rossumb8f63662001-08-15 23:57:02 +00004536/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
4537static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
4538
4539static PyObject *
4540slot_tp_richcompare(PyObject *self, PyObject *other, int op)
4541{
4542 PyObject *res;
4543
4544 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
4545 res = half_richcompare(self, other, op);
4546 if (res != Py_NotImplemented)
4547 return res;
4548 Py_DECREF(res);
4549 }
4550 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
4551 res = half_richcompare(other, self, swapped_op[op]);
4552 if (res != Py_NotImplemented) {
4553 return res;
4554 }
4555 Py_DECREF(res);
4556 }
4557 Py_INCREF(Py_NotImplemented);
4558 return Py_NotImplemented;
4559}
4560
4561static PyObject *
4562slot_tp_iter(PyObject *self)
4563{
4564 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004565 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004566
Guido van Rossum60718732001-08-28 17:47:51 +00004567 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004568 if (func != NULL) {
Guido van Rossum84b2bed2002-08-16 17:01:09 +00004569 PyObject *args;
4570 args = res = PyTuple_New(0);
4571 if (args != NULL) {
4572 res = PyObject_Call(func, args, NULL);
4573 Py_DECREF(args);
4574 }
4575 Py_DECREF(func);
4576 return res;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004577 }
4578 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004579 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004580 if (func == NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00004581 PyErr_SetString(PyExc_TypeError,
4582 "iteration over non-sequence");
Guido van Rossumb8f63662001-08-15 23:57:02 +00004583 return NULL;
4584 }
4585 Py_DECREF(func);
4586 return PySeqIter_New(self);
4587}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004588
4589static PyObject *
4590slot_tp_iternext(PyObject *self)
4591{
Guido van Rossum2730b132001-08-28 18:22:14 +00004592 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00004593 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004594}
4595
Guido van Rossum1a493502001-08-17 16:47:50 +00004596static PyObject *
4597slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4598{
4599 PyTypeObject *tp = self->ob_type;
4600 PyObject *get;
4601 static PyObject *get_str = NULL;
4602
4603 if (get_str == NULL) {
4604 get_str = PyString_InternFromString("__get__");
4605 if (get_str == NULL)
4606 return NULL;
4607 }
4608 get = _PyType_Lookup(tp, get_str);
4609 if (get == NULL) {
4610 /* Avoid further slowdowns */
4611 if (tp->tp_descr_get == slot_tp_descr_get)
4612 tp->tp_descr_get = NULL;
4613 Py_INCREF(self);
4614 return self;
4615 }
Guido van Rossum2c252392001-08-24 10:13:31 +00004616 if (obj == NULL)
4617 obj = Py_None;
4618 if (type == NULL)
4619 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00004620 return PyObject_CallFunction(get, "OOO", self, obj, type);
4621}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004622
4623static int
4624slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
4625{
Guido van Rossum2c252392001-08-24 10:13:31 +00004626 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004627 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00004628
4629 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00004630 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004631 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00004632 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004633 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004634 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004635 if (res == NULL)
4636 return -1;
4637 Py_DECREF(res);
4638 return 0;
4639}
4640
4641static int
4642slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
4643{
Guido van Rossum60718732001-08-28 17:47:51 +00004644 static PyObject *init_str;
4645 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004646 PyObject *res;
4647
4648 if (meth == NULL)
4649 return -1;
4650 res = PyObject_Call(meth, args, kwds);
4651 Py_DECREF(meth);
4652 if (res == NULL)
4653 return -1;
4654 Py_DECREF(res);
4655 return 0;
4656}
4657
4658static PyObject *
4659slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4660{
Guido van Rossum7bed2132002-08-08 21:57:53 +00004661 static PyObject *new_str;
4662 PyObject *func;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004663 PyObject *newargs, *x;
4664 int i, n;
4665
Guido van Rossum7bed2132002-08-08 21:57:53 +00004666 if (new_str == NULL) {
4667 new_str = PyString_InternFromString("__new__");
4668 if (new_str == NULL)
4669 return NULL;
4670 }
4671 func = PyObject_GetAttr((PyObject *)type, new_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004672 if (func == NULL)
4673 return NULL;
4674 assert(PyTuple_Check(args));
4675 n = PyTuple_GET_SIZE(args);
4676 newargs = PyTuple_New(n+1);
4677 if (newargs == NULL)
4678 return NULL;
4679 Py_INCREF(type);
4680 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
4681 for (i = 0; i < n; i++) {
4682 x = PyTuple_GET_ITEM(args, i);
4683 Py_INCREF(x);
4684 PyTuple_SET_ITEM(newargs, i+1, x);
4685 }
4686 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00004687 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004688 Py_DECREF(func);
4689 return x;
4690}
4691
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004692static void
4693slot_tp_del(PyObject *self)
4694{
4695 static PyObject *del_str = NULL;
4696 PyObject *del, *res;
4697 PyObject *error_type, *error_value, *error_traceback;
4698
4699 /* Temporarily resurrect the object. */
4700 assert(self->ob_refcnt == 0);
4701 self->ob_refcnt = 1;
4702
4703 /* Save the current exception, if any. */
4704 PyErr_Fetch(&error_type, &error_value, &error_traceback);
4705
4706 /* Execute __del__ method, if any. */
4707 del = lookup_maybe(self, "__del__", &del_str);
4708 if (del != NULL) {
4709 res = PyEval_CallObject(del, NULL);
4710 if (res == NULL)
4711 PyErr_WriteUnraisable(del);
4712 else
4713 Py_DECREF(res);
4714 Py_DECREF(del);
4715 }
4716
4717 /* Restore the saved exception. */
4718 PyErr_Restore(error_type, error_value, error_traceback);
4719
4720 /* Undo the temporary resurrection; can't use DECREF here, it would
4721 * cause a recursive call.
4722 */
4723 assert(self->ob_refcnt > 0);
4724 if (--self->ob_refcnt == 0)
4725 return; /* this is the normal path out */
4726
4727 /* __del__ resurrected it! Make it look like the original Py_DECREF
4728 * never happened.
4729 */
4730 {
4731 int refcnt = self->ob_refcnt;
4732 _Py_NewReference(self);
4733 self->ob_refcnt = refcnt;
4734 }
4735 assert(!PyType_IS_GC(self->ob_type) ||
4736 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
4737 /* If Py_REF_DEBUG, the original decref dropped _Py_RefTotal, but
4738 * _Py_NewReference bumped it again, so that's a wash.
4739 * If Py_TRACE_REFS, _Py_NewReference re-added self to the object
4740 * chain, so no more to do there either.
4741 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
4742 * _Py_NewReference bumped tp_allocs: both of those need to be
4743 * undone.
4744 */
4745#ifdef COUNT_ALLOCS
4746 --self->ob_type->tp_frees;
4747 --self->ob_type->tp_allocs;
4748#endif
4749}
4750
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004751
4752/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
Tim Petersbf9b2442003-03-23 05:35:36 +00004753 functions. The offsets here are relative to the 'PyHeapTypeObject'
Guido van Rossume5c691a2003-03-07 15:13:17 +00004754 structure, which incorporates the additional structures used for numbers,
4755 sequences and mappings.
4756 Note that multiple names may map to the same slot (e.g. __eq__,
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004757 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00004758 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
4759 terminated with an all-zero entry. (This table is further initialized and
4760 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004761
Guido van Rossum6d204072001-10-21 00:44:31 +00004762typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004763
4764#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00004765#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004766#undef ETSLOT
4767#undef SQSLOT
4768#undef MPSLOT
4769#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00004770#undef UNSLOT
4771#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004772#undef BINSLOT
4773#undef RBINSLOT
4774
Guido van Rossum6d204072001-10-21 00:44:31 +00004775#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004776 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
4777 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00004778#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
4779 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004780 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00004781#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Guido van Rossume5c691a2003-03-07 15:13:17 +00004782 {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004783 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00004784#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4785 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
4786#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4787 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
4788#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4789 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
4790#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4791 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
4792 "x." NAME "() <==> " DOC)
4793#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4794 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
4795 "x." NAME "(y) <==> x" DOC "y")
4796#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
4797 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
4798 "x." NAME "(y) <==> x" DOC "y")
4799#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
4800 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
4801 "x." NAME "(y) <==> y" DOC "x")
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004802
4803static slotdef slotdefs[] = {
Guido van Rossum6d204072001-10-21 00:44:31 +00004804 SQSLOT("__len__", sq_length, slot_sq_length, wrap_inquiry,
4805 "x.__len__() <==> len(x)"),
4806 SQSLOT("__add__", sq_concat, slot_sq_concat, wrap_binaryfunc,
4807 "x.__add__(y) <==> x+y"),
4808 SQSLOT("__mul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
4809 "x.__mul__(n) <==> x*n"),
4810 SQSLOT("__rmul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
4811 "x.__rmul__(n) <==> n*x"),
4812 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
4813 "x.__getitem__(y) <==> x[y]"),
4814 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_intintargfunc,
Brett Cannon154da9b2003-05-20 02:30:04 +00004815 "x.__getslice__(i, j) <==> x[i:j]\n\
4816 \n\
4817 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00004818 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
Brett Cannonbe67d872003-05-20 02:40:12 +00004819 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum6d204072001-10-21 00:44:31 +00004820 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
Brett Cannonbe67d872003-05-20 02:40:12 +00004821 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004822 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Guido van Rossum6d204072001-10-21 00:44:31 +00004823 wrap_intintobjargproc,
Brett Cannonbe67d872003-05-20 02:40:12 +00004824 "x.__setslice__(i, j, y) <==> x[i:j]=y\n\
4825 \n\
4826 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00004827 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
Brett Cannonbe67d872003-05-20 02:40:12 +00004828 "x.__delslice__(i, j) <==> del x[i:j]\n\
4829 \n\
4830 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00004831 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
4832 "x.__contains__(y) <==> y in x"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004833 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat,
Guido van Rossum6d204072001-10-21 00:44:31 +00004834 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004835 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat,
Guido van Rossum6d204072001-10-21 00:44:31 +00004836 wrap_intargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004837
Guido van Rossum6d204072001-10-21 00:44:31 +00004838 MPSLOT("__len__", mp_length, slot_mp_length, wrap_inquiry,
4839 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00004840 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004841 wrap_binaryfunc,
4842 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004843 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004844 wrap_objobjargproc,
4845 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004846 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004847 wrap_delitem,
4848 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004849
Guido van Rossum6d204072001-10-21 00:44:31 +00004850 BINSLOT("__add__", nb_add, slot_nb_add,
4851 "+"),
4852 RBINSLOT("__radd__", nb_add, slot_nb_add,
4853 "+"),
4854 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
4855 "-"),
4856 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
4857 "-"),
4858 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
4859 "*"),
4860 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
4861 "*"),
4862 BINSLOT("__div__", nb_divide, slot_nb_divide,
4863 "/"),
4864 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
4865 "/"),
4866 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
4867 "%"),
4868 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
4869 "%"),
4870 BINSLOT("__divmod__", nb_divmod, slot_nb_divmod,
4871 "divmod(x, y)"),
4872 RBINSLOT("__rdivmod__", nb_divmod, slot_nb_divmod,
4873 "divmod(y, x)"),
4874 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
4875 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
4876 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
4877 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
4878 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
4879 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
4880 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
4881 "abs(x)"),
Guido van Rossumdfce3bf2002-03-10 14:11:16 +00004882 UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquiry,
Guido van Rossum6d204072001-10-21 00:44:31 +00004883 "x != 0"),
4884 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
4885 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
4886 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
4887 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
4888 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
4889 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
4890 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
4891 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
4892 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
4893 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
4894 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
4895 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
4896 "x.__coerce__(y) <==> coerce(x, y)"),
4897 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
4898 "int(x)"),
4899 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
4900 "long(x)"),
4901 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
4902 "float(x)"),
4903 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
4904 "oct(x)"),
4905 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
4906 "hex(x)"),
4907 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
4908 wrap_binaryfunc, "+"),
4909 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
4910 wrap_binaryfunc, "-"),
4911 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
4912 wrap_binaryfunc, "*"),
4913 IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
4914 wrap_binaryfunc, "/"),
4915 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
4916 wrap_binaryfunc, "%"),
4917 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
Guido van Rossum6e5680f2002-10-15 01:01:53 +00004918 wrap_binaryfunc, "**"),
Guido van Rossum6d204072001-10-21 00:44:31 +00004919 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
4920 wrap_binaryfunc, "<<"),
4921 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
4922 wrap_binaryfunc, ">>"),
4923 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
4924 wrap_binaryfunc, "&"),
4925 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
4926 wrap_binaryfunc, "^"),
4927 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
4928 wrap_binaryfunc, "|"),
4929 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
4930 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
4931 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
4932 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
4933 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
4934 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
4935 IBSLOT("__itruediv__", nb_inplace_true_divide,
4936 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004937
Guido van Rossum6d204072001-10-21 00:44:31 +00004938 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
4939 "x.__str__() <==> str(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00004940 TPSLOT("__str__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00004941 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
4942 "x.__repr__() <==> repr(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00004943 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00004944 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
4945 "x.__cmp__(y) <==> cmp(x,y)"),
4946 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
4947 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00004948 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
4949 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004950 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00004951 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
4952 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
4953 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
4954 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
4955 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
4956 "x.__setattr__('name', value) <==> x.name = value"),
4957 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
4958 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
4959 "x.__delattr__('name') <==> del x.name"),
4960 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
4961 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
4962 "x.__lt__(y) <==> x<y"),
4963 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
4964 "x.__le__(y) <==> x<=y"),
4965 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
4966 "x.__eq__(y) <==> x==y"),
4967 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
4968 "x.__ne__(y) <==> x!=y"),
4969 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
4970 "x.__gt__(y) <==> x>y"),
4971 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
4972 "x.__ge__(y) <==> x>=y"),
4973 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
4974 "x.__iter__() <==> iter(x)"),
4975 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
4976 "x.next() -> the next value, or raise StopIteration"),
4977 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
4978 "descr.__get__(obj[, type]) -> value"),
4979 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
4980 "descr.__set__(obj, value)"),
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004981 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
4982 wrap_descr_delete, "descr.__delete__(obj)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00004983 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00004984 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00004985 "see x.__class__.__doc__ for signature",
4986 PyWrapperFlag_KEYWORDS),
4987 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004988 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004989 {NULL}
4990};
4991
Guido van Rossumc334df52002-04-04 23:44:47 +00004992/* Given a type pointer and an offset gotten from a slotdef entry, return a
4993 pointer to the actual slot. This is not quite the same as simply adding
4994 the offset to the type pointer, since it takes care to indirect through the
4995 proper indirection pointer (as_buffer, etc.); it returns NULL if the
4996 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004997static void **
4998slotptr(PyTypeObject *type, int offset)
4999{
5000 char *ptr;
5001
Guido van Rossume5c691a2003-03-07 15:13:17 +00005002 /* Note: this depends on the order of the members of PyHeapTypeObject! */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005003 assert(offset >= 0);
Guido van Rossume5c691a2003-03-07 15:13:17 +00005004 assert(offset < offsetof(PyHeapTypeObject, as_buffer));
5005 if (offset >= offsetof(PyHeapTypeObject, as_sequence)) {
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005006 ptr = (void *)type->tp_as_sequence;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005007 offset -= offsetof(PyHeapTypeObject, as_sequence);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005008 }
Guido van Rossume5c691a2003-03-07 15:13:17 +00005009 else if (offset >= offsetof(PyHeapTypeObject, as_mapping)) {
Guido van Rossum09638c12002-06-13 19:17:46 +00005010 ptr = (void *)type->tp_as_mapping;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005011 offset -= offsetof(PyHeapTypeObject, as_mapping);
Guido van Rossum09638c12002-06-13 19:17:46 +00005012 }
Guido van Rossume5c691a2003-03-07 15:13:17 +00005013 else if (offset >= offsetof(PyHeapTypeObject, as_number)) {
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005014 ptr = (void *)type->tp_as_number;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005015 offset -= offsetof(PyHeapTypeObject, as_number);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005016 }
5017 else {
5018 ptr = (void *)type;
5019 }
5020 if (ptr != NULL)
5021 ptr += offset;
5022 return (void **)ptr;
5023}
Guido van Rossumf040ede2001-08-07 16:40:56 +00005024
Guido van Rossumc334df52002-04-04 23:44:47 +00005025/* Length of array of slotdef pointers used to store slots with the
5026 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
5027 the same __name__, for any __name__. Since that's a static property, it is
5028 appropriate to declare fixed-size arrays for this. */
5029#define MAX_EQUIV 10
5030
5031/* Return a slot pointer for a given name, but ONLY if the attribute has
5032 exactly one slot function. The name must be an interned string. */
5033static void **
5034resolve_slotdups(PyTypeObject *type, PyObject *name)
5035{
5036 /* XXX Maybe this could be optimized more -- but is it worth it? */
5037
5038 /* pname and ptrs act as a little cache */
5039 static PyObject *pname;
5040 static slotdef *ptrs[MAX_EQUIV];
5041 slotdef *p, **pp;
5042 void **res, **ptr;
5043
5044 if (pname != name) {
5045 /* Collect all slotdefs that match name into ptrs. */
5046 pname = name;
5047 pp = ptrs;
5048 for (p = slotdefs; p->name_strobj; p++) {
5049 if (p->name_strobj == name)
5050 *pp++ = p;
5051 }
5052 *pp = NULL;
5053 }
5054
5055 /* Look in all matching slots of the type; if exactly one of these has
5056 a filled-in slot, return its value. Otherwise return NULL. */
5057 res = NULL;
5058 for (pp = ptrs; *pp; pp++) {
5059 ptr = slotptr(type, (*pp)->offset);
5060 if (ptr == NULL || *ptr == NULL)
5061 continue;
5062 if (res != NULL)
5063 return NULL;
5064 res = ptr;
5065 }
5066 return res;
5067}
5068
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005069/* Common code for update_slots_callback() and fixup_slot_dispatchers(). This
Guido van Rossumc334df52002-04-04 23:44:47 +00005070 does some incredibly complex thinking and then sticks something into the
5071 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
5072 interests, and then stores a generic wrapper or a specific function into
5073 the slot.) Return a pointer to the next slotdef with a different offset,
5074 because that's convenient for fixup_slot_dispatchers(). */
5075static slotdef *
5076update_one_slot(PyTypeObject *type, slotdef *p)
5077{
5078 PyObject *descr;
5079 PyWrapperDescrObject *d;
5080 void *generic = NULL, *specific = NULL;
5081 int use_generic = 0;
5082 int offset = p->offset;
5083 void **ptr = slotptr(type, offset);
5084
5085 if (ptr == NULL) {
5086 do {
5087 ++p;
5088 } while (p->offset == offset);
5089 return p;
5090 }
5091 do {
5092 descr = _PyType_Lookup(type, p->name_strobj);
5093 if (descr == NULL)
5094 continue;
5095 if (descr->ob_type == &PyWrapperDescr_Type) {
5096 void **tptr = resolve_slotdups(type, p->name_strobj);
5097 if (tptr == NULL || tptr == ptr)
5098 generic = p->function;
5099 d = (PyWrapperDescrObject *)descr;
5100 if (d->d_base->wrapper == p->wrapper &&
5101 PyType_IsSubtype(type, d->d_type))
5102 {
5103 if (specific == NULL ||
5104 specific == d->d_wrapped)
5105 specific = d->d_wrapped;
5106 else
5107 use_generic = 1;
5108 }
5109 }
Guido van Rossum721f62e2002-08-09 02:14:34 +00005110 else if (descr->ob_type == &PyCFunction_Type &&
5111 PyCFunction_GET_FUNCTION(descr) ==
5112 (PyCFunction)tp_new_wrapper &&
5113 strcmp(p->name, "__new__") == 0)
5114 {
5115 /* The __new__ wrapper is not a wrapper descriptor,
5116 so must be special-cased differently.
5117 If we don't do this, creating an instance will
5118 always use slot_tp_new which will look up
5119 __new__ in the MRO which will call tp_new_wrapper
5120 which will look through the base classes looking
5121 for a static base and call its tp_new (usually
5122 PyType_GenericNew), after performing various
5123 sanity checks and constructing a new argument
5124 list. Cut all that nonsense short -- this speeds
5125 up instance creation tremendously. */
Martin v. Löwisa94568a2003-05-10 07:36:56 +00005126 specific = (void *)type->tp_new;
Guido van Rossum721f62e2002-08-09 02:14:34 +00005127 /* XXX I'm not 100% sure that there isn't a hole
5128 in this reasoning that requires additional
5129 sanity checks. I'll buy the first person to
5130 point out a bug in this reasoning a beer. */
5131 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005132 else {
5133 use_generic = 1;
5134 generic = p->function;
5135 }
5136 } while ((++p)->offset == offset);
5137 if (specific && !use_generic)
5138 *ptr = specific;
5139 else
5140 *ptr = generic;
5141 return p;
5142}
5143
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005144/* In the type, update the slots whose slotdefs are gathered in the pp array.
5145 This is a callback for update_subclasses(). */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005146static int
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005147update_slots_callback(PyTypeObject *type, void *data)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005148{
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005149 slotdef **pp = (slotdef **)data;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005150
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005151 for (; *pp; pp++)
Guido van Rossumc334df52002-04-04 23:44:47 +00005152 update_one_slot(type, *pp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005153 return 0;
5154}
5155
Guido van Rossumc334df52002-04-04 23:44:47 +00005156/* Comparison function for qsort() to compare slotdefs by their offset, and
5157 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005158static int
5159slotdef_cmp(const void *aa, const void *bb)
5160{
5161 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
5162 int c = a->offset - b->offset;
5163 if (c != 0)
5164 return c;
5165 else
5166 return a - b;
5167}
5168
Guido van Rossumc334df52002-04-04 23:44:47 +00005169/* Initialize the slotdefs table by adding interned string objects for the
5170 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005171static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005172init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005173{
5174 slotdef *p;
5175 static int initialized = 0;
5176
5177 if (initialized)
5178 return;
5179 for (p = slotdefs; p->name; p++) {
5180 p->name_strobj = PyString_InternFromString(p->name);
5181 if (!p->name_strobj)
Guido van Rossumc334df52002-04-04 23:44:47 +00005182 Py_FatalError("Out of memory interning slotdef names");
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005183 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005184 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
5185 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005186 initialized = 1;
5187}
5188
Guido van Rossumc334df52002-04-04 23:44:47 +00005189/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005190static int
5191update_slot(PyTypeObject *type, PyObject *name)
5192{
Guido van Rossumc334df52002-04-04 23:44:47 +00005193 slotdef *ptrs[MAX_EQUIV];
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005194 slotdef *p;
5195 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005196 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005197
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005198 init_slotdefs();
5199 pp = ptrs;
5200 for (p = slotdefs; p->name; p++) {
5201 /* XXX assume name is interned! */
5202 if (p->name_strobj == name)
5203 *pp++ = p;
5204 }
5205 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005206 for (pp = ptrs; *pp; pp++) {
5207 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005208 offset = p->offset;
5209 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005210 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005211 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005212 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005213 if (ptrs[0] == NULL)
5214 return 0; /* Not an attribute that affects any slots */
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005215 return update_subclasses(type, name,
5216 update_slots_callback, (void *)ptrs);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005217}
5218
Guido van Rossumc334df52002-04-04 23:44:47 +00005219/* Store the proper functions in the slot dispatches at class (type)
5220 definition time, based upon which operations the class overrides in its
5221 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00005222static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005223fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005224{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005225 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005226
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005227 init_slotdefs();
Guido van Rossumc334df52002-04-04 23:44:47 +00005228 for (p = slotdefs; p->name; )
5229 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005230}
Guido van Rossum705f0f52001-08-24 16:47:00 +00005231
Michael W. Hudson98bbc492002-11-26 14:47:27 +00005232static void
5233update_all_slots(PyTypeObject* type)
5234{
5235 slotdef *p;
5236
5237 init_slotdefs();
5238 for (p = slotdefs; p->name; p++) {
5239 /* update_slot returns int but can't actually fail */
5240 update_slot(type, p->name_strobj);
5241 }
5242}
5243
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005244/* recurse_down_subclasses() and update_subclasses() are mutually
5245 recursive functions to call a callback for all subclasses,
5246 but refraining from recursing into subclasses that define 'name'. */
5247
5248static int
5249update_subclasses(PyTypeObject *type, PyObject *name,
5250 update_callback callback, void *data)
5251{
5252 if (callback(type, data) < 0)
5253 return -1;
5254 return recurse_down_subclasses(type, name, callback, data);
5255}
5256
5257static int
5258recurse_down_subclasses(PyTypeObject *type, PyObject *name,
5259 update_callback callback, void *data)
5260{
5261 PyTypeObject *subclass;
5262 PyObject *ref, *subclasses, *dict;
5263 int i, n;
5264
5265 subclasses = type->tp_subclasses;
5266 if (subclasses == NULL)
5267 return 0;
5268 assert(PyList_Check(subclasses));
5269 n = PyList_GET_SIZE(subclasses);
5270 for (i = 0; i < n; i++) {
5271 ref = PyList_GET_ITEM(subclasses, i);
5272 assert(PyWeakref_CheckRef(ref));
5273 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
5274 assert(subclass != NULL);
5275 if ((PyObject *)subclass == Py_None)
5276 continue;
5277 assert(PyType_Check(subclass));
5278 /* Avoid recursing down into unaffected classes */
5279 dict = subclass->tp_dict;
5280 if (dict != NULL && PyDict_Check(dict) &&
5281 PyDict_GetItem(dict, name) != NULL)
5282 continue;
5283 if (update_subclasses(subclass, name, callback, data) < 0)
5284 return -1;
5285 }
5286 return 0;
5287}
5288
Guido van Rossum6d204072001-10-21 00:44:31 +00005289/* This function is called by PyType_Ready() to populate the type's
5290 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00005291 function slot (like tp_repr) that's defined in the type, one or more
5292 corresponding descriptors are added in the type's tp_dict dictionary
5293 under the appropriate name (like __repr__). Some function slots
5294 cause more than one descriptor to be added (for example, the nb_add
5295 slot adds both __add__ and __radd__ descriptors) and some function
5296 slots compete for the same descriptor (for example both sq_item and
5297 mp_subscript generate a __getitem__ descriptor).
5298
5299 In the latter case, the first slotdef entry encoutered wins. Since
Tim Petersbf9b2442003-03-23 05:35:36 +00005300 slotdef entries are sorted by the offset of the slot in the
Guido van Rossume5c691a2003-03-07 15:13:17 +00005301 PyHeapTypeObject, this gives us some control over disambiguating
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005302 between competing slots: the members of PyHeapTypeObject are listed
5303 from most general to least general, so the most general slot is
5304 preferred. In particular, because as_mapping comes before as_sequence,
5305 for a type that defines both mp_subscript and sq_item, mp_subscript
5306 wins.
Guido van Rossum09638c12002-06-13 19:17:46 +00005307
5308 This only adds new descriptors and doesn't overwrite entries in
5309 tp_dict that were previously defined. The descriptors contain a
5310 reference to the C function they must call, so that it's safe if they
5311 are copied into a subtype's __dict__ and the subtype has a different
5312 C function in its slot -- calling the method defined by the
5313 descriptor will call the C function that was used to create it,
5314 rather than the C function present in the slot when it is called.
5315 (This is important because a subtype may have a C function in the
5316 slot that calls the method from the dictionary, and we want to avoid
5317 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00005318
5319static int
5320add_operators(PyTypeObject *type)
5321{
5322 PyObject *dict = type->tp_dict;
5323 slotdef *p;
5324 PyObject *descr;
5325 void **ptr;
5326
5327 init_slotdefs();
5328 for (p = slotdefs; p->name; p++) {
5329 if (p->wrapper == NULL)
5330 continue;
5331 ptr = slotptr(type, p->offset);
5332 if (!ptr || !*ptr)
5333 continue;
5334 if (PyDict_GetItem(dict, p->name_strobj))
5335 continue;
5336 descr = PyDescr_NewWrapper(type, p, *ptr);
5337 if (descr == NULL)
5338 return -1;
5339 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
5340 return -1;
5341 Py_DECREF(descr);
5342 }
5343 if (type->tp_new != NULL) {
5344 if (add_tp_new_wrapper(type) < 0)
5345 return -1;
5346 }
5347 return 0;
5348}
5349
Guido van Rossum705f0f52001-08-24 16:47:00 +00005350
5351/* Cooperative 'super' */
5352
5353typedef struct {
5354 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00005355 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005356 PyObject *obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005357 PyTypeObject *obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005358} superobject;
5359
Guido van Rossum6f799372001-09-20 20:46:19 +00005360static PyMemberDef super_members[] = {
5361 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
5362 "the class invoking super()"},
5363 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
5364 "the instance invoking super(); may be None"},
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005365 {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
5366 "the type of the the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005367 {0}
5368};
5369
Guido van Rossum705f0f52001-08-24 16:47:00 +00005370static void
5371super_dealloc(PyObject *self)
5372{
5373 superobject *su = (superobject *)self;
5374
Guido van Rossum048eb752001-10-02 21:24:57 +00005375 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005376 Py_XDECREF(su->obj);
5377 Py_XDECREF(su->type);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005378 Py_XDECREF(su->obj_type);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005379 self->ob_type->tp_free(self);
5380}
5381
5382static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005383super_repr(PyObject *self)
5384{
5385 superobject *su = (superobject *)self;
5386
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005387 if (su->obj_type)
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005388 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005389 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005390 su->type ? su->type->tp_name : "NULL",
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005391 su->obj_type->tp_name);
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005392 else
5393 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005394 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005395 su->type ? su->type->tp_name : "NULL");
5396}
5397
5398static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00005399super_getattro(PyObject *self, PyObject *name)
5400{
5401 superobject *su = (superobject *)self;
Guido van Rossum76ba09f2003-04-16 19:40:58 +00005402 int skip = su->obj_type == NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005403
Guido van Rossum76ba09f2003-04-16 19:40:58 +00005404 if (!skip) {
5405 /* We want __class__ to return the class of the super object
5406 (i.e. super, or a subclass), not the class of su->obj. */
5407 skip = (PyString_Check(name) &&
5408 PyString_GET_SIZE(name) == 9 &&
5409 strcmp(PyString_AS_STRING(name), "__class__") == 0);
5410 }
5411
5412 if (!skip) {
Tim Petersa91e9642001-11-14 23:32:33 +00005413 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005414 PyTypeObject *starttype;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005415 descrgetfunc f;
5416 int i, n;
5417
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005418 starttype = su->obj_type;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005419 mro = starttype->tp_mro;
5420
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005421 if (mro == NULL)
5422 n = 0;
5423 else {
5424 assert(PyTuple_Check(mro));
5425 n = PyTuple_GET_SIZE(mro);
5426 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005427 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00005428 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00005429 break;
5430 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005431 i++;
5432 res = NULL;
5433 for (; i < n; i++) {
5434 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00005435 if (PyType_Check(tmp))
5436 dict = ((PyTypeObject *)tmp)->tp_dict;
5437 else if (PyClass_Check(tmp))
5438 dict = ((PyClassObject *)tmp)->cl_dict;
5439 else
5440 continue;
5441 res = PyDict_GetItem(dict, name);
Guido van Rossum6cc5bb62003-04-16 20:01:36 +00005442 if (res != NULL) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00005443 Py_INCREF(res);
5444 f = res->ob_type->tp_descr_get;
5445 if (f != NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00005446 tmp = f(res, su->obj,
5447 (PyObject *)starttype);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005448 Py_DECREF(res);
5449 res = tmp;
5450 }
5451 return res;
5452 }
5453 }
5454 }
5455 return PyObject_GenericGetAttr(self, name);
5456}
5457
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005458static PyTypeObject *
Guido van Rossum5b443c62001-12-03 15:38:28 +00005459supercheck(PyTypeObject *type, PyObject *obj)
5460{
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005461 /* Check that a super() call makes sense. Return a type object.
5462
5463 obj can be a new-style class, or an instance of one:
5464
5465 - If it is a class, it must be a subclass of 'type'. This case is
5466 used for class methods; the return value is obj.
5467
5468 - If it is an instance, it must be an instance of 'type'. This is
5469 the normal case; the return value is obj.__class__.
5470
5471 But... when obj is an instance, we want to allow for the case where
5472 obj->ob_type is not a subclass of type, but obj.__class__ is!
5473 This will allow using super() with a proxy for obj.
5474 */
5475
Guido van Rossum8e80a722003-02-18 19:22:22 +00005476 /* Check for first bullet above (special case) */
5477 if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
5478 Py_INCREF(obj);
5479 return (PyTypeObject *)obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005480 }
Guido van Rossum8e80a722003-02-18 19:22:22 +00005481
5482 /* Normal case */
5483 if (PyType_IsSubtype(obj->ob_type, type)) {
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005484 Py_INCREF(obj->ob_type);
5485 return obj->ob_type;
5486 }
5487 else {
5488 /* Try the slow way */
5489 static PyObject *class_str = NULL;
5490 PyObject *class_attr;
5491
5492 if (class_str == NULL) {
5493 class_str = PyString_FromString("__class__");
5494 if (class_str == NULL)
5495 return NULL;
5496 }
5497
5498 class_attr = PyObject_GetAttr(obj, class_str);
5499
5500 if (class_attr != NULL &&
5501 PyType_Check(class_attr) &&
5502 (PyTypeObject *)class_attr != obj->ob_type)
5503 {
5504 int ok = PyType_IsSubtype(
5505 (PyTypeObject *)class_attr, type);
5506 if (ok)
5507 return (PyTypeObject *)class_attr;
5508 }
5509
5510 if (class_attr == NULL)
5511 PyErr_Clear();
5512 else
5513 Py_DECREF(class_attr);
5514 }
5515
Tim Peters97e5ff52003-02-18 19:32:50 +00005516 PyErr_SetString(PyExc_TypeError,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005517 "super(type, obj): "
5518 "obj must be an instance or subtype of type");
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005519 return NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005520}
5521
Guido van Rossum705f0f52001-08-24 16:47:00 +00005522static PyObject *
5523super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5524{
5525 superobject *su = (superobject *)self;
5526 superobject *new;
5527
5528 if (obj == NULL || obj == Py_None || su->obj != NULL) {
5529 /* Not binding to an object, or already bound */
5530 Py_INCREF(self);
5531 return self;
5532 }
Guido van Rossum5b443c62001-12-03 15:38:28 +00005533 if (su->ob_type != &PySuper_Type)
5534 /* If su is an instance of a subclass of super,
5535 call its type */
5536 return PyObject_CallFunction((PyObject *)su->ob_type,
5537 "OO", su->type, obj);
5538 else {
5539 /* Inline the common case */
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005540 PyTypeObject *obj_type = supercheck(su->type, obj);
5541 if (obj_type == NULL)
Guido van Rossum5b443c62001-12-03 15:38:28 +00005542 return NULL;
5543 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
5544 NULL, NULL);
5545 if (new == NULL)
5546 return NULL;
5547 Py_INCREF(su->type);
5548 Py_INCREF(obj);
5549 new->type = su->type;
5550 new->obj = obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005551 new->obj_type = obj_type;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005552 return (PyObject *)new;
5553 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005554}
5555
5556static int
5557super_init(PyObject *self, PyObject *args, PyObject *kwds)
5558{
5559 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00005560 PyTypeObject *type;
5561 PyObject *obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005562 PyTypeObject *obj_type = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005563
5564 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
5565 return -1;
5566 if (obj == Py_None)
5567 obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005568 if (obj != NULL) {
5569 obj_type = supercheck(type, obj);
5570 if (obj_type == NULL)
5571 return -1;
5572 Py_INCREF(obj);
5573 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005574 Py_INCREF(type);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005575 su->type = type;
5576 su->obj = obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005577 su->obj_type = obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005578 return 0;
5579}
5580
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005581PyDoc_STRVAR(super_doc,
Guido van Rossum705f0f52001-08-24 16:47:00 +00005582"super(type) -> unbound super object\n"
5583"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00005584"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00005585"Typical use to call a cooperative superclass method:\n"
5586"class C(B):\n"
5587" def meth(self, arg):\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005588" super(C, self).meth(arg)");
Guido van Rossum705f0f52001-08-24 16:47:00 +00005589
Guido van Rossum048eb752001-10-02 21:24:57 +00005590static int
5591super_traverse(PyObject *self, visitproc visit, void *arg)
5592{
5593 superobject *su = (superobject *)self;
5594 int err;
5595
5596#define VISIT(SLOT) \
5597 if (SLOT) { \
5598 err = visit((PyObject *)(SLOT), arg); \
5599 if (err) \
5600 return err; \
5601 }
5602
5603 VISIT(su->obj);
5604 VISIT(su->type);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005605 VISIT(su->obj_type);
Guido van Rossum048eb752001-10-02 21:24:57 +00005606
5607#undef VISIT
5608
5609 return 0;
5610}
5611
Guido van Rossum705f0f52001-08-24 16:47:00 +00005612PyTypeObject PySuper_Type = {
5613 PyObject_HEAD_INIT(&PyType_Type)
5614 0, /* ob_size */
5615 "super", /* tp_name */
5616 sizeof(superobject), /* tp_basicsize */
5617 0, /* tp_itemsize */
5618 /* methods */
5619 super_dealloc, /* tp_dealloc */
5620 0, /* tp_print */
5621 0, /* tp_getattr */
5622 0, /* tp_setattr */
5623 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005624 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005625 0, /* tp_as_number */
5626 0, /* tp_as_sequence */
5627 0, /* tp_as_mapping */
5628 0, /* tp_hash */
5629 0, /* tp_call */
5630 0, /* tp_str */
5631 super_getattro, /* tp_getattro */
5632 0, /* tp_setattro */
5633 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00005634 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
5635 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005636 super_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00005637 super_traverse, /* tp_traverse */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005638 0, /* tp_clear */
5639 0, /* tp_richcompare */
5640 0, /* tp_weaklistoffset */
5641 0, /* tp_iter */
5642 0, /* tp_iternext */
5643 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005644 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005645 0, /* tp_getset */
5646 0, /* tp_base */
5647 0, /* tp_dict */
5648 super_descr_get, /* tp_descr_get */
5649 0, /* tp_descr_set */
5650 0, /* tp_dictoffset */
5651 super_init, /* tp_init */
5652 PyType_GenericAlloc, /* tp_alloc */
5653 PyType_GenericNew, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00005654 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005655};