blob: bdbabf42e60613a6f2ded0054d44ec332a47f8c7 [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;
Raymond Hettinger8ae46892003-10-12 19:09:37 +0000166 tuple = PyTuple_Pack(2, 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;
Raymond Hettinger8ae46892003-10-12 19:09:37 +0000261 PyArg_UnpackTuple(PyList_GET_ITEM(temp, i),
262 "", 2, 2, &cls, &mro);
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000263 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:
Michael W. Hudsone723e452003-08-07 14:58:10 +0000306 Py_DECREF(type->tp_bases);
307 Py_DECREF(type->tp_base);
308 if (type->tp_mro != old_mro) {
309 Py_DECREF(type->tp_mro);
310 }
311
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000312 type->tp_bases = old_bases;
313 type->tp_base = old_base;
314 type->tp_mro = old_mro;
Tim Petersea7f75d2002-12-07 21:39:16 +0000315
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000316 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000317}
318
319static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000320type_dict(PyTypeObject *type, void *context)
321{
322 if (type->tp_dict == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000323 Py_INCREF(Py_None);
324 return Py_None;
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000325 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000326 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000327}
328
Tim Peters24008312002-03-17 18:56:20 +0000329static PyObject *
330type_get_doc(PyTypeObject *type, void *context)
331{
332 PyObject *result;
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000333 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL)
Tim Peters24008312002-03-17 18:56:20 +0000334 return PyString_FromString(type->tp_doc);
Tim Peters24008312002-03-17 18:56:20 +0000335 result = PyDict_GetItemString(type->tp_dict, "__doc__");
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000336 if (result == NULL) {
337 result = Py_None;
338 Py_INCREF(result);
339 }
340 else if (result->ob_type->tp_descr_get) {
Tim Peters2b858972002-04-18 04:12:28 +0000341 result = result->ob_type->tp_descr_get(result, NULL,
342 (PyObject *)type);
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000343 }
344 else {
345 Py_INCREF(result);
346 }
Tim Peters24008312002-03-17 18:56:20 +0000347 return result;
348}
349
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000350static PyGetSetDef type_getsets[] = {
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000351 {"__name__", (getter)type_name, (setter)type_set_name, NULL},
352 {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL},
Guido van Rossum3926a632001-09-25 16:25:58 +0000353 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000354 {"__dict__", (getter)type_dict, NULL, NULL},
Tim Peters24008312002-03-17 18:56:20 +0000355 {"__doc__", (getter)type_get_doc, NULL, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000356 {0}
357};
358
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000359static int
360type_compare(PyObject *v, PyObject *w)
361{
362 /* This is called with type objects only. So we
363 can just compare the addresses. */
364 Py_uintptr_t vv = (Py_uintptr_t)v;
365 Py_uintptr_t ww = (Py_uintptr_t)w;
366 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
367}
368
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000369static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000370type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000371{
Barry Warsaw7ce36942001-08-24 18:34:26 +0000372 PyObject *mod, *name, *rtn;
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000373 char *kind;
Guido van Rossumc3542212001-08-16 09:18:56 +0000374
375 mod = type_module(type, NULL);
376 if (mod == NULL)
377 PyErr_Clear();
378 else if (!PyString_Check(mod)) {
379 Py_DECREF(mod);
380 mod = NULL;
381 }
382 name = type_name(type, NULL);
383 if (name == NULL)
384 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000385
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000386 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
387 kind = "class";
388 else
389 kind = "type";
390
Barry Warsaw7ce36942001-08-24 18:34:26 +0000391 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__")) {
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000392 rtn = PyString_FromFormat("<%s '%s.%s'>",
393 kind,
Barry Warsaw7ce36942001-08-24 18:34:26 +0000394 PyString_AS_STRING(mod),
395 PyString_AS_STRING(name));
396 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000397 else
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000398 rtn = PyString_FromFormat("<%s '%s'>", kind, type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000399
Guido van Rossumc3542212001-08-16 09:18:56 +0000400 Py_XDECREF(mod);
401 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000402 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000403}
404
Tim Peters6d6c1a32001-08-02 04:15:00 +0000405static PyObject *
406type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
407{
408 PyObject *obj;
409
410 if (type->tp_new == NULL) {
411 PyErr_Format(PyExc_TypeError,
412 "cannot create '%.100s' instances",
413 type->tp_name);
414 return NULL;
415 }
416
Tim Peters3f996e72001-09-13 19:18:27 +0000417 obj = type->tp_new(type, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000418 if (obj != NULL) {
Guido van Rossumf76de622001-10-18 15:49:21 +0000419 /* Ugly exception: when the call was type(something),
420 don't call tp_init on the result. */
421 if (type == &PyType_Type &&
422 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
423 (kwds == NULL ||
424 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
425 return obj;
Guido van Rossum8ace1ab2002-04-06 01:05:01 +0000426 /* If the returned object is not an instance of type,
427 it won't be initialized. */
428 if (!PyType_IsSubtype(obj->ob_type, type))
429 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000430 type = obj->ob_type;
Jeremy Hylton719841e2002-07-16 19:39:38 +0000431 if (PyType_HasFeature(type, Py_TPFLAGS_HAVE_CLASS) &&
432 type->tp_init != NULL &&
Tim Peters6d6c1a32001-08-02 04:15:00 +0000433 type->tp_init(obj, args, kwds) < 0) {
434 Py_DECREF(obj);
435 obj = NULL;
436 }
437 }
438 return obj;
439}
440
441PyObject *
442PyType_GenericAlloc(PyTypeObject *type, int nitems)
443{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000444 PyObject *obj;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000445 const size_t size = _PyObject_VAR_SIZE(type, nitems+1);
446 /* note that we need to add one, for the sentinel */
Tim Peters406fe3b2001-10-06 19:04:01 +0000447
448 if (PyType_IS_GC(type))
Neil Schemenauer09a2ae52002-04-12 03:06:53 +0000449 obj = _PyObject_GC_Malloc(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000450 else
Neil Schemenauerc806c882001-08-29 23:54:54 +0000451 obj = PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000452
Neil Schemenauerc806c882001-08-29 23:54:54 +0000453 if (obj == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000454 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000455
Neil Schemenauerc806c882001-08-29 23:54:54 +0000456 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000457
Tim Peters6d6c1a32001-08-02 04:15:00 +0000458 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
459 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000460
Tim Peters6d6c1a32001-08-02 04:15:00 +0000461 if (type->tp_itemsize == 0)
462 PyObject_INIT(obj, type);
463 else
464 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000465
Tim Peters6d6c1a32001-08-02 04:15:00 +0000466 if (PyType_IS_GC(type))
Neil Schemenauerc806c882001-08-29 23:54:54 +0000467 _PyObject_GC_TRACK(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000468 return obj;
469}
470
471PyObject *
472PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
473{
474 return type->tp_alloc(type, 0);
475}
476
Guido van Rossum9475a232001-10-05 20:51:39 +0000477/* Helpers for subtyping */
478
479static int
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000480traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
481{
482 int i, n;
483 PyMemberDef *mp;
484
485 n = type->ob_size;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000486 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000487 for (i = 0; i < n; i++, mp++) {
488 if (mp->type == T_OBJECT_EX) {
489 char *addr = (char *)self + mp->offset;
490 PyObject *obj = *(PyObject **)addr;
491 if (obj != NULL) {
492 int err = visit(obj, arg);
493 if (err)
494 return err;
495 }
496 }
497 }
498 return 0;
499}
500
501static int
Guido van Rossum9475a232001-10-05 20:51:39 +0000502subtype_traverse(PyObject *self, visitproc visit, void *arg)
503{
504 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000505 traverseproc basetraverse;
Guido van Rossum9475a232001-10-05 20:51:39 +0000506
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000507 /* Find the nearest base with a different tp_traverse,
508 and traverse slots while we're at it */
Guido van Rossum9475a232001-10-05 20:51:39 +0000509 type = self->ob_type;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000510 base = type;
511 while ((basetraverse = base->tp_traverse) == subtype_traverse) {
512 if (base->ob_size) {
513 int err = traverse_slots(base, self, visit, arg);
514 if (err)
515 return err;
516 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000517 base = base->tp_base;
518 assert(base);
519 }
520
521 if (type->tp_dictoffset != base->tp_dictoffset) {
522 PyObject **dictptr = _PyObject_GetDictPtr(self);
523 if (dictptr && *dictptr) {
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000524 int err = visit(*dictptr, arg);
Guido van Rossum9475a232001-10-05 20:51:39 +0000525 if (err)
526 return err;
527 }
528 }
529
Guido van Rossuma3862092002-06-10 15:24:42 +0000530 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
531 /* For a heaptype, the instances count as references
532 to the type. Traverse the type so the collector
533 can find cycles involving this link. */
534 int err = visit((PyObject *)type, arg);
535 if (err)
536 return err;
537 }
538
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000539 if (basetraverse)
540 return basetraverse(self, visit, arg);
541 return 0;
542}
543
544static void
545clear_slots(PyTypeObject *type, PyObject *self)
546{
547 int i, n;
548 PyMemberDef *mp;
549
550 n = type->ob_size;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000551 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000552 for (i = 0; i < n; i++, mp++) {
553 if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
554 char *addr = (char *)self + mp->offset;
555 PyObject *obj = *(PyObject **)addr;
556 if (obj != NULL) {
557 Py_DECREF(obj);
558 *(PyObject **)addr = NULL;
559 }
560 }
561 }
562}
563
564static int
565subtype_clear(PyObject *self)
566{
567 PyTypeObject *type, *base;
568 inquiry baseclear;
569
570 /* Find the nearest base with a different tp_clear
571 and clear slots while we're at it */
572 type = self->ob_type;
573 base = type;
574 while ((baseclear = base->tp_clear) == subtype_clear) {
575 if (base->ob_size)
576 clear_slots(base, self);
577 base = base->tp_base;
578 assert(base);
579 }
580
Guido van Rossuma3862092002-06-10 15:24:42 +0000581 /* There's no need to clear the instance dict (if any);
582 the collector will call its tp_clear handler. */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000583
584 if (baseclear)
585 return baseclear(self);
Guido van Rossum9475a232001-10-05 20:51:39 +0000586 return 0;
587}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000588
589static void
590subtype_dealloc(PyObject *self)
591{
Guido van Rossum14227b42001-12-06 02:35:58 +0000592 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000593 destructor basedealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000594
Guido van Rossum22b13872002-08-06 21:41:44 +0000595 /* Extract the type; we expect it to be a heap type */
596 type = self->ob_type;
597 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000598
Guido van Rossum22b13872002-08-06 21:41:44 +0000599 /* Test whether the type has GC exactly once */
600
601 if (!PyType_IS_GC(type)) {
602 /* It's really rare to find a dynamic type that doesn't have
603 GC; it can only happen when deriving from 'object' and not
604 adding any slots or instance variables. This allows
605 certain simplifications: there's no need to call
606 clear_slots(), or DECREF the dict, or clear weakrefs. */
607
608 /* Maybe call finalizer; exit early if resurrected */
Guido van Rossumfebd61d2002-08-08 20:55:20 +0000609 if (type->tp_del) {
610 type->tp_del(self);
611 if (self->ob_refcnt > 0)
612 return;
613 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000614
615 /* Find the nearest base with a different tp_dealloc */
616 base = type;
617 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
618 assert(base->ob_size == 0);
619 base = base->tp_base;
620 assert(base);
621 }
622
623 /* Call the base tp_dealloc() */
624 assert(basedealloc);
625 basedealloc(self);
626
627 /* Can't reference self beyond this point */
628 Py_DECREF(type);
629
630 /* Done */
631 return;
632 }
633
634 /* We get here only if the type has GC */
635
636 /* UnTrack and re-Track around the trashcan macro, alas */
Andrew M. Kuchlingc9172d32003-02-06 15:22:49 +0000637 /* See explanation at end of function for full disclosure */
Guido van Rossum0906e072002-08-07 20:42:09 +0000638 PyObject_GC_UnTrack(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000639 ++_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000640 Py_TRASHCAN_SAFE_BEGIN(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000641 --_PyTrash_delete_nesting;
Tim Petersadd09b42003-11-12 20:43:28 +0000642 /* DO NOT restore GC tracking at this point. The weakref callback
643 * (if any) may trigger GC, and if self is tracked at that point,
644 * it will look like trash to GC and GC will try to delete it
645 * again. Double-deallocation is a subtle disaster.
646 */
Guido van Rossum22b13872002-08-06 21:41:44 +0000647
Guido van Rossum59195fd2003-06-13 20:54:40 +0000648 /* Find the nearest base with a different tp_dealloc */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000649 base = type;
650 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000651 base = base->tp_base;
652 assert(base);
Guido van Rossum14227b42001-12-06 02:35:58 +0000653 }
654
Guido van Rossum1987c662003-05-29 14:29:23 +0000655 /* If we added a weaklist, we clear it. Do this *before* calling
Guido van Rossum59195fd2003-06-13 20:54:40 +0000656 the finalizer (__del__), clearing slots, or clearing the instance
657 dict. */
658
Guido van Rossum1987c662003-05-29 14:29:23 +0000659 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
660 PyObject_ClearWeakRefs(self);
Tim Petersadd09b42003-11-12 20:43:28 +0000661 _PyObject_GC_TRACK(self); /* We'll untrack for real later */
Guido van Rossum1987c662003-05-29 14:29:23 +0000662
663 /* Maybe call finalizer; exit early if resurrected */
664 if (type->tp_del) {
665 type->tp_del(self);
666 if (self->ob_refcnt > 0)
667 goto endlabel;
668 }
669
Guido van Rossum59195fd2003-06-13 20:54:40 +0000670 /* Clear slots up to the nearest base with a different tp_dealloc */
671 base = type;
672 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
673 if (base->ob_size)
674 clear_slots(base, self);
675 base = base->tp_base;
676 assert(base);
677 }
678
Tim Peters6d6c1a32001-08-02 04:15:00 +0000679 /* If we added a dict, DECREF it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000680 if (type->tp_dictoffset && !base->tp_dictoffset) {
681 PyObject **dictptr = _PyObject_GetDictPtr(self);
682 if (dictptr != NULL) {
683 PyObject *dict = *dictptr;
684 if (dict != NULL) {
685 Py_DECREF(dict);
686 *dictptr = NULL;
687 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000688 }
689 }
690
691 /* Finalize GC if the base doesn't do GC and we do */
Guido van Rossum22b13872002-08-06 21:41:44 +0000692 if (!PyType_IS_GC(base))
Guido van Rossum048eb752001-10-02 21:24:57 +0000693 _PyObject_GC_UNTRACK(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000694
695 /* Call the base tp_dealloc() */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000696 assert(basedealloc);
697 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000698
699 /* Can't reference self beyond this point */
Guido van Rossum22b13872002-08-06 21:41:44 +0000700 Py_DECREF(type);
701
Guido van Rossum0906e072002-08-07 20:42:09 +0000702 endlabel:
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000703 ++_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000704 Py_TRASHCAN_SAFE_END(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000705 --_PyTrash_delete_nesting;
706
707 /* Explanation of the weirdness around the trashcan macros:
708
709 Q. What do the trashcan macros do?
710
711 A. Read the comment titled "Trashcan mechanism" in object.h.
712 For one, this explains why there must be a call to GC-untrack
713 before the trashcan begin macro. Without understanding the
714 trashcan code, the answers to the following questions don't make
715 sense.
716
717 Q. Why do we GC-untrack before the trashcan and then immediately
718 GC-track again afterward?
719
720 A. In the case that the base class is GC-aware, the base class
721 probably GC-untracks the object. If it does that using the
722 UNTRACK macro, this will crash when the object is already
723 untracked. Because we don't know what the base class does, the
724 only safe thing is to make sure the object is tracked when we
725 call the base class dealloc. But... The trashcan begin macro
726 requires that the object is *untracked* before it is called. So
727 the dance becomes:
728
729 GC untrack
730 trashcan begin
731 GC track
732
733 Q. Why the bizarre (net-zero) manipulation of
734 _PyTrash_delete_nesting around the trashcan macros?
735
736 A. Some base classes (e.g. list) also use the trashcan mechanism.
737 The following scenario used to be possible:
738
739 - suppose the trashcan level is one below the trashcan limit
740
741 - subtype_dealloc() is called
742
743 - the trashcan limit is not yet reached, so the trashcan level
744 is incremented and the code between trashcan begin and end is
745 executed
746
747 - this destroys much of the object's contents, including its
748 slots and __dict__
749
750 - basedealloc() is called; this is really list_dealloc(), or
751 some other type which also uses the trashcan macros
752
753 - the trashcan limit is now reached, so the object is put on the
754 trashcan's to-be-deleted-later list
755
756 - basedealloc() returns
757
758 - subtype_dealloc() decrefs the object's type
759
760 - subtype_dealloc() returns
761
762 - later, the trashcan code starts deleting the objects from its
763 to-be-deleted-later list
764
765 - subtype_dealloc() is called *AGAIN* for the same object
766
767 - at the very least (if the destroyed slots and __dict__ don't
768 cause problems) the object's type gets decref'ed a second
769 time, which is *BAD*!!!
770
771 The remedy is to make sure that if the code between trashcan
772 begin and end in subtype_dealloc() is called, the code between
773 trashcan begin and end in basedealloc() will also be called.
774 This is done by decrementing the level after passing into the
775 trashcan block, and incrementing it just before leaving the
776 block.
777
778 But now it's possible that a chain of objects consisting solely
779 of objects whose deallocator is subtype_dealloc() will defeat
780 the trashcan mechanism completely: the decremented level means
781 that the effective level never reaches the limit. Therefore, we
782 *increment* the level *before* entering the trashcan block, and
783 matchingly decrement it after leaving. This means the trashcan
784 code will trigger a little early, but that's no big deal.
785
786 Q. Are there any live examples of code in need of all this
787 complexity?
788
789 A. Yes. See SF bug 668433 for code that crashed (when Python was
790 compiled in debug mode) before the trashcan level manipulations
791 were added. For more discussion, see SF patches 581742, 575073
792 and bug 574207.
793 */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000794}
795
Jeremy Hylton938ace62002-07-17 16:30:39 +0000796static PyTypeObject *solid_base(PyTypeObject *type);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000797
Tim Peters6d6c1a32001-08-02 04:15:00 +0000798/* type test with subclassing support */
799
800int
801PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
802{
803 PyObject *mro;
804
Guido van Rossum9478d072001-09-07 18:52:13 +0000805 if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
806 return b == a || b == &PyBaseObject_Type;
807
Tim Peters6d6c1a32001-08-02 04:15:00 +0000808 mro = a->tp_mro;
809 if (mro != NULL) {
810 /* Deal with multiple inheritance without recursion
811 by walking the MRO tuple */
812 int i, n;
813 assert(PyTuple_Check(mro));
814 n = PyTuple_GET_SIZE(mro);
815 for (i = 0; i < n; i++) {
816 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
817 return 1;
818 }
819 return 0;
820 }
821 else {
822 /* a is not completely initilized yet; follow tp_base */
823 do {
824 if (a == b)
825 return 1;
826 a = a->tp_base;
827 } while (a != NULL);
828 return b == &PyBaseObject_Type;
829 }
830}
831
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000832/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +0000833 without looking in the instance dictionary
834 (so we can't use PyObject_GetAttr) but still binding
835 it to the instance. The arguments are the object,
836 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000837 static variable used to cache the interned Python string.
838
839 Two variants:
840
841 - lookup_maybe() returns NULL without raising an exception
842 when the _PyType_Lookup() call fails;
843
844 - lookup_method() always raises an exception upon errors.
845*/
Guido van Rossum60718732001-08-28 17:47:51 +0000846
847static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000848lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +0000849{
850 PyObject *res;
851
852 if (*attrobj == NULL) {
853 *attrobj = PyString_InternFromString(attrstr);
854 if (*attrobj == NULL)
855 return NULL;
856 }
857 res = _PyType_Lookup(self->ob_type, *attrobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000858 if (res != NULL) {
Guido van Rossum60718732001-08-28 17:47:51 +0000859 descrgetfunc f;
860 if ((f = res->ob_type->tp_descr_get) == NULL)
861 Py_INCREF(res);
862 else
863 res = f(res, self, (PyObject *)(self->ob_type));
864 }
865 return res;
866}
867
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000868static PyObject *
869lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
870{
871 PyObject *res = lookup_maybe(self, attrstr, attrobj);
872 if (res == NULL && !PyErr_Occurred())
873 PyErr_SetObject(PyExc_AttributeError, *attrobj);
874 return res;
875}
876
Guido van Rossum2730b132001-08-28 18:22:14 +0000877/* A variation of PyObject_CallMethod that uses lookup_method()
878 instead of PyObject_GetAttrString(). This uses the same convention
879 as lookup_method to cache the interned name string object. */
880
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000881static PyObject *
Guido van Rossum2730b132001-08-28 18:22:14 +0000882call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
883{
884 va_list va;
885 PyObject *args, *func = 0, *retval;
Guido van Rossum2730b132001-08-28 18:22:14 +0000886 va_start(va, format);
887
Guido van Rossumda21c012001-10-03 00:50:18 +0000888 func = lookup_maybe(o, name, nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000889 if (func == NULL) {
890 va_end(va);
891 if (!PyErr_Occurred())
Guido van Rossumda21c012001-10-03 00:50:18 +0000892 PyErr_SetObject(PyExc_AttributeError, *nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000893 return NULL;
894 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000895
896 if (format && *format)
897 args = Py_VaBuildValue(format, va);
898 else
899 args = PyTuple_New(0);
900
901 va_end(va);
902
903 if (args == NULL)
904 return NULL;
905
906 assert(PyTuple_Check(args));
907 retval = PyObject_Call(func, args, NULL);
908
909 Py_DECREF(args);
910 Py_DECREF(func);
911
912 return retval;
913}
914
915/* Clone of call_method() that returns NotImplemented when the lookup fails. */
916
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000917static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000918call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
919{
920 va_list va;
921 PyObject *args, *func = 0, *retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000922 va_start(va, format);
923
Guido van Rossumda21c012001-10-03 00:50:18 +0000924 func = lookup_maybe(o, name, nameobj);
Guido van Rossum2730b132001-08-28 18:22:14 +0000925 if (func == NULL) {
926 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000927 if (!PyErr_Occurred()) {
928 Py_INCREF(Py_NotImplemented);
929 return Py_NotImplemented;
930 }
Guido van Rossum717ce002001-09-14 16:58:08 +0000931 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +0000932 }
933
934 if (format && *format)
935 args = Py_VaBuildValue(format, va);
936 else
937 args = PyTuple_New(0);
938
939 va_end(va);
940
Guido van Rossum717ce002001-09-14 16:58:08 +0000941 if (args == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +0000942 return NULL;
943
Guido van Rossum717ce002001-09-14 16:58:08 +0000944 assert(PyTuple_Check(args));
945 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +0000946
947 Py_DECREF(args);
948 Py_DECREF(func);
949
950 return retval;
951}
952
Tim Petersa91e9642001-11-14 23:32:33 +0000953static int
954fill_classic_mro(PyObject *mro, PyObject *cls)
955{
956 PyObject *bases, *base;
957 int i, n;
958
959 assert(PyList_Check(mro));
960 assert(PyClass_Check(cls));
961 i = PySequence_Contains(mro, cls);
962 if (i < 0)
963 return -1;
964 if (!i) {
965 if (PyList_Append(mro, cls) < 0)
966 return -1;
967 }
968 bases = ((PyClassObject *)cls)->cl_bases;
969 assert(bases && PyTuple_Check(bases));
970 n = PyTuple_GET_SIZE(bases);
971 for (i = 0; i < n; i++) {
972 base = PyTuple_GET_ITEM(bases, i);
973 if (fill_classic_mro(mro, base) < 0)
974 return -1;
975 }
976 return 0;
977}
978
979static PyObject *
980classic_mro(PyObject *cls)
981{
982 PyObject *mro;
983
984 assert(PyClass_Check(cls));
985 mro = PyList_New(0);
986 if (mro != NULL) {
987 if (fill_classic_mro(mro, cls) == 0)
988 return mro;
989 Py_DECREF(mro);
990 }
991 return NULL;
992}
993
Tim Petersea7f75d2002-12-07 21:39:16 +0000994/*
Guido van Rossum1f121312002-11-14 19:49:16 +0000995 Method resolution order algorithm C3 described in
996 "A Monotonic Superclass Linearization for Dylan",
997 by Kim Barrett, Bob Cassel, Paul Haahr,
Tim Petersea7f75d2002-12-07 21:39:16 +0000998 David A. Moon, Keith Playford, and P. Tucker Withington.
Guido van Rossum1f121312002-11-14 19:49:16 +0000999 (OOPSLA 1996)
1000
Guido van Rossum98f33732002-11-25 21:36:54 +00001001 Some notes about the rules implied by C3:
1002
Tim Petersea7f75d2002-12-07 21:39:16 +00001003 No duplicate bases.
Guido van Rossum98f33732002-11-25 21:36:54 +00001004 It isn't legal to repeat a class in a list of base classes.
1005
1006 The next three properties are the 3 constraints in "C3".
1007
Tim Petersea7f75d2002-12-07 21:39:16 +00001008 Local precendece order.
Guido van Rossum98f33732002-11-25 21:36:54 +00001009 If A precedes B in C's MRO, then A will precede B in the MRO of all
1010 subclasses of C.
1011
1012 Monotonicity.
1013 The MRO of a class must be an extension without reordering of the
1014 MRO of each of its superclasses.
1015
1016 Extended Precedence Graph (EPG).
1017 Linearization is consistent if there is a path in the EPG from
1018 each class to all its successors in the linearization. See
1019 the paper for definition of EPG.
Guido van Rossum1f121312002-11-14 19:49:16 +00001020 */
1021
Tim Petersea7f75d2002-12-07 21:39:16 +00001022static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001023tail_contains(PyObject *list, int whence, PyObject *o) {
1024 int j, size;
1025 size = PyList_GET_SIZE(list);
1026
1027 for (j = whence+1; j < size; j++) {
1028 if (PyList_GET_ITEM(list, j) == o)
1029 return 1;
1030 }
1031 return 0;
1032}
1033
Guido van Rossum98f33732002-11-25 21:36:54 +00001034static PyObject *
1035class_name(PyObject *cls)
1036{
1037 PyObject *name = PyObject_GetAttrString(cls, "__name__");
1038 if (name == NULL) {
1039 PyErr_Clear();
1040 Py_XDECREF(name);
1041 name = PyObject_Repr(cls);
1042 }
1043 if (name == NULL)
1044 return NULL;
1045 if (!PyString_Check(name)) {
1046 Py_DECREF(name);
1047 return NULL;
1048 }
1049 return name;
1050}
1051
1052static int
1053check_duplicates(PyObject *list)
1054{
1055 int i, j, n;
1056 /* Let's use a quadratic time algorithm,
1057 assuming that the bases lists is short.
1058 */
1059 n = PyList_GET_SIZE(list);
1060 for (i = 0; i < n; i++) {
1061 PyObject *o = PyList_GET_ITEM(list, i);
1062 for (j = i + 1; j < n; j++) {
1063 if (PyList_GET_ITEM(list, j) == o) {
1064 o = class_name(o);
1065 PyErr_Format(PyExc_TypeError,
1066 "duplicate base class %s",
1067 o ? PyString_AS_STRING(o) : "?");
1068 Py_XDECREF(o);
1069 return -1;
1070 }
1071 }
1072 }
1073 return 0;
1074}
1075
1076/* Raise a TypeError for an MRO order disagreement.
1077
1078 It's hard to produce a good error message. In the absence of better
1079 insight into error reporting, report the classes that were candidates
1080 to be put next into the MRO. There is some conflict between the
1081 order in which they should be put in the MRO, but it's hard to
1082 diagnose what constraint can't be satisfied.
1083*/
1084
1085static void
1086set_mro_error(PyObject *to_merge, int *remain)
1087{
1088 int i, n, off, to_merge_size;
1089 char buf[1000];
1090 PyObject *k, *v;
1091 PyObject *set = PyDict_New();
1092
1093 to_merge_size = PyList_GET_SIZE(to_merge);
1094 for (i = 0; i < to_merge_size; i++) {
1095 PyObject *L = PyList_GET_ITEM(to_merge, i);
1096 if (remain[i] < PyList_GET_SIZE(L)) {
1097 PyObject *c = PyList_GET_ITEM(L, remain[i]);
1098 if (PyDict_SetItem(set, c, Py_None) < 0)
1099 return;
1100 }
1101 }
1102 n = PyDict_Size(set);
1103
Raymond Hettingerf394df42003-04-06 19:13:41 +00001104 off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \
1105consistent method resolution\norder (MRO) for bases");
Guido van Rossum98f33732002-11-25 21:36:54 +00001106 i = 0;
1107 while (PyDict_Next(set, &i, &k, &v) && off < sizeof(buf)) {
1108 PyObject *name = class_name(k);
1109 off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s",
1110 name ? PyString_AS_STRING(name) : "?");
1111 Py_XDECREF(name);
1112 if (--n && off+1 < sizeof(buf)) {
1113 buf[off++] = ',';
1114 buf[off] = '\0';
1115 }
1116 }
1117 PyErr_SetString(PyExc_TypeError, buf);
1118 Py_DECREF(set);
1119}
1120
Tim Petersea7f75d2002-12-07 21:39:16 +00001121static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001122pmerge(PyObject *acc, PyObject* to_merge) {
1123 int i, j, to_merge_size;
1124 int *remain;
1125 int ok, empty_cnt;
Tim Petersea7f75d2002-12-07 21:39:16 +00001126
Guido van Rossum1f121312002-11-14 19:49:16 +00001127 to_merge_size = PyList_GET_SIZE(to_merge);
1128
Guido van Rossum98f33732002-11-25 21:36:54 +00001129 /* remain stores an index into each sublist of to_merge.
1130 remain[i] is the index of the next base in to_merge[i]
1131 that is not included in acc.
1132 */
Guido van Rossum1f121312002-11-14 19:49:16 +00001133 remain = PyMem_MALLOC(SIZEOF_INT*to_merge_size);
1134 if (remain == NULL)
1135 return -1;
1136 for (i = 0; i < to_merge_size; i++)
1137 remain[i] = 0;
1138
1139 again:
1140 empty_cnt = 0;
1141 for (i = 0; i < to_merge_size; i++) {
1142 PyObject *candidate;
Tim Petersea7f75d2002-12-07 21:39:16 +00001143
Guido van Rossum1f121312002-11-14 19:49:16 +00001144 PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
1145
1146 if (remain[i] >= PyList_GET_SIZE(cur_list)) {
1147 empty_cnt++;
1148 continue;
1149 }
1150
Guido van Rossum98f33732002-11-25 21:36:54 +00001151 /* Choose next candidate for MRO.
1152
1153 The input sequences alone can determine the choice.
1154 If not, choose the class which appears in the MRO
1155 of the earliest direct superclass of the new class.
1156 */
1157
Guido van Rossum1f121312002-11-14 19:49:16 +00001158 candidate = PyList_GET_ITEM(cur_list, remain[i]);
1159 for (j = 0; j < to_merge_size; j++) {
1160 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum98f33732002-11-25 21:36:54 +00001161 if (tail_contains(j_lst, remain[j], candidate)) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001162 goto skip; /* continue outer loop */
Guido van Rossum98f33732002-11-25 21:36:54 +00001163 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001164 }
1165 ok = PyList_Append(acc, candidate);
1166 if (ok < 0) {
1167 PyMem_Free(remain);
1168 return -1;
1169 }
1170 for (j = 0; j < to_merge_size; j++) {
1171 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum768158c2002-12-31 16:33:01 +00001172 if (remain[j] < PyList_GET_SIZE(j_lst) &&
1173 PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001174 remain[j]++;
1175 }
1176 }
1177 goto again;
Tim Peters9a6b8d82002-11-14 23:22:33 +00001178 skip: ;
Guido van Rossum1f121312002-11-14 19:49:16 +00001179 }
1180
Guido van Rossum98f33732002-11-25 21:36:54 +00001181 if (empty_cnt == to_merge_size) {
1182 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001183 return 0;
Guido van Rossum98f33732002-11-25 21:36:54 +00001184 }
1185 set_mro_error(to_merge, remain);
1186 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001187 return -1;
1188}
1189
Tim Peters6d6c1a32001-08-02 04:15:00 +00001190static PyObject *
1191mro_implementation(PyTypeObject *type)
1192{
1193 int i, n, ok;
1194 PyObject *bases, *result;
Guido van Rossum1f121312002-11-14 19:49:16 +00001195 PyObject *to_merge, *bases_aslist;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001196
Guido van Rossum63517572002-06-18 16:44:57 +00001197 if(type->tp_dict == NULL) {
1198 if(PyType_Ready(type) < 0)
1199 return NULL;
1200 }
1201
Guido van Rossum98f33732002-11-25 21:36:54 +00001202 /* Find a superclass linearization that honors the constraints
1203 of the explicit lists of bases and the constraints implied by
Tim Petersea7f75d2002-12-07 21:39:16 +00001204 each base class.
Guido van Rossum98f33732002-11-25 21:36:54 +00001205
1206 to_merge is a list of lists, where each list is a superclass
1207 linearization implied by a base class. The last element of
1208 to_merge is the declared list of bases.
1209 */
1210
Tim Peters6d6c1a32001-08-02 04:15:00 +00001211 bases = type->tp_bases;
1212 n = PyTuple_GET_SIZE(bases);
Guido van Rossum1f121312002-11-14 19:49:16 +00001213
1214 to_merge = PyList_New(n+1);
1215 if (to_merge == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001216 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001217
Tim Peters6d6c1a32001-08-02 04:15:00 +00001218 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001219 PyObject *base = PyTuple_GET_ITEM(bases, i);
1220 PyObject *parentMRO;
1221 if (PyType_Check(base))
1222 parentMRO = PySequence_List(
1223 ((PyTypeObject*)base)->tp_mro);
1224 else
1225 parentMRO = classic_mro(base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001226 if (parentMRO == NULL) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001227 Py_DECREF(to_merge);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001228 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001229 }
1230
1231 PyList_SET_ITEM(to_merge, i, parentMRO);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001232 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001233
1234 bases_aslist = PySequence_List(bases);
1235 if (bases_aslist == NULL) {
1236 Py_DECREF(to_merge);
1237 return NULL;
1238 }
Guido van Rossum98f33732002-11-25 21:36:54 +00001239 /* This is just a basic sanity check. */
1240 if (check_duplicates(bases_aslist) < 0) {
1241 Py_DECREF(to_merge);
1242 Py_DECREF(bases_aslist);
1243 return NULL;
1244 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001245 PyList_SET_ITEM(to_merge, n, bases_aslist);
1246
1247 result = Py_BuildValue("[O]", (PyObject *)type);
1248 if (result == NULL) {
1249 Py_DECREF(to_merge);
1250 return NULL;
1251 }
1252
1253 ok = pmerge(result, to_merge);
1254 Py_DECREF(to_merge);
1255 if (ok < 0) {
1256 Py_DECREF(result);
1257 return NULL;
1258 }
1259
Tim Peters6d6c1a32001-08-02 04:15:00 +00001260 return result;
1261}
1262
1263static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001264mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001265{
1266 PyTypeObject *type = (PyTypeObject *)self;
1267
Tim Peters6d6c1a32001-08-02 04:15:00 +00001268 return mro_implementation(type);
1269}
1270
1271static int
1272mro_internal(PyTypeObject *type)
1273{
1274 PyObject *mro, *result, *tuple;
1275
1276 if (type->ob_type == &PyType_Type) {
1277 result = mro_implementation(type);
1278 }
1279 else {
Guido van Rossum60718732001-08-28 17:47:51 +00001280 static PyObject *mro_str;
1281 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001282 if (mro == NULL)
1283 return -1;
1284 result = PyObject_CallObject(mro, NULL);
1285 Py_DECREF(mro);
1286 }
1287 if (result == NULL)
1288 return -1;
1289 tuple = PySequence_Tuple(result);
1290 Py_DECREF(result);
1291 type->tp_mro = tuple;
1292 return 0;
1293}
1294
1295
1296/* Calculate the best base amongst multiple base classes.
1297 This is the first one that's on the path to the "solid base". */
1298
1299static PyTypeObject *
1300best_base(PyObject *bases)
1301{
1302 int i, n;
1303 PyTypeObject *base, *winner, *candidate, *base_i;
Tim Petersa91e9642001-11-14 23:32:33 +00001304 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001305
1306 assert(PyTuple_Check(bases));
1307 n = PyTuple_GET_SIZE(bases);
1308 assert(n > 0);
Tim Petersa91e9642001-11-14 23:32:33 +00001309 base = NULL;
1310 winner = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001311 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001312 base_proto = PyTuple_GET_ITEM(bases, i);
1313 if (PyClass_Check(base_proto))
1314 continue;
1315 if (!PyType_Check(base_proto)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001316 PyErr_SetString(
1317 PyExc_TypeError,
1318 "bases must be types");
1319 return NULL;
1320 }
Tim Petersa91e9642001-11-14 23:32:33 +00001321 base_i = (PyTypeObject *)base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001322 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001323 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001324 return NULL;
1325 }
1326 candidate = solid_base(base_i);
Tim Petersa91e9642001-11-14 23:32:33 +00001327 if (winner == NULL) {
1328 winner = candidate;
1329 base = base_i;
1330 }
1331 else if (PyType_IsSubtype(winner, candidate))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001332 ;
1333 else if (PyType_IsSubtype(candidate, winner)) {
1334 winner = candidate;
1335 base = base_i;
1336 }
1337 else {
1338 PyErr_SetString(
1339 PyExc_TypeError,
1340 "multiple bases have "
1341 "instance lay-out conflict");
1342 return NULL;
1343 }
1344 }
Guido van Rossume54616c2001-12-14 04:19:56 +00001345 if (base == NULL)
1346 PyErr_SetString(PyExc_TypeError,
1347 "a new-style class can't have only classic bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001348 return base;
1349}
1350
1351static int
1352extra_ivars(PyTypeObject *type, PyTypeObject *base)
1353{
Neil Schemenauerc806c882001-08-29 23:54:54 +00001354 size_t t_size = type->tp_basicsize;
1355 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001356
Guido van Rossum9676b222001-08-17 20:32:36 +00001357 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001358 if (type->tp_itemsize || base->tp_itemsize) {
1359 /* If itemsize is involved, stricter rules */
1360 return t_size != b_size ||
1361 type->tp_itemsize != base->tp_itemsize;
1362 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001363 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
1364 type->tp_weaklistoffset + sizeof(PyObject *) == t_size)
1365 t_size -= sizeof(PyObject *);
1366 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
1367 type->tp_dictoffset + sizeof(PyObject *) == t_size)
1368 t_size -= sizeof(PyObject *);
1369
1370 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001371}
1372
1373static PyTypeObject *
1374solid_base(PyTypeObject *type)
1375{
1376 PyTypeObject *base;
1377
1378 if (type->tp_base)
1379 base = solid_base(type->tp_base);
1380 else
1381 base = &PyBaseObject_Type;
1382 if (extra_ivars(type, base))
1383 return type;
1384 else
1385 return base;
1386}
1387
Jeremy Hylton938ace62002-07-17 16:30:39 +00001388static void object_dealloc(PyObject *);
1389static int object_init(PyObject *, PyObject *, PyObject *);
1390static int update_slot(PyTypeObject *, PyObject *);
1391static void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001392
1393static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001394subtype_dict(PyObject *obj, void *context)
1395{
1396 PyObject **dictptr = _PyObject_GetDictPtr(obj);
1397 PyObject *dict;
1398
1399 if (dictptr == NULL) {
1400 PyErr_SetString(PyExc_AttributeError,
1401 "This object has no __dict__");
1402 return NULL;
1403 }
1404 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +00001405 if (dict == NULL)
1406 *dictptr = dict = PyDict_New();
1407 Py_XINCREF(dict);
1408 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001409}
1410
Guido van Rossum6661be32001-10-26 04:26:12 +00001411static int
1412subtype_setdict(PyObject *obj, PyObject *value, void *context)
1413{
1414 PyObject **dictptr = _PyObject_GetDictPtr(obj);
1415 PyObject *dict;
1416
1417 if (dictptr == NULL) {
1418 PyErr_SetString(PyExc_AttributeError,
1419 "This object has no __dict__");
1420 return -1;
1421 }
Guido van Rossumd331cb52001-12-05 19:46:42 +00001422 if (value != NULL && !PyDict_Check(value)) {
Guido van Rossum6661be32001-10-26 04:26:12 +00001423 PyErr_SetString(PyExc_TypeError,
1424 "__dict__ must be set to a dictionary");
1425 return -1;
1426 }
1427 dict = *dictptr;
Guido van Rossumd331cb52001-12-05 19:46:42 +00001428 Py_XINCREF(value);
Guido van Rossum6661be32001-10-26 04:26:12 +00001429 *dictptr = value;
1430 Py_XDECREF(dict);
1431 return 0;
1432}
1433
Guido van Rossumad47da02002-08-12 19:05:44 +00001434static PyObject *
1435subtype_getweakref(PyObject *obj, void *context)
1436{
1437 PyObject **weaklistptr;
1438 PyObject *result;
1439
1440 if (obj->ob_type->tp_weaklistoffset == 0) {
1441 PyErr_SetString(PyExc_AttributeError,
1442 "This object has no __weaklist__");
1443 return NULL;
1444 }
1445 assert(obj->ob_type->tp_weaklistoffset > 0);
1446 assert(obj->ob_type->tp_weaklistoffset + sizeof(PyObject *) <=
Guido van Rossum3747a0f2002-08-12 19:25:08 +00001447 (size_t)(obj->ob_type->tp_basicsize));
Guido van Rossumad47da02002-08-12 19:05:44 +00001448 weaklistptr = (PyObject **)
Guido van Rossum3747a0f2002-08-12 19:25:08 +00001449 ((char *)obj + obj->ob_type->tp_weaklistoffset);
Guido van Rossumad47da02002-08-12 19:05:44 +00001450 if (*weaklistptr == NULL)
1451 result = Py_None;
1452 else
1453 result = *weaklistptr;
1454 Py_INCREF(result);
1455 return result;
1456}
1457
Guido van Rossum373c7412003-01-07 13:41:37 +00001458/* Three variants on the subtype_getsets list. */
1459
1460static PyGetSetDef subtype_getsets_full[] = {
Guido van Rossumad47da02002-08-12 19:05:44 +00001461 {"__dict__", subtype_dict, subtype_setdict,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001462 PyDoc_STR("dictionary for instance variables (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001463 {"__weakref__", subtype_getweakref, NULL,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001464 PyDoc_STR("list of weak references to the object (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001465 {0}
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001466};
1467
Guido van Rossum373c7412003-01-07 13:41:37 +00001468static PyGetSetDef subtype_getsets_dict_only[] = {
1469 {"__dict__", subtype_dict, subtype_setdict,
1470 PyDoc_STR("dictionary for instance variables (if defined)")},
1471 {0}
1472};
1473
1474static PyGetSetDef subtype_getsets_weakref_only[] = {
1475 {"__weakref__", subtype_getweakref, NULL,
1476 PyDoc_STR("list of weak references to the object (if defined)")},
1477 {0}
1478};
1479
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001480static int
1481valid_identifier(PyObject *s)
1482{
Guido van Rossum03013a02002-07-16 14:30:28 +00001483 unsigned char *p;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001484 int i, n;
1485
1486 if (!PyString_Check(s)) {
1487 PyErr_SetString(PyExc_TypeError,
1488 "__slots__ must be strings");
1489 return 0;
1490 }
Guido van Rossum03013a02002-07-16 14:30:28 +00001491 p = (unsigned char *) PyString_AS_STRING(s);
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001492 n = PyString_GET_SIZE(s);
1493 /* We must reject an empty name. As a hack, we bump the
1494 length to 1 so that the loop will balk on the trailing \0. */
1495 if (n == 0)
1496 n = 1;
1497 for (i = 0; i < n; i++, p++) {
1498 if (!(i == 0 ? isalpha(*p) : isalnum(*p)) && *p != '_') {
1499 PyErr_SetString(PyExc_TypeError,
1500 "__slots__ must be identifiers");
1501 return 0;
1502 }
1503 }
1504 return 1;
1505}
1506
Martin v. Löwisd919a592002-10-14 21:07:28 +00001507#ifdef Py_USING_UNICODE
1508/* Replace Unicode objects in slots. */
1509
1510static PyObject *
1511_unicode_to_string(PyObject *slots, int nslots)
1512{
1513 PyObject *tmp = slots;
1514 PyObject *o, *o1;
1515 int i;
1516 intintargfunc copy = slots->ob_type->tp_as_sequence->sq_slice;
1517 for (i = 0; i < nslots; i++) {
1518 if (PyUnicode_Check(o = PyTuple_GET_ITEM(tmp, i))) {
1519 if (tmp == slots) {
1520 tmp = copy(slots, 0, PyTuple_GET_SIZE(slots));
1521 if (tmp == NULL)
1522 return NULL;
1523 }
1524 o1 = _PyUnicode_AsDefaultEncodedString
1525 (o, NULL);
1526 if (o1 == NULL) {
1527 Py_DECREF(tmp);
1528 return 0;
1529 }
1530 Py_INCREF(o1);
1531 Py_DECREF(o);
1532 PyTuple_SET_ITEM(tmp, i, o1);
1533 }
1534 }
1535 return tmp;
1536}
1537#endif
1538
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001539static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001540type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
1541{
1542 PyObject *name, *bases, *dict;
1543 static char *kwlist[] = {"name", "bases", "dict", 0};
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001544 PyObject *slots, *tmp, *newslots;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001545 PyTypeObject *type, *base, *tmptype, *winner;
Guido van Rossume5c691a2003-03-07 15:13:17 +00001546 PyHeapTypeObject *et;
Guido van Rossum6f799372001-09-20 20:46:19 +00001547 PyMemberDef *mp;
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001548 int i, nbases, nslots, slotoffset, add_dict, add_weak;
Guido van Rossumad47da02002-08-12 19:05:44 +00001549 int j, may_add_dict, may_add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001550
Tim Peters3abca122001-10-27 19:37:48 +00001551 assert(args != NULL && PyTuple_Check(args));
1552 assert(kwds == NULL || PyDict_Check(kwds));
1553
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001554 /* Special case: type(x) should return x->ob_type */
Tim Peters3abca122001-10-27 19:37:48 +00001555 {
1556 const int nargs = PyTuple_GET_SIZE(args);
1557 const int nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
1558
1559 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
1560 PyObject *x = PyTuple_GET_ITEM(args, 0);
1561 Py_INCREF(x->ob_type);
1562 return (PyObject *) x->ob_type;
1563 }
1564
1565 /* SF bug 475327 -- if that didn't trigger, we need 3
1566 arguments. but PyArg_ParseTupleAndKeywords below may give
1567 a msg saying type() needs exactly 3. */
1568 if (nargs + nkwds != 3) {
1569 PyErr_SetString(PyExc_TypeError,
1570 "type() takes 1 or 3 arguments");
1571 return NULL;
1572 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001573 }
1574
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001575 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001576 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
1577 &name,
1578 &PyTuple_Type, &bases,
1579 &PyDict_Type, &dict))
1580 return NULL;
1581
1582 /* Determine the proper metatype to deal with this,
1583 and check for metatype conflicts while we're at it.
1584 Note that if some other metatype wins to contract,
1585 it's possible that its instances are not types. */
1586 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001587 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001588 for (i = 0; i < nbases; i++) {
1589 tmp = PyTuple_GET_ITEM(bases, i);
1590 tmptype = tmp->ob_type;
Tim Petersa91e9642001-11-14 23:32:33 +00001591 if (tmptype == &PyClass_Type)
1592 continue; /* Special case classic classes */
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001593 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001594 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001595 if (PyType_IsSubtype(tmptype, winner)) {
1596 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001597 continue;
1598 }
1599 PyErr_SetString(PyExc_TypeError,
Guido van Rossum636688d2003-04-23 12:07:22 +00001600 "metaclass conflict: "
1601 "the metaclass of a derived class "
1602 "must be a (non-strict) subclass "
1603 "of the metaclasses of all its bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001604 return NULL;
1605 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001606 if (winner != metatype) {
1607 if (winner->tp_new != type_new) /* Pass it to the winner */
1608 return winner->tp_new(winner, args, kwds);
1609 metatype = winner;
1610 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001611
1612 /* Adjust for empty tuple bases */
1613 if (nbases == 0) {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001614 bases = PyTuple_Pack(1, &PyBaseObject_Type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001615 if (bases == NULL)
1616 return NULL;
1617 nbases = 1;
1618 }
1619 else
1620 Py_INCREF(bases);
1621
1622 /* XXX From here until type is allocated, "return NULL" leaks bases! */
1623
1624 /* Calculate best base, and check that all bases are type objects */
1625 base = best_base(bases);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001626 if (base == NULL) {
1627 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001628 return NULL;
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001629 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001630 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
1631 PyErr_Format(PyExc_TypeError,
1632 "type '%.100s' is not an acceptable base type",
1633 base->tp_name);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001634 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001635 return NULL;
1636 }
1637
Tim Peters6d6c1a32001-08-02 04:15:00 +00001638 /* Check for a __slots__ sequence variable in dict, and count it */
1639 slots = PyDict_GetItemString(dict, "__slots__");
1640 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +00001641 add_dict = 0;
1642 add_weak = 0;
Guido van Rossumad47da02002-08-12 19:05:44 +00001643 may_add_dict = base->tp_dictoffset == 0;
1644 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
1645 if (slots == NULL) {
1646 if (may_add_dict) {
1647 add_dict++;
1648 }
1649 if (may_add_weak) {
1650 add_weak++;
1651 }
1652 }
1653 else {
1654 /* Have slots */
1655
Tim Peters6d6c1a32001-08-02 04:15:00 +00001656 /* Make it into a tuple */
1657 if (PyString_Check(slots))
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001658 slots = PyTuple_Pack(1, slots);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001659 else
1660 slots = PySequence_Tuple(slots);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001661 if (slots == NULL) {
1662 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001663 return NULL;
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001664 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001665 assert(PyTuple_Check(slots));
1666
1667 /* Are slots allowed? */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001668 nslots = PyTuple_GET_SIZE(slots);
Jeremy Hylton1c7a0ea2003-07-16 16:08:23 +00001669 if (nslots > 0 && base->tp_itemsize != 0) {
Guido van Rossumc4141872001-08-30 04:43:35 +00001670 PyErr_Format(PyExc_TypeError,
1671 "nonempty __slots__ "
1672 "not supported for subtype of '%s'",
1673 base->tp_name);
Guido van Rossumad47da02002-08-12 19:05:44 +00001674 bad_slots:
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001675 Py_DECREF(bases);
Guido van Rossumad47da02002-08-12 19:05:44 +00001676 Py_DECREF(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +00001677 return NULL;
1678 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001679
Martin v. Löwisd919a592002-10-14 21:07:28 +00001680#ifdef Py_USING_UNICODE
1681 tmp = _unicode_to_string(slots, nslots);
Martin v. Löwis13b1a5c2002-10-14 21:11:34 +00001682 if (tmp != slots) {
1683 Py_DECREF(slots);
1684 slots = tmp;
1685 }
Martin v. Löwisd919a592002-10-14 21:07:28 +00001686 if (!tmp)
1687 return NULL;
1688#endif
Guido van Rossumad47da02002-08-12 19:05:44 +00001689 /* Check for valid slot names and two special cases */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001690 for (i = 0; i < nslots; i++) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001691 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
1692 char *s;
1693 if (!valid_identifier(tmp))
1694 goto bad_slots;
1695 assert(PyString_Check(tmp));
1696 s = PyString_AS_STRING(tmp);
1697 if (strcmp(s, "__dict__") == 0) {
1698 if (!may_add_dict || add_dict) {
1699 PyErr_SetString(PyExc_TypeError,
1700 "__dict__ slot disallowed: "
1701 "we already got one");
1702 goto bad_slots;
1703 }
1704 add_dict++;
1705 }
1706 if (strcmp(s, "__weakref__") == 0) {
1707 if (!may_add_weak || add_weak) {
1708 PyErr_SetString(PyExc_TypeError,
1709 "__weakref__ slot disallowed: "
1710 "either we already got one, "
1711 "or __itemsize__ != 0");
1712 goto bad_slots;
1713 }
1714 add_weak++;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001715 }
1716 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001717
Guido van Rossumad47da02002-08-12 19:05:44 +00001718 /* Copy slots into yet another tuple, demangling names */
1719 newslots = PyTuple_New(nslots - add_dict - add_weak);
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001720 if (newslots == NULL)
Guido van Rossumad47da02002-08-12 19:05:44 +00001721 goto bad_slots;
1722 for (i = j = 0; i < nslots; i++) {
1723 char *s;
Guido van Rossum8e829202002-08-16 03:47:49 +00001724 char buffer[256];
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001725 tmp = PyTuple_GET_ITEM(slots, i);
Guido van Rossumad47da02002-08-12 19:05:44 +00001726 s = PyString_AS_STRING(tmp);
1727 if ((add_dict && strcmp(s, "__dict__") == 0) ||
1728 (add_weak && strcmp(s, "__weakref__") == 0))
1729 continue;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001730 if (_Py_Mangle(PyString_AS_STRING(name),
Guido van Rossumad47da02002-08-12 19:05:44 +00001731 PyString_AS_STRING(tmp),
1732 buffer, sizeof(buffer)))
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001733 {
1734 tmp = PyString_FromString(buffer);
1735 } else {
1736 Py_INCREF(tmp);
1737 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001738 PyTuple_SET_ITEM(newslots, j, tmp);
1739 j++;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001740 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001741 assert(j == nslots - add_dict - add_weak);
1742 nslots = j;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001743 Py_DECREF(slots);
1744 slots = newslots;
1745
Guido van Rossumad47da02002-08-12 19:05:44 +00001746 /* Secondary bases may provide weakrefs or dict */
1747 if (nbases > 1 &&
1748 ((may_add_dict && !add_dict) ||
1749 (may_add_weak && !add_weak))) {
1750 for (i = 0; i < nbases; i++) {
1751 tmp = PyTuple_GET_ITEM(bases, i);
1752 if (tmp == (PyObject *)base)
1753 continue; /* Skip primary base */
1754 if (PyClass_Check(tmp)) {
1755 /* Classic base class provides both */
1756 if (may_add_dict && !add_dict)
1757 add_dict++;
1758 if (may_add_weak && !add_weak)
1759 add_weak++;
1760 break;
1761 }
1762 assert(PyType_Check(tmp));
1763 tmptype = (PyTypeObject *)tmp;
1764 if (may_add_dict && !add_dict &&
1765 tmptype->tp_dictoffset != 0)
1766 add_dict++;
1767 if (may_add_weak && !add_weak &&
1768 tmptype->tp_weaklistoffset != 0)
1769 add_weak++;
1770 if (may_add_dict && !add_dict)
1771 continue;
1772 if (may_add_weak && !add_weak)
1773 continue;
1774 /* Nothing more to check */
1775 break;
1776 }
1777 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001778 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001779
1780 /* XXX From here until type is safely allocated,
1781 "return NULL" may leak slots! */
1782
1783 /* Allocate the type object */
1784 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
Guido van Rossumad47da02002-08-12 19:05:44 +00001785 if (type == NULL) {
1786 Py_XDECREF(slots);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001787 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001788 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00001789 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001790
1791 /* Keep name and slots alive in the extended type object */
Guido van Rossume5c691a2003-03-07 15:13:17 +00001792 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001793 Py_INCREF(name);
1794 et->name = name;
1795 et->slots = slots;
1796
Guido van Rossumdc91b992001-08-08 22:26:22 +00001797 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001798 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
1799 Py_TPFLAGS_BASETYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00001800 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
1801 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00001802
1803 /* It's a new-style number unless it specifically inherits any
1804 old-style numeric behavior */
1805 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
1806 (base->tp_as_number == NULL))
1807 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
1808
1809 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001810 type->tp_as_number = &et->as_number;
1811 type->tp_as_sequence = &et->as_sequence;
1812 type->tp_as_mapping = &et->as_mapping;
1813 type->tp_as_buffer = &et->as_buffer;
1814 type->tp_name = PyString_AS_STRING(name);
1815
1816 /* Set tp_base and tp_bases */
1817 type->tp_bases = bases;
1818 Py_INCREF(base);
1819 type->tp_base = base;
1820
Guido van Rossum687ae002001-10-15 22:03:32 +00001821 /* Initialize tp_dict from passed-in dict */
1822 type->tp_dict = dict = PyDict_Copy(dict);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001823 if (dict == NULL) {
1824 Py_DECREF(type);
1825 return NULL;
1826 }
1827
Guido van Rossumc3542212001-08-16 09:18:56 +00001828 /* Set __module__ in the dict */
1829 if (PyDict_GetItemString(dict, "__module__") == NULL) {
1830 tmp = PyEval_GetGlobals();
1831 if (tmp != NULL) {
1832 tmp = PyDict_GetItemString(tmp, "__name__");
1833 if (tmp != NULL) {
1834 if (PyDict_SetItemString(dict, "__module__",
1835 tmp) < 0)
1836 return NULL;
1837 }
1838 }
1839 }
1840
Tim Peters2f93e282001-10-04 05:27:00 +00001841 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
Tim Peters24008312002-03-17 18:56:20 +00001842 and is a string. The __doc__ accessor will first look for tp_doc;
1843 if that fails, it will still look into __dict__.
Tim Peters2f93e282001-10-04 05:27:00 +00001844 */
1845 {
1846 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
1847 if (doc != NULL && PyString_Check(doc)) {
1848 const size_t n = (size_t)PyString_GET_SIZE(doc);
Tim Peters59f809d2001-10-04 05:43:02 +00001849 type->tp_doc = (char *)PyObject_MALLOC(n+1);
Tim Peters2f93e282001-10-04 05:27:00 +00001850 if (type->tp_doc == NULL) {
1851 Py_DECREF(type);
1852 return NULL;
1853 }
1854 memcpy(type->tp_doc, PyString_AS_STRING(doc), n+1);
1855 }
1856 }
1857
Tim Peters6d6c1a32001-08-02 04:15:00 +00001858 /* Special-case __new__: if it's a plain function,
1859 make it a static function */
1860 tmp = PyDict_GetItemString(dict, "__new__");
1861 if (tmp != NULL && PyFunction_Check(tmp)) {
1862 tmp = PyStaticMethod_New(tmp);
1863 if (tmp == NULL) {
1864 Py_DECREF(type);
1865 return NULL;
1866 }
1867 PyDict_SetItemString(dict, "__new__", tmp);
1868 Py_DECREF(tmp);
1869 }
1870
1871 /* Add descriptors for custom slots from __slots__, or for __dict__ */
Guido van Rossume5c691a2003-03-07 15:13:17 +00001872 mp = PyHeapType_GET_MEMBERS(et);
Neil Schemenauerc806c882001-08-29 23:54:54 +00001873 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001874 if (slots != NULL) {
1875 for (i = 0; i < nslots; i++, mp++) {
1876 mp->name = PyString_AS_STRING(
1877 PyTuple_GET_ITEM(slots, i));
Guido van Rossum64b206c2001-12-04 17:13:22 +00001878 mp->type = T_OBJECT_EX;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001879 mp->offset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +00001880 if (base->tp_weaklistoffset == 0 &&
Guido van Rossum64b206c2001-12-04 17:13:22 +00001881 strcmp(mp->name, "__weakref__") == 0) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001882 add_weak++;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001883 mp->type = T_OBJECT;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001884 mp->flags = READONLY;
Guido van Rossum9676b222001-08-17 20:32:36 +00001885 type->tp_weaklistoffset = slotoffset;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001886 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001887 slotoffset += sizeof(PyObject *);
1888 }
1889 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001890 if (add_dict) {
1891 if (base->tp_itemsize)
1892 type->tp_dictoffset = -(long)sizeof(PyObject *);
1893 else
1894 type->tp_dictoffset = slotoffset;
1895 slotoffset += sizeof(PyObject *);
1896 }
1897 if (add_weak) {
1898 assert(!base->tp_itemsize);
1899 type->tp_weaklistoffset = slotoffset;
1900 slotoffset += sizeof(PyObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001901 }
1902 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001903 type->tp_itemsize = base->tp_itemsize;
Guido van Rossume5c691a2003-03-07 15:13:17 +00001904 type->tp_members = PyHeapType_GET_MEMBERS(et);
Guido van Rossum373c7412003-01-07 13:41:37 +00001905
1906 if (type->tp_weaklistoffset && type->tp_dictoffset)
1907 type->tp_getset = subtype_getsets_full;
1908 else if (type->tp_weaklistoffset && !type->tp_dictoffset)
1909 type->tp_getset = subtype_getsets_weakref_only;
1910 else if (!type->tp_weaklistoffset && type->tp_dictoffset)
1911 type->tp_getset = subtype_getsets_dict_only;
1912 else
1913 type->tp_getset = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001914
1915 /* Special case some slots */
1916 if (type->tp_dictoffset != 0 || nslots > 0) {
1917 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
1918 type->tp_getattro = PyObject_GenericGetAttr;
1919 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
1920 type->tp_setattro = PyObject_GenericSetAttr;
1921 }
1922 type->tp_dealloc = subtype_dealloc;
1923
Guido van Rossum9475a232001-10-05 20:51:39 +00001924 /* Enable GC unless there are really no instance variables possible */
1925 if (!(type->tp_basicsize == sizeof(PyObject) &&
1926 type->tp_itemsize == 0))
1927 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
1928
Tim Peters6d6c1a32001-08-02 04:15:00 +00001929 /* Always override allocation strategy to use regular heap */
1930 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00001931 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001932 type->tp_free = PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00001933 type->tp_traverse = subtype_traverse;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001934 type->tp_clear = subtype_clear;
Guido van Rossum048eb752001-10-02 21:24:57 +00001935 }
1936 else
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001937 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001938
1939 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001940 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001941 Py_DECREF(type);
1942 return NULL;
1943 }
1944
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001945 /* Put the proper slots in place */
1946 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00001947
Tim Peters6d6c1a32001-08-02 04:15:00 +00001948 return (PyObject *)type;
1949}
1950
1951/* Internal API to look for a name through the MRO.
1952 This returns a borrowed reference, and doesn't set an exception! */
1953PyObject *
1954_PyType_Lookup(PyTypeObject *type, PyObject *name)
1955{
1956 int i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00001957 PyObject *mro, *res, *base, *dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001958
Guido van Rossum687ae002001-10-15 22:03:32 +00001959 /* Look in tp_dict of types in MRO */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001960 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00001961
1962 /* If mro is NULL, the type is either not yet initialized
1963 by PyType_Ready(), or already cleared by type_clear().
1964 Either way the safest thing to do is to return NULL. */
1965 if (mro == NULL)
1966 return NULL;
1967
Tim Peters6d6c1a32001-08-02 04:15:00 +00001968 assert(PyTuple_Check(mro));
1969 n = PyTuple_GET_SIZE(mro);
1970 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001971 base = PyTuple_GET_ITEM(mro, i);
1972 if (PyClass_Check(base))
1973 dict = ((PyClassObject *)base)->cl_dict;
1974 else {
1975 assert(PyType_Check(base));
1976 dict = ((PyTypeObject *)base)->tp_dict;
1977 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001978 assert(dict && PyDict_Check(dict));
1979 res = PyDict_GetItem(dict, name);
1980 if (res != NULL)
1981 return res;
1982 }
1983 return NULL;
1984}
1985
1986/* This is similar to PyObject_GenericGetAttr(),
1987 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
1988static PyObject *
1989type_getattro(PyTypeObject *type, PyObject *name)
1990{
1991 PyTypeObject *metatype = type->ob_type;
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001992 PyObject *meta_attribute, *attribute;
1993 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001994
1995 /* Initialize this type (we'll assume the metatype is initialized) */
1996 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001997 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001998 return NULL;
1999 }
2000
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002001 /* No readable descriptor found yet */
2002 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00002003
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002004 /* Look for the attribute in the metatype */
2005 meta_attribute = _PyType_Lookup(metatype, name);
2006
2007 if (meta_attribute != NULL) {
2008 meta_get = meta_attribute->ob_type->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00002009
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002010 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
2011 /* Data descriptors implement tp_descr_set to intercept
2012 * writes. Assume the attribute is not overridden in
2013 * type's tp_dict (and bases): call the descriptor now.
2014 */
2015 return meta_get(meta_attribute, (PyObject *)type,
2016 (PyObject *)metatype);
2017 }
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002018 Py_INCREF(meta_attribute);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002019 }
2020
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002021 /* No data descriptor found on metatype. Look in tp_dict of this
2022 * type and its bases */
2023 attribute = _PyType_Lookup(type, name);
2024 if (attribute != NULL) {
2025 /* Implement descriptor functionality, if any */
2026 descrgetfunc local_get = attribute->ob_type->tp_descr_get;
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002027
2028 Py_XDECREF(meta_attribute);
2029
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002030 if (local_get != NULL) {
2031 /* NULL 2nd argument indicates the descriptor was
2032 * found on the target object itself (or a base) */
2033 return local_get(attribute, (PyObject *)NULL,
2034 (PyObject *)type);
2035 }
Tim Peters34592512002-07-11 06:23:50 +00002036
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002037 Py_INCREF(attribute);
2038 return attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002039 }
2040
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002041 /* No attribute found in local __dict__ (or bases): use the
2042 * descriptor from the metatype, if any */
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002043 if (meta_get != NULL) {
2044 PyObject *res;
2045 res = meta_get(meta_attribute, (PyObject *)type,
2046 (PyObject *)metatype);
2047 Py_DECREF(meta_attribute);
2048 return res;
2049 }
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002050
2051 /* If an ordinary attribute was found on the metatype, return it now */
2052 if (meta_attribute != NULL) {
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002053 return meta_attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002054 }
2055
2056 /* Give up */
2057 PyErr_Format(PyExc_AttributeError,
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002058 "type object '%.50s' has no attribute '%.400s'",
2059 type->tp_name, PyString_AS_STRING(name));
Tim Peters6d6c1a32001-08-02 04:15:00 +00002060 return NULL;
2061}
2062
2063static int
2064type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
2065{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002066 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2067 PyErr_Format(
2068 PyExc_TypeError,
2069 "can't set attributes of built-in/extension type '%s'",
2070 type->tp_name);
2071 return -1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002072 }
Guido van Rossum8d24ee92003-03-24 23:49:49 +00002073 /* XXX Example of how I expect this to be used...
2074 if (update_subclasses(type, name, invalidate_cache, NULL) < 0)
2075 return -1;
2076 */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002077 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
2078 return -1;
2079 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002080}
2081
2082static void
2083type_dealloc(PyTypeObject *type)
2084{
Guido van Rossume5c691a2003-03-07 15:13:17 +00002085 PyHeapTypeObject *et;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002086
2087 /* Assert this is a heap-allocated type object */
2088 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002089 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00002090 PyObject_ClearWeakRefs((PyObject *)type);
Guido van Rossume5c691a2003-03-07 15:13:17 +00002091 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002092 Py_XDECREF(type->tp_base);
2093 Py_XDECREF(type->tp_dict);
2094 Py_XDECREF(type->tp_bases);
2095 Py_XDECREF(type->tp_mro);
Guido van Rossum687ae002001-10-15 22:03:32 +00002096 Py_XDECREF(type->tp_cache);
Guido van Rossum1c450732001-10-08 15:18:27 +00002097 Py_XDECREF(type->tp_subclasses);
Neal Norwitzcee5ca02002-07-30 00:42:06 +00002098 PyObject_Free(type->tp_doc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002099 Py_XDECREF(et->name);
2100 Py_XDECREF(et->slots);
2101 type->ob_type->tp_free((PyObject *)type);
2102}
2103
Guido van Rossum1c450732001-10-08 15:18:27 +00002104static PyObject *
2105type_subclasses(PyTypeObject *type, PyObject *args_ignored)
2106{
2107 PyObject *list, *raw, *ref;
2108 int i, n;
2109
2110 list = PyList_New(0);
2111 if (list == NULL)
2112 return NULL;
2113 raw = type->tp_subclasses;
2114 if (raw == NULL)
2115 return list;
2116 assert(PyList_Check(raw));
2117 n = PyList_GET_SIZE(raw);
2118 for (i = 0; i < n; i++) {
2119 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00002120 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00002121 ref = PyWeakref_GET_OBJECT(ref);
2122 if (ref != Py_None) {
2123 if (PyList_Append(list, ref) < 0) {
2124 Py_DECREF(list);
2125 return NULL;
2126 }
2127 }
2128 }
2129 return list;
2130}
2131
Tim Peters6d6c1a32001-08-02 04:15:00 +00002132static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002133 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002134 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
Guido van Rossum1c450732001-10-08 15:18:27 +00002135 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002136 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002137 {0}
2138};
2139
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002140PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002141"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002142"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002143
Guido van Rossum048eb752001-10-02 21:24:57 +00002144static int
2145type_traverse(PyTypeObject *type, visitproc visit, void *arg)
2146{
Guido van Rossum048eb752001-10-02 21:24:57 +00002147 int err;
2148
Guido van Rossuma3862092002-06-10 15:24:42 +00002149 /* Because of type_is_gc(), the collector only calls this
2150 for heaptypes. */
2151 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002152
2153#define VISIT(SLOT) \
2154 if (SLOT) { \
2155 err = visit((PyObject *)(SLOT), arg); \
2156 if (err) \
2157 return err; \
2158 }
2159
2160 VISIT(type->tp_dict);
Guido van Rossum687ae002001-10-15 22:03:32 +00002161 VISIT(type->tp_cache);
Guido van Rossum048eb752001-10-02 21:24:57 +00002162 VISIT(type->tp_mro);
2163 VISIT(type->tp_bases);
2164 VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00002165
2166 /* There's no need to visit type->tp_subclasses or
Guido van Rossume5c691a2003-03-07 15:13:17 +00002167 ((PyHeapTypeObject *)type)->slots, because they can't be involved
Guido van Rossuma3862092002-06-10 15:24:42 +00002168 in cycles; tp_subclasses is a list of weak references,
2169 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00002170
2171#undef VISIT
2172
2173 return 0;
2174}
2175
2176static int
2177type_clear(PyTypeObject *type)
2178{
Guido van Rossum048eb752001-10-02 21:24:57 +00002179 PyObject *tmp;
2180
Guido van Rossuma3862092002-06-10 15:24:42 +00002181 /* Because of type_is_gc(), the collector only calls this
2182 for heaptypes. */
2183 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002184
2185#define CLEAR(SLOT) \
2186 if (SLOT) { \
2187 tmp = (PyObject *)(SLOT); \
2188 SLOT = NULL; \
2189 Py_DECREF(tmp); \
2190 }
2191
Guido van Rossuma3862092002-06-10 15:24:42 +00002192 /* The only field we need to clear is tp_mro, which is part of a
2193 hard cycle (its first element is the class itself) that won't
2194 be broken otherwise (it's a tuple and tuples don't have a
2195 tp_clear handler). None of the other fields need to be
2196 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00002197
Guido van Rossuma3862092002-06-10 15:24:42 +00002198 tp_dict:
2199 It is a dict, so the collector will call its tp_clear.
2200
2201 tp_cache:
2202 Not used; if it were, it would be a dict.
2203
2204 tp_bases, tp_base:
2205 If these are involved in a cycle, there must be at least
2206 one other, mutable object in the cycle, e.g. a base
2207 class's dict; the cycle will be broken that way.
2208
2209 tp_subclasses:
2210 A list of weak references can't be part of a cycle; and
2211 lists have their own tp_clear.
2212
Guido van Rossume5c691a2003-03-07 15:13:17 +00002213 slots (in PyHeapTypeObject):
Guido van Rossuma3862092002-06-10 15:24:42 +00002214 A tuple of strings can't be part of a cycle.
2215 */
2216
2217 CLEAR(type->tp_mro);
Tim Peters2f93e282001-10-04 05:27:00 +00002218
Guido van Rossum048eb752001-10-02 21:24:57 +00002219#undef CLEAR
2220
2221 return 0;
2222}
2223
2224static int
2225type_is_gc(PyTypeObject *type)
2226{
2227 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
2228}
2229
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002230PyTypeObject PyType_Type = {
2231 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002232 0, /* ob_size */
2233 "type", /* tp_name */
Guido van Rossume5c691a2003-03-07 15:13:17 +00002234 sizeof(PyHeapTypeObject), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00002235 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002236 (destructor)type_dealloc, /* tp_dealloc */
2237 0, /* tp_print */
2238 0, /* tp_getattr */
2239 0, /* tp_setattr */
2240 type_compare, /* tp_compare */
2241 (reprfunc)type_repr, /* tp_repr */
2242 0, /* tp_as_number */
2243 0, /* tp_as_sequence */
2244 0, /* tp_as_mapping */
2245 (hashfunc)_Py_HashPointer, /* tp_hash */
2246 (ternaryfunc)type_call, /* tp_call */
2247 0, /* tp_str */
2248 (getattrofunc)type_getattro, /* tp_getattro */
2249 (setattrofunc)type_setattro, /* tp_setattro */
2250 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00002251 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2252 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002253 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00002254 (traverseproc)type_traverse, /* tp_traverse */
2255 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002256 0, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00002257 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002258 0, /* tp_iter */
2259 0, /* tp_iternext */
2260 type_methods, /* tp_methods */
2261 type_members, /* tp_members */
2262 type_getsets, /* tp_getset */
2263 0, /* tp_base */
2264 0, /* tp_dict */
2265 0, /* tp_descr_get */
2266 0, /* tp_descr_set */
2267 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
2268 0, /* tp_init */
2269 0, /* tp_alloc */
2270 type_new, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002271 PyObject_GC_Del, /* tp_free */
Guido van Rossum048eb752001-10-02 21:24:57 +00002272 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002273};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002274
2275
2276/* The base type of all types (eventually)... except itself. */
2277
2278static int
2279object_init(PyObject *self, PyObject *args, PyObject *kwds)
2280{
2281 return 0;
2282}
2283
Guido van Rossum298e4212003-02-13 16:30:16 +00002284/* If we don't have a tp_new for a new-style class, new will use this one.
2285 Therefore this should take no arguments/keywords. However, this new may
2286 also be inherited by objects that define a tp_init but no tp_new. These
2287 objects WILL pass argumets to tp_new, because it gets the same args as
2288 tp_init. So only allow arguments if we aren't using the default init, in
2289 which case we expect init to handle argument parsing. */
2290static PyObject *
2291object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2292{
2293 if (type->tp_init == object_init && (PyTuple_GET_SIZE(args) ||
2294 (kwds && PyDict_Check(kwds) && PyDict_Size(kwds)))) {
2295 PyErr_SetString(PyExc_TypeError,
2296 "default __new__ takes no parameters");
2297 return NULL;
2298 }
2299 return type->tp_alloc(type, 0);
2300}
2301
Tim Peters6d6c1a32001-08-02 04:15:00 +00002302static void
2303object_dealloc(PyObject *self)
2304{
2305 self->ob_type->tp_free(self);
2306}
2307
Guido van Rossum8e248182001-08-12 05:17:56 +00002308static PyObject *
2309object_repr(PyObject *self)
2310{
Guido van Rossum76e69632001-08-16 18:52:43 +00002311 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00002312 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002313
Guido van Rossum76e69632001-08-16 18:52:43 +00002314 type = self->ob_type;
2315 mod = type_module(type, NULL);
2316 if (mod == NULL)
2317 PyErr_Clear();
2318 else if (!PyString_Check(mod)) {
2319 Py_DECREF(mod);
2320 mod = NULL;
2321 }
2322 name = type_name(type, NULL);
2323 if (name == NULL)
2324 return NULL;
2325 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002326 rtn = PyString_FromFormat("<%s.%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002327 PyString_AS_STRING(mod),
2328 PyString_AS_STRING(name),
2329 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002330 else
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002331 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002332 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002333 Py_XDECREF(mod);
2334 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00002335 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002336}
2337
Guido van Rossumb8f63662001-08-15 23:57:02 +00002338static PyObject *
2339object_str(PyObject *self)
2340{
2341 unaryfunc f;
2342
2343 f = self->ob_type->tp_repr;
2344 if (f == NULL)
2345 f = object_repr;
2346 return f(self);
2347}
2348
Guido van Rossum8e248182001-08-12 05:17:56 +00002349static long
2350object_hash(PyObject *self)
2351{
2352 return _Py_HashPointer(self);
2353}
Guido van Rossum8e248182001-08-12 05:17:56 +00002354
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002355static PyObject *
2356object_get_class(PyObject *self, void *closure)
2357{
2358 Py_INCREF(self->ob_type);
2359 return (PyObject *)(self->ob_type);
2360}
2361
2362static int
2363equiv_structs(PyTypeObject *a, PyTypeObject *b)
2364{
2365 return a == b ||
2366 (a != NULL &&
2367 b != NULL &&
2368 a->tp_basicsize == b->tp_basicsize &&
2369 a->tp_itemsize == b->tp_itemsize &&
2370 a->tp_dictoffset == b->tp_dictoffset &&
2371 a->tp_weaklistoffset == b->tp_weaklistoffset &&
2372 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
2373 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
2374}
2375
2376static int
2377same_slots_added(PyTypeObject *a, PyTypeObject *b)
2378{
2379 PyTypeObject *base = a->tp_base;
2380 int size;
2381
2382 if (base != b->tp_base)
2383 return 0;
2384 if (equiv_structs(a, base) && equiv_structs(b, base))
2385 return 1;
2386 size = base->tp_basicsize;
2387 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
2388 size += sizeof(PyObject *);
2389 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
2390 size += sizeof(PyObject *);
2391 return size == a->tp_basicsize && size == b->tp_basicsize;
2392}
2393
2394static int
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002395compatible_for_assignment(PyTypeObject* old, PyTypeObject* new, char* attr)
2396{
2397 PyTypeObject *newbase, *oldbase;
2398
2399 if (new->tp_dealloc != old->tp_dealloc ||
2400 new->tp_free != old->tp_free)
2401 {
2402 PyErr_Format(PyExc_TypeError,
2403 "%s assignment: "
2404 "'%s' deallocator differs from '%s'",
2405 attr,
2406 new->tp_name,
2407 old->tp_name);
2408 return 0;
2409 }
2410 newbase = new;
2411 oldbase = old;
2412 while (equiv_structs(newbase, newbase->tp_base))
2413 newbase = newbase->tp_base;
2414 while (equiv_structs(oldbase, oldbase->tp_base))
2415 oldbase = oldbase->tp_base;
2416 if (newbase != oldbase &&
2417 (newbase->tp_base != oldbase->tp_base ||
2418 !same_slots_added(newbase, oldbase))) {
2419 PyErr_Format(PyExc_TypeError,
2420 "%s assignment: "
2421 "'%s' object layout differs from '%s'",
2422 attr,
2423 new->tp_name,
2424 old->tp_name);
2425 return 0;
2426 }
Tim Petersea7f75d2002-12-07 21:39:16 +00002427
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002428 return 1;
2429}
2430
2431static int
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002432object_set_class(PyObject *self, PyObject *value, void *closure)
2433{
2434 PyTypeObject *old = self->ob_type;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002435 PyTypeObject *new;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002436
Guido van Rossumb6b89422002-04-15 01:03:30 +00002437 if (value == NULL) {
2438 PyErr_SetString(PyExc_TypeError,
2439 "can't delete __class__ attribute");
2440 return -1;
2441 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002442 if (!PyType_Check(value)) {
2443 PyErr_Format(PyExc_TypeError,
2444 "__class__ must be set to new-style class, not '%s' object",
2445 value->ob_type->tp_name);
2446 return -1;
2447 }
2448 new = (PyTypeObject *)value;
Guido van Rossum40af8892002-08-10 05:42:07 +00002449 if (!(new->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
2450 !(old->tp_flags & Py_TPFLAGS_HEAPTYPE))
2451 {
2452 PyErr_Format(PyExc_TypeError,
2453 "__class__ assignment: only for heap types");
2454 return -1;
2455 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002456 if (compatible_for_assignment(new, old, "__class__")) {
2457 Py_INCREF(new);
2458 self->ob_type = new;
2459 Py_DECREF(old);
2460 return 0;
2461 }
2462 else {
Guido van Rossum9ee4b942002-05-24 18:47:47 +00002463 return -1;
2464 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002465}
2466
2467static PyGetSetDef object_getsets[] = {
2468 {"__class__", object_get_class, object_set_class,
Neal Norwitz858e34f2002-08-13 17:18:45 +00002469 PyDoc_STR("the object's class")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002470 {0}
2471};
2472
Guido van Rossumc53f0092003-02-18 22:05:12 +00002473
Guido van Rossum036f9992003-02-21 22:02:54 +00002474/* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
2475 We fall back to helpers in copy_reg for:
2476 - pickle protocols < 2
2477 - calculating the list of slot names (done only once per class)
2478 - the __newobj__ function (which is used as a token but never called)
2479*/
2480
2481static PyObject *
2482import_copy_reg(void)
2483{
2484 static PyObject *copy_reg_str;
Guido van Rossum3926a632001-09-25 16:25:58 +00002485
2486 if (!copy_reg_str) {
2487 copy_reg_str = PyString_InternFromString("copy_reg");
2488 if (copy_reg_str == NULL)
2489 return NULL;
2490 }
Guido van Rossum036f9992003-02-21 22:02:54 +00002491
2492 return PyImport_Import(copy_reg_str);
2493}
2494
2495static PyObject *
2496slotnames(PyObject *cls)
2497{
2498 PyObject *clsdict;
2499 PyObject *copy_reg;
2500 PyObject *slotnames;
2501
2502 if (!PyType_Check(cls)) {
2503 Py_INCREF(Py_None);
2504 return Py_None;
2505 }
2506
2507 clsdict = ((PyTypeObject *)cls)->tp_dict;
2508 slotnames = PyDict_GetItemString(clsdict, "__slotnames__");
2509 if (slotnames != NULL) {
2510 Py_INCREF(slotnames);
2511 return slotnames;
2512 }
2513
2514 copy_reg = import_copy_reg();
2515 if (copy_reg == NULL)
2516 return NULL;
2517
2518 slotnames = PyObject_CallMethod(copy_reg, "_slotnames", "O", cls);
2519 Py_DECREF(copy_reg);
2520 if (slotnames != NULL &&
2521 slotnames != Py_None &&
2522 !PyList_Check(slotnames))
2523 {
2524 PyErr_SetString(PyExc_TypeError,
2525 "copy_reg._slotnames didn't return a list or None");
2526 Py_DECREF(slotnames);
2527 slotnames = NULL;
2528 }
2529
2530 return slotnames;
2531}
2532
2533static PyObject *
2534reduce_2(PyObject *obj)
2535{
2536 PyObject *cls, *getnewargs;
2537 PyObject *args = NULL, *args2 = NULL;
2538 PyObject *getstate = NULL, *state = NULL, *names = NULL;
2539 PyObject *slots = NULL, *listitems = NULL, *dictitems = NULL;
2540 PyObject *copy_reg = NULL, *newobj = NULL, *res = NULL;
2541 int i, n;
2542
2543 cls = PyObject_GetAttrString(obj, "__class__");
2544 if (cls == NULL)
2545 return NULL;
2546
2547 getnewargs = PyObject_GetAttrString(obj, "__getnewargs__");
2548 if (getnewargs != NULL) {
2549 args = PyObject_CallObject(getnewargs, NULL);
2550 Py_DECREF(getnewargs);
2551 if (args != NULL && !PyTuple_Check(args)) {
2552 PyErr_SetString(PyExc_TypeError,
2553 "__getnewargs__ should return a tuple");
2554 goto end;
2555 }
2556 }
2557 else {
2558 PyErr_Clear();
2559 args = PyTuple_New(0);
2560 }
2561 if (args == NULL)
2562 goto end;
2563
2564 getstate = PyObject_GetAttrString(obj, "__getstate__");
2565 if (getstate != NULL) {
2566 state = PyObject_CallObject(getstate, NULL);
2567 Py_DECREF(getstate);
Neal Norwitze2fdc612003-06-08 13:19:58 +00002568 if (state == NULL)
2569 goto end;
Guido van Rossum036f9992003-02-21 22:02:54 +00002570 }
2571 else {
2572 state = PyObject_GetAttrString(obj, "__dict__");
2573 if (state == NULL) {
2574 PyErr_Clear();
2575 state = Py_None;
2576 Py_INCREF(state);
2577 }
2578 names = slotnames(cls);
2579 if (names == NULL)
2580 goto end;
2581 if (names != Py_None) {
2582 assert(PyList_Check(names));
2583 slots = PyDict_New();
2584 if (slots == NULL)
2585 goto end;
2586 n = 0;
2587 /* Can't pre-compute the list size; the list
2588 is stored on the class so accessible to other
2589 threads, which may be run by DECREF */
2590 for (i = 0; i < PyList_GET_SIZE(names); i++) {
2591 PyObject *name, *value;
2592 name = PyList_GET_ITEM(names, i);
2593 value = PyObject_GetAttr(obj, name);
2594 if (value == NULL)
2595 PyErr_Clear();
2596 else {
2597 int err = PyDict_SetItem(slots, name,
2598 value);
2599 Py_DECREF(value);
2600 if (err)
2601 goto end;
2602 n++;
2603 }
2604 }
2605 if (n) {
2606 state = Py_BuildValue("(NO)", state, slots);
2607 if (state == NULL)
2608 goto end;
2609 }
2610 }
2611 }
2612
2613 if (!PyList_Check(obj)) {
2614 listitems = Py_None;
2615 Py_INCREF(listitems);
2616 }
2617 else {
2618 listitems = PyObject_GetIter(obj);
2619 if (listitems == NULL)
2620 goto end;
2621 }
2622
2623 if (!PyDict_Check(obj)) {
2624 dictitems = Py_None;
2625 Py_INCREF(dictitems);
2626 }
2627 else {
2628 dictitems = PyObject_CallMethod(obj, "iteritems", "");
2629 if (dictitems == NULL)
2630 goto end;
2631 }
2632
2633 copy_reg = import_copy_reg();
2634 if (copy_reg == NULL)
2635 goto end;
2636 newobj = PyObject_GetAttrString(copy_reg, "__newobj__");
2637 if (newobj == NULL)
2638 goto end;
2639
2640 n = PyTuple_GET_SIZE(args);
2641 args2 = PyTuple_New(n+1);
2642 if (args2 == NULL)
2643 goto end;
2644 PyTuple_SET_ITEM(args2, 0, cls);
2645 cls = NULL;
2646 for (i = 0; i < n; i++) {
2647 PyObject *v = PyTuple_GET_ITEM(args, i);
2648 Py_INCREF(v);
2649 PyTuple_SET_ITEM(args2, i+1, v);
2650 }
2651
Raymond Hettinger8ae46892003-10-12 19:09:37 +00002652 res = PyTuple_Pack(5, newobj, args2, state, listitems, dictitems);
Guido van Rossum036f9992003-02-21 22:02:54 +00002653
2654 end:
2655 Py_XDECREF(cls);
2656 Py_XDECREF(args);
2657 Py_XDECREF(args2);
Jeremy Hyltond06483c2003-04-09 21:01:42 +00002658 Py_XDECREF(slots);
Guido van Rossum036f9992003-02-21 22:02:54 +00002659 Py_XDECREF(state);
2660 Py_XDECREF(names);
2661 Py_XDECREF(listitems);
2662 Py_XDECREF(dictitems);
2663 Py_XDECREF(copy_reg);
2664 Py_XDECREF(newobj);
2665 return res;
2666}
2667
2668static PyObject *
2669object_reduce_ex(PyObject *self, PyObject *args)
2670{
2671 /* Call copy_reg._reduce_ex(self, proto) */
2672 PyObject *reduce, *copy_reg, *res;
2673 int proto = 0;
2674
2675 if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
2676 return NULL;
2677
2678 reduce = PyObject_GetAttrString(self, "__reduce__");
2679 if (reduce == NULL)
2680 PyErr_Clear();
2681 else {
2682 PyObject *cls, *clsreduce, *objreduce;
2683 int override;
2684 cls = PyObject_GetAttrString(self, "__class__");
2685 if (cls == NULL) {
2686 Py_DECREF(reduce);
2687 return NULL;
2688 }
2689 clsreduce = PyObject_GetAttrString(cls, "__reduce__");
2690 Py_DECREF(cls);
2691 if (clsreduce == NULL) {
2692 Py_DECREF(reduce);
2693 return NULL;
2694 }
2695 objreduce = PyDict_GetItemString(PyBaseObject_Type.tp_dict,
2696 "__reduce__");
2697 override = (clsreduce != objreduce);
2698 Py_DECREF(clsreduce);
2699 if (override) {
2700 res = PyObject_CallObject(reduce, NULL);
2701 Py_DECREF(reduce);
2702 return res;
2703 }
2704 else
2705 Py_DECREF(reduce);
2706 }
2707
2708 if (proto >= 2)
2709 return reduce_2(self);
2710
2711 copy_reg = import_copy_reg();
Guido van Rossum3926a632001-09-25 16:25:58 +00002712 if (!copy_reg)
2713 return NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00002714
Guido van Rossumc53f0092003-02-18 22:05:12 +00002715 res = PyEval_CallMethod(copy_reg, "_reduce_ex", "(Oi)", self, proto);
Guido van Rossum3926a632001-09-25 16:25:58 +00002716 Py_DECREF(copy_reg);
Guido van Rossum036f9992003-02-21 22:02:54 +00002717
Guido van Rossum3926a632001-09-25 16:25:58 +00002718 return res;
2719}
2720
2721static PyMethodDef object_methods[] = {
Guido van Rossumc53f0092003-02-18 22:05:12 +00002722 {"__reduce_ex__", object_reduce_ex, METH_VARARGS,
2723 PyDoc_STR("helper for pickle")},
2724 {"__reduce__", object_reduce_ex, METH_VARARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002725 PyDoc_STR("helper for pickle")},
Guido van Rossum3926a632001-09-25 16:25:58 +00002726 {0}
2727};
2728
Guido van Rossum036f9992003-02-21 22:02:54 +00002729
Tim Peters6d6c1a32001-08-02 04:15:00 +00002730PyTypeObject PyBaseObject_Type = {
2731 PyObject_HEAD_INIT(&PyType_Type)
2732 0, /* ob_size */
2733 "object", /* tp_name */
2734 sizeof(PyObject), /* tp_basicsize */
2735 0, /* tp_itemsize */
2736 (destructor)object_dealloc, /* tp_dealloc */
2737 0, /* tp_print */
2738 0, /* tp_getattr */
2739 0, /* tp_setattr */
2740 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002741 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002742 0, /* tp_as_number */
2743 0, /* tp_as_sequence */
2744 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002745 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002746 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002747 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002748 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002749 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002750 0, /* tp_as_buffer */
2751 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002752 PyDoc_STR("The most base type"), /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002753 0, /* tp_traverse */
2754 0, /* tp_clear */
2755 0, /* tp_richcompare */
2756 0, /* tp_weaklistoffset */
2757 0, /* tp_iter */
2758 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00002759 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002760 0, /* tp_members */
2761 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002762 0, /* tp_base */
2763 0, /* tp_dict */
2764 0, /* tp_descr_get */
2765 0, /* tp_descr_set */
2766 0, /* tp_dictoffset */
2767 object_init, /* tp_init */
2768 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossum298e4212003-02-13 16:30:16 +00002769 object_new, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002770 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002771};
2772
2773
2774/* Initialize the __dict__ in a type object */
2775
2776static int
2777add_methods(PyTypeObject *type, PyMethodDef *meth)
2778{
Guido van Rossum687ae002001-10-15 22:03:32 +00002779 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002780
2781 for (; meth->ml_name != NULL; meth++) {
2782 PyObject *descr;
2783 if (PyDict_GetItemString(dict, meth->ml_name))
2784 continue;
Fred Drake7bf97152002-03-28 05:33:33 +00002785 if (meth->ml_flags & METH_CLASS) {
2786 if (meth->ml_flags & METH_STATIC) {
2787 PyErr_SetString(PyExc_ValueError,
2788 "method cannot be both class and static");
2789 return -1;
2790 }
Tim Petersbca1cbc2002-12-09 22:56:13 +00002791 descr = PyDescr_NewClassMethod(type, meth);
Fred Drake7bf97152002-03-28 05:33:33 +00002792 }
2793 else if (meth->ml_flags & METH_STATIC) {
Guido van Rossum9af48ff2003-02-11 17:12:46 +00002794 PyObject *cfunc = PyCFunction_New(meth, NULL);
2795 if (cfunc == NULL)
2796 return -1;
2797 descr = PyStaticMethod_New(cfunc);
2798 Py_DECREF(cfunc);
Fred Drake7bf97152002-03-28 05:33:33 +00002799 }
2800 else {
2801 descr = PyDescr_NewMethod(type, meth);
2802 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002803 if (descr == NULL)
2804 return -1;
Fred Drake7bf97152002-03-28 05:33:33 +00002805 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002806 return -1;
2807 Py_DECREF(descr);
2808 }
2809 return 0;
2810}
2811
2812static int
Guido van Rossum6f799372001-09-20 20:46:19 +00002813add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002814{
Guido van Rossum687ae002001-10-15 22:03:32 +00002815 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002816
2817 for (; memb->name != NULL; memb++) {
2818 PyObject *descr;
2819 if (PyDict_GetItemString(dict, memb->name))
2820 continue;
2821 descr = PyDescr_NewMember(type, memb);
2822 if (descr == NULL)
2823 return -1;
2824 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
2825 return -1;
2826 Py_DECREF(descr);
2827 }
2828 return 0;
2829}
2830
2831static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00002832add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002833{
Guido van Rossum687ae002001-10-15 22:03:32 +00002834 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002835
2836 for (; gsp->name != NULL; gsp++) {
2837 PyObject *descr;
2838 if (PyDict_GetItemString(dict, gsp->name))
2839 continue;
2840 descr = PyDescr_NewGetSet(type, gsp);
2841
2842 if (descr == NULL)
2843 return -1;
2844 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
2845 return -1;
2846 Py_DECREF(descr);
2847 }
2848 return 0;
2849}
2850
Guido van Rossum13d52f02001-08-10 21:24:08 +00002851static void
2852inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002853{
2854 int oldsize, newsize;
2855
Guido van Rossum13d52f02001-08-10 21:24:08 +00002856 /* Special flag magic */
2857 if (!type->tp_as_buffer && base->tp_as_buffer) {
2858 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
2859 type->tp_flags |=
2860 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
2861 }
2862 if (!type->tp_as_sequence && base->tp_as_sequence) {
2863 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
2864 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
2865 }
2866 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
2867 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
2868 if ((!type->tp_as_number && base->tp_as_number) ||
2869 (!type->tp_as_sequence && base->tp_as_sequence)) {
2870 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
2871 if (!type->tp_as_number && !type->tp_as_sequence) {
2872 type->tp_flags |= base->tp_flags &
2873 Py_TPFLAGS_HAVE_INPLACEOPS;
2874 }
2875 }
2876 /* Wow */
2877 }
2878 if (!type->tp_as_number && base->tp_as_number) {
2879 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
2880 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
2881 }
2882
2883 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00002884 oldsize = base->tp_basicsize;
2885 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
2886 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
2887 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00002888 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
2889 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00002890 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00002891 if (type->tp_traverse == NULL)
2892 type->tp_traverse = base->tp_traverse;
2893 if (type->tp_clear == NULL)
2894 type->tp_clear = base->tp_clear;
2895 }
2896 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
Guido van Rossumf884b742001-12-17 17:14:22 +00002897 /* The condition below could use some explanation.
2898 It appears that tp_new is not inherited for static types
2899 whose base class is 'object'; this seems to be a precaution
2900 so that old extension types don't suddenly become
2901 callable (object.__new__ wouldn't insure the invariants
2902 that the extension type's own factory function ensures).
2903 Heap types, of course, are under our control, so they do
2904 inherit tp_new; static extension types that specify some
2905 other built-in type as the default are considered
2906 new-style-aware so they also inherit object.__new__. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002907 if (base != &PyBaseObject_Type ||
2908 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2909 if (type->tp_new == NULL)
2910 type->tp_new = base->tp_new;
2911 }
2912 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00002913 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00002914
2915 /* Copy other non-function slots */
2916
2917#undef COPYVAL
2918#define COPYVAL(SLOT) \
2919 if (type->SLOT == 0) type->SLOT = base->SLOT
2920
2921 COPYVAL(tp_itemsize);
2922 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
2923 COPYVAL(tp_weaklistoffset);
2924 }
2925 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2926 COPYVAL(tp_dictoffset);
2927 }
Guido van Rossum13d52f02001-08-10 21:24:08 +00002928}
2929
2930static void
2931inherit_slots(PyTypeObject *type, PyTypeObject *base)
2932{
2933 PyTypeObject *basebase;
2934
2935#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00002936#undef COPYSLOT
2937#undef COPYNUM
2938#undef COPYSEQ
2939#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00002940#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00002941
2942#define SLOTDEFINED(SLOT) \
2943 (base->SLOT != 0 && \
2944 (basebase == NULL || base->SLOT != basebase->SLOT))
2945
Tim Peters6d6c1a32001-08-02 04:15:00 +00002946#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00002947 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00002948
2949#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
2950#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
2951#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00002952#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002953
Guido van Rossum13d52f02001-08-10 21:24:08 +00002954 /* This won't inherit indirect slots (from tp_as_number etc.)
2955 if type doesn't provide the space. */
2956
2957 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
2958 basebase = base->tp_base;
2959 if (basebase->tp_as_number == NULL)
2960 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002961 COPYNUM(nb_add);
2962 COPYNUM(nb_subtract);
2963 COPYNUM(nb_multiply);
2964 COPYNUM(nb_divide);
2965 COPYNUM(nb_remainder);
2966 COPYNUM(nb_divmod);
2967 COPYNUM(nb_power);
2968 COPYNUM(nb_negative);
2969 COPYNUM(nb_positive);
2970 COPYNUM(nb_absolute);
2971 COPYNUM(nb_nonzero);
2972 COPYNUM(nb_invert);
2973 COPYNUM(nb_lshift);
2974 COPYNUM(nb_rshift);
2975 COPYNUM(nb_and);
2976 COPYNUM(nb_xor);
2977 COPYNUM(nb_or);
2978 COPYNUM(nb_coerce);
2979 COPYNUM(nb_int);
2980 COPYNUM(nb_long);
2981 COPYNUM(nb_float);
2982 COPYNUM(nb_oct);
2983 COPYNUM(nb_hex);
2984 COPYNUM(nb_inplace_add);
2985 COPYNUM(nb_inplace_subtract);
2986 COPYNUM(nb_inplace_multiply);
2987 COPYNUM(nb_inplace_divide);
2988 COPYNUM(nb_inplace_remainder);
2989 COPYNUM(nb_inplace_power);
2990 COPYNUM(nb_inplace_lshift);
2991 COPYNUM(nb_inplace_rshift);
2992 COPYNUM(nb_inplace_and);
2993 COPYNUM(nb_inplace_xor);
2994 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00002995 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
2996 COPYNUM(nb_true_divide);
2997 COPYNUM(nb_floor_divide);
2998 COPYNUM(nb_inplace_true_divide);
2999 COPYNUM(nb_inplace_floor_divide);
3000 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003001 }
3002
Guido van Rossum13d52f02001-08-10 21:24:08 +00003003 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
3004 basebase = base->tp_base;
3005 if (basebase->tp_as_sequence == NULL)
3006 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003007 COPYSEQ(sq_length);
3008 COPYSEQ(sq_concat);
3009 COPYSEQ(sq_repeat);
3010 COPYSEQ(sq_item);
3011 COPYSEQ(sq_slice);
3012 COPYSEQ(sq_ass_item);
3013 COPYSEQ(sq_ass_slice);
3014 COPYSEQ(sq_contains);
3015 COPYSEQ(sq_inplace_concat);
3016 COPYSEQ(sq_inplace_repeat);
3017 }
3018
Guido van Rossum13d52f02001-08-10 21:24:08 +00003019 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
3020 basebase = base->tp_base;
3021 if (basebase->tp_as_mapping == NULL)
3022 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003023 COPYMAP(mp_length);
3024 COPYMAP(mp_subscript);
3025 COPYMAP(mp_ass_subscript);
3026 }
3027
Tim Petersfc57ccb2001-10-12 02:38:24 +00003028 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
3029 basebase = base->tp_base;
3030 if (basebase->tp_as_buffer == NULL)
3031 basebase = NULL;
3032 COPYBUF(bf_getreadbuffer);
3033 COPYBUF(bf_getwritebuffer);
3034 COPYBUF(bf_getsegcount);
3035 COPYBUF(bf_getcharbuffer);
3036 }
3037
Guido van Rossum13d52f02001-08-10 21:24:08 +00003038 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003039
Tim Peters6d6c1a32001-08-02 04:15:00 +00003040 COPYSLOT(tp_dealloc);
3041 COPYSLOT(tp_print);
3042 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
3043 type->tp_getattr = base->tp_getattr;
3044 type->tp_getattro = base->tp_getattro;
3045 }
3046 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
3047 type->tp_setattr = base->tp_setattr;
3048 type->tp_setattro = base->tp_setattro;
3049 }
3050 /* tp_compare see tp_richcompare */
3051 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003052 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003053 COPYSLOT(tp_call);
3054 COPYSLOT(tp_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003055 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003056 if (type->tp_compare == NULL &&
3057 type->tp_richcompare == NULL &&
3058 type->tp_hash == NULL)
3059 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003060 type->tp_compare = base->tp_compare;
3061 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003062 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003063 }
3064 }
3065 else {
3066 COPYSLOT(tp_compare);
3067 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003068 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
3069 COPYSLOT(tp_iter);
3070 COPYSLOT(tp_iternext);
3071 }
3072 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
3073 COPYSLOT(tp_descr_get);
3074 COPYSLOT(tp_descr_set);
3075 COPYSLOT(tp_dictoffset);
3076 COPYSLOT(tp_init);
3077 COPYSLOT(tp_alloc);
Guido van Rossumcc8fe042002-04-05 17:10:16 +00003078 COPYSLOT(tp_is_gc);
Tim Peters3cfe7542003-05-21 21:29:48 +00003079 if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) ==
3080 (base->tp_flags & Py_TPFLAGS_HAVE_GC)) {
3081 /* They agree about gc. */
3082 COPYSLOT(tp_free);
3083 }
3084 else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3085 type->tp_free == NULL &&
3086 base->tp_free == _PyObject_Del) {
3087 /* A bit of magic to plug in the correct default
3088 * tp_free function when a derived class adds gc,
3089 * didn't define tp_free, and the base uses the
3090 * default non-gc tp_free.
3091 */
3092 type->tp_free = PyObject_GC_Del;
3093 }
3094 /* else they didn't agree about gc, and there isn't something
3095 * obvious to be done -- the type is on its own.
3096 */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003097 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003098}
3099
Jeremy Hylton938ace62002-07-17 16:30:39 +00003100static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00003101
Tim Peters6d6c1a32001-08-02 04:15:00 +00003102int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00003103PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003104{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003105 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003106 PyTypeObject *base;
3107 int i, n;
3108
Guido van Rossumcab05802002-06-10 15:29:03 +00003109 if (type->tp_flags & Py_TPFLAGS_READY) {
3110 assert(type->tp_dict != NULL);
Guido van Rossumd614f972001-08-10 17:39:49 +00003111 return 0;
Guido van Rossumcab05802002-06-10 15:29:03 +00003112 }
Guido van Rossumd614f972001-08-10 17:39:49 +00003113 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00003114
3115 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003116
Tim Peters36eb4df2003-03-23 03:33:13 +00003117#ifdef Py_TRACE_REFS
3118 /* PyType_Ready is the closest thing we have to a choke point
3119 * for type objects, so is the best place I can think of to try
3120 * to get type objects into the doubly-linked list of all objects.
3121 * Still, not all type objects go thru PyType_Ready.
3122 */
Tim Peters7571a0f2003-03-23 17:52:28 +00003123 _Py_AddToAllObjects((PyObject *)type, 0);
Tim Peters36eb4df2003-03-23 03:33:13 +00003124#endif
3125
Tim Peters6d6c1a32001-08-02 04:15:00 +00003126 /* Initialize tp_base (defaults to BaseObject unless that's us) */
3127 base = type->tp_base;
3128 if (base == NULL && type != &PyBaseObject_Type)
3129 base = type->tp_base = &PyBaseObject_Type;
3130
Guido van Rossum323a9cf2002-08-14 17:26:30 +00003131 /* Initialize the base class */
3132 if (base && base->tp_dict == NULL) {
3133 if (PyType_Ready(base) < 0)
3134 goto error;
3135 }
3136
Guido van Rossum0986d822002-04-08 01:38:42 +00003137 /* Initialize ob_type if NULL. This means extensions that want to be
3138 compilable separately on Windows can call PyType_Ready() instead of
3139 initializing the ob_type field of their type objects. */
3140 if (type->ob_type == NULL)
3141 type->ob_type = base->ob_type;
3142
Tim Peters6d6c1a32001-08-02 04:15:00 +00003143 /* Initialize tp_bases */
3144 bases = type->tp_bases;
3145 if (bases == NULL) {
3146 if (base == NULL)
3147 bases = PyTuple_New(0);
3148 else
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003149 bases = PyTuple_Pack(1, base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003150 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003151 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003152 type->tp_bases = bases;
3153 }
3154
Guido van Rossum687ae002001-10-15 22:03:32 +00003155 /* Initialize tp_dict */
3156 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003157 if (dict == NULL) {
3158 dict = PyDict_New();
3159 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003160 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00003161 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003162 }
3163
Guido van Rossum687ae002001-10-15 22:03:32 +00003164 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003165 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003166 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003167 if (type->tp_methods != NULL) {
3168 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003169 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003170 }
3171 if (type->tp_members != NULL) {
3172 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003173 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003174 }
3175 if (type->tp_getset != NULL) {
3176 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003177 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003178 }
3179
Tim Peters6d6c1a32001-08-02 04:15:00 +00003180 /* Calculate method resolution order */
3181 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00003182 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003183 }
3184
Guido van Rossum13d52f02001-08-10 21:24:08 +00003185 /* Inherit special flags from dominant base */
3186 if (type->tp_base != NULL)
3187 inherit_special(type, type->tp_base);
3188
Tim Peters6d6c1a32001-08-02 04:15:00 +00003189 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003190 bases = type->tp_mro;
3191 assert(bases != NULL);
3192 assert(PyTuple_Check(bases));
3193 n = PyTuple_GET_SIZE(bases);
3194 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003195 PyObject *b = PyTuple_GET_ITEM(bases, i);
3196 if (PyType_Check(b))
3197 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003198 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003199
Tim Peters3cfe7542003-05-21 21:29:48 +00003200 /* Sanity check for tp_free. */
3201 if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) &&
3202 (type->tp_free == NULL || type->tp_free == PyObject_Del)) {
3203 /* This base class needs to call tp_free, but doesn't have
3204 * one, or its tp_free is for non-gc'ed objects.
3205 */
3206 PyErr_Format(PyExc_TypeError, "type '%.100s' participates in "
3207 "gc and is a base type but has inappropriate "
3208 "tp_free slot",
3209 type->tp_name);
3210 goto error;
3211 }
3212
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003213 /* if the type dictionary doesn't contain a __doc__, set it from
3214 the tp_doc slot.
3215 */
3216 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
3217 if (type->tp_doc != NULL) {
3218 PyObject *doc = PyString_FromString(type->tp_doc);
3219 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
3220 Py_DECREF(doc);
3221 } else {
Guido van Rossumd4641072002-04-03 02:13:37 +00003222 PyDict_SetItemString(type->tp_dict,
3223 "__doc__", Py_None);
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003224 }
3225 }
3226
Guido van Rossum13d52f02001-08-10 21:24:08 +00003227 /* Some more special stuff */
3228 base = type->tp_base;
3229 if (base != NULL) {
3230 if (type->tp_as_number == NULL)
3231 type->tp_as_number = base->tp_as_number;
3232 if (type->tp_as_sequence == NULL)
3233 type->tp_as_sequence = base->tp_as_sequence;
3234 if (type->tp_as_mapping == NULL)
3235 type->tp_as_mapping = base->tp_as_mapping;
Guido van Rossumeea47182003-02-11 20:39:59 +00003236 if (type->tp_as_buffer == NULL)
3237 type->tp_as_buffer = base->tp_as_buffer;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003238 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003239
Guido van Rossum1c450732001-10-08 15:18:27 +00003240 /* Link into each base class's list of subclasses */
3241 bases = type->tp_bases;
3242 n = PyTuple_GET_SIZE(bases);
3243 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003244 PyObject *b = PyTuple_GET_ITEM(bases, i);
3245 if (PyType_Check(b) &&
3246 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00003247 goto error;
3248 }
3249
Guido van Rossum13d52f02001-08-10 21:24:08 +00003250 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00003251 assert(type->tp_dict != NULL);
3252 type->tp_flags =
3253 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003254 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00003255
3256 error:
3257 type->tp_flags &= ~Py_TPFLAGS_READYING;
3258 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003259}
3260
Guido van Rossum1c450732001-10-08 15:18:27 +00003261static int
3262add_subclass(PyTypeObject *base, PyTypeObject *type)
3263{
3264 int i;
3265 PyObject *list, *ref, *new;
3266
3267 list = base->tp_subclasses;
3268 if (list == NULL) {
3269 base->tp_subclasses = list = PyList_New(0);
3270 if (list == NULL)
3271 return -1;
3272 }
3273 assert(PyList_Check(list));
3274 new = PyWeakref_NewRef((PyObject *)type, NULL);
3275 i = PyList_GET_SIZE(list);
3276 while (--i >= 0) {
3277 ref = PyList_GET_ITEM(list, i);
3278 assert(PyWeakref_CheckRef(ref));
Guido van Rossum3930bc32002-10-18 13:51:49 +00003279 if (PyWeakref_GET_OBJECT(ref) == Py_None)
3280 return PyList_SetItem(list, i, new);
Guido van Rossum1c450732001-10-08 15:18:27 +00003281 }
3282 i = PyList_Append(list, new);
3283 Py_DECREF(new);
3284 return i;
3285}
3286
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003287static void
3288remove_subclass(PyTypeObject *base, PyTypeObject *type)
3289{
3290 int i;
3291 PyObject *list, *ref;
3292
3293 list = base->tp_subclasses;
3294 if (list == NULL) {
3295 return;
3296 }
3297 assert(PyList_Check(list));
3298 i = PyList_GET_SIZE(list);
3299 while (--i >= 0) {
3300 ref = PyList_GET_ITEM(list, i);
3301 assert(PyWeakref_CheckRef(ref));
3302 if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
3303 /* this can't fail, right? */
3304 PySequence_DelItem(list, i);
3305 return;
3306 }
3307 }
3308}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003309
3310/* Generic wrappers for overloadable 'operators' such as __getitem__ */
3311
3312/* There's a wrapper *function* for each distinct function typedef used
3313 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
3314 wrapper *table* for each distinct operation (e.g. __len__, __add__).
3315 Most tables have only one entry; the tables for binary operators have two
3316 entries, one regular and one with reversed arguments. */
3317
3318static PyObject *
3319wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
3320{
3321 inquiry func = (inquiry)wrapped;
3322 int res;
3323
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003324 if (!PyArg_UnpackTuple(args, "", 0, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003325 return NULL;
3326 res = (*func)(self);
3327 if (res == -1 && PyErr_Occurred())
3328 return NULL;
3329 return PyInt_FromLong((long)res);
3330}
3331
Tim Peters6d6c1a32001-08-02 04:15:00 +00003332static PyObject *
Raymond Hettingerf34f2642003-10-11 17:29:04 +00003333wrap_inquirypred(PyObject *self, PyObject *args, void *wrapped)
3334{
3335 inquiry func = (inquiry)wrapped;
3336 int res;
3337
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003338 if (!PyArg_UnpackTuple(args, "", 0, 0))
Raymond Hettingerf34f2642003-10-11 17:29:04 +00003339 return NULL;
3340 res = (*func)(self);
3341 if (res == -1 && PyErr_Occurred())
3342 return NULL;
3343 return PyBool_FromLong((long)res);
3344}
3345
3346static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003347wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
3348{
3349 binaryfunc func = (binaryfunc)wrapped;
3350 PyObject *other;
3351
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003352 if (!PyArg_UnpackTuple(args, "", 1, 1, &other))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003353 return NULL;
3354 return (*func)(self, other);
3355}
3356
3357static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003358wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
3359{
3360 binaryfunc func = (binaryfunc)wrapped;
3361 PyObject *other;
3362
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003363 if (!PyArg_UnpackTuple(args, "", 1, 1, &other))
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003364 return NULL;
3365 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003366 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003367 Py_INCREF(Py_NotImplemented);
3368 return Py_NotImplemented;
3369 }
3370 return (*func)(self, other);
3371}
3372
3373static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003374wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3375{
3376 binaryfunc func = (binaryfunc)wrapped;
3377 PyObject *other;
3378
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003379 if (!PyArg_UnpackTuple(args, "", 1, 1, &other))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003380 return NULL;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003381 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003382 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003383 Py_INCREF(Py_NotImplemented);
3384 return Py_NotImplemented;
3385 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003386 return (*func)(other, self);
3387}
3388
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003389static PyObject *
3390wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
3391{
3392 coercion func = (coercion)wrapped;
3393 PyObject *other, *res;
3394 int ok;
3395
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003396 if (!PyArg_UnpackTuple(args, "", 1, 1, &other))
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003397 return NULL;
3398 ok = func(&self, &other);
3399 if (ok < 0)
3400 return NULL;
3401 if (ok > 0) {
3402 Py_INCREF(Py_NotImplemented);
3403 return Py_NotImplemented;
3404 }
3405 res = PyTuple_New(2);
3406 if (res == NULL) {
3407 Py_DECREF(self);
3408 Py_DECREF(other);
3409 return NULL;
3410 }
3411 PyTuple_SET_ITEM(res, 0, self);
3412 PyTuple_SET_ITEM(res, 1, other);
3413 return res;
3414}
3415
Tim Peters6d6c1a32001-08-02 04:15:00 +00003416static PyObject *
3417wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
3418{
3419 ternaryfunc func = (ternaryfunc)wrapped;
3420 PyObject *other;
3421 PyObject *third = Py_None;
3422
3423 /* Note: This wrapper only works for __pow__() */
3424
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003425 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003426 return NULL;
3427 return (*func)(self, other, third);
3428}
3429
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00003430static PyObject *
3431wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3432{
3433 ternaryfunc func = (ternaryfunc)wrapped;
3434 PyObject *other;
3435 PyObject *third = Py_None;
3436
3437 /* Note: This wrapper only works for __pow__() */
3438
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003439 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00003440 return NULL;
3441 return (*func)(other, self, third);
3442}
3443
Tim Peters6d6c1a32001-08-02 04:15:00 +00003444static PyObject *
3445wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
3446{
3447 unaryfunc func = (unaryfunc)wrapped;
3448
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003449 if (!PyArg_UnpackTuple(args, "", 0, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003450 return NULL;
3451 return (*func)(self);
3452}
3453
Tim Peters6d6c1a32001-08-02 04:15:00 +00003454static PyObject *
3455wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
3456{
3457 intargfunc func = (intargfunc)wrapped;
3458 int i;
3459
3460 if (!PyArg_ParseTuple(args, "i", &i))
3461 return NULL;
3462 return (*func)(self, i);
3463}
3464
Guido van Rossum5d815f32001-08-17 21:57:47 +00003465static int
3466getindex(PyObject *self, PyObject *arg)
3467{
3468 int i;
3469
3470 i = PyInt_AsLong(arg);
3471 if (i == -1 && PyErr_Occurred())
3472 return -1;
3473 if (i < 0) {
3474 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
3475 if (sq && sq->sq_length) {
3476 int n = (*sq->sq_length)(self);
3477 if (n < 0)
3478 return -1;
3479 i += n;
3480 }
3481 }
3482 return i;
3483}
3484
3485static PyObject *
3486wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
3487{
3488 intargfunc func = (intargfunc)wrapped;
3489 PyObject *arg;
3490 int i;
3491
Guido van Rossumf4593e02001-10-03 12:09:30 +00003492 if (PyTuple_GET_SIZE(args) == 1) {
3493 arg = PyTuple_GET_ITEM(args, 0);
3494 i = getindex(self, arg);
3495 if (i == -1 && PyErr_Occurred())
3496 return NULL;
3497 return (*func)(self, i);
3498 }
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003499 PyArg_UnpackTuple(args, "", 1, 1, &arg);
Guido van Rossumf4593e02001-10-03 12:09:30 +00003500 assert(PyErr_Occurred());
3501 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003502}
3503
Tim Peters6d6c1a32001-08-02 04:15:00 +00003504static PyObject *
3505wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
3506{
3507 intintargfunc func = (intintargfunc)wrapped;
3508 int i, j;
3509
3510 if (!PyArg_ParseTuple(args, "ii", &i, &j))
3511 return NULL;
3512 return (*func)(self, i, j);
3513}
3514
Tim Peters6d6c1a32001-08-02 04:15:00 +00003515static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003516wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003517{
3518 intobjargproc func = (intobjargproc)wrapped;
3519 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003520 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003521
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003522 if (!PyArg_UnpackTuple(args, "", 2, 2, &arg, &value))
Guido van Rossum5d815f32001-08-17 21:57:47 +00003523 return NULL;
3524 i = getindex(self, arg);
3525 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00003526 return NULL;
3527 res = (*func)(self, i, value);
3528 if (res == -1 && PyErr_Occurred())
3529 return NULL;
3530 Py_INCREF(Py_None);
3531 return Py_None;
3532}
3533
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003534static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003535wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003536{
3537 intobjargproc func = (intobjargproc)wrapped;
3538 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003539 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003540
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003541 if (!PyArg_UnpackTuple(args, "", 1, 1, &arg))
Guido van Rossum5d815f32001-08-17 21:57:47 +00003542 return NULL;
3543 i = getindex(self, arg);
3544 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003545 return NULL;
3546 res = (*func)(self, i, NULL);
3547 if (res == -1 && PyErr_Occurred())
3548 return NULL;
3549 Py_INCREF(Py_None);
3550 return Py_None;
3551}
3552
Tim Peters6d6c1a32001-08-02 04:15:00 +00003553static PyObject *
3554wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
3555{
3556 intintobjargproc func = (intintobjargproc)wrapped;
3557 int i, j, res;
3558 PyObject *value;
3559
3560 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
3561 return NULL;
3562 res = (*func)(self, i, j, value);
3563 if (res == -1 && PyErr_Occurred())
3564 return NULL;
3565 Py_INCREF(Py_None);
3566 return Py_None;
3567}
3568
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003569static PyObject *
3570wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
3571{
3572 intintobjargproc func = (intintobjargproc)wrapped;
3573 int i, j, res;
3574
3575 if (!PyArg_ParseTuple(args, "ii", &i, &j))
3576 return NULL;
3577 res = (*func)(self, i, j, NULL);
3578 if (res == -1 && PyErr_Occurred())
3579 return NULL;
3580 Py_INCREF(Py_None);
3581 return Py_None;
3582}
3583
Tim Peters6d6c1a32001-08-02 04:15:00 +00003584/* XXX objobjproc is a misnomer; should be objargpred */
3585static PyObject *
3586wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
3587{
3588 objobjproc func = (objobjproc)wrapped;
3589 int res;
Guido van Rossum22c3dda2003-10-09 03:46:35 +00003590 PyObject *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003591
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003592 if (!PyArg_UnpackTuple(args, "", 1, 1, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003593 return NULL;
3594 res = (*func)(self, value);
3595 if (res == -1 && PyErr_Occurred())
3596 return NULL;
Guido van Rossum22c3dda2003-10-09 03:46:35 +00003597 else
3598 return PyBool_FromLong(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003599}
3600
Tim Peters6d6c1a32001-08-02 04:15:00 +00003601static PyObject *
3602wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
3603{
3604 objobjargproc func = (objobjargproc)wrapped;
3605 int res;
3606 PyObject *key, *value;
3607
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003608 if (!PyArg_UnpackTuple(args, "", 2, 2, &key, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003609 return NULL;
3610 res = (*func)(self, key, value);
3611 if (res == -1 && PyErr_Occurred())
3612 return NULL;
3613 Py_INCREF(Py_None);
3614 return Py_None;
3615}
3616
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003617static PyObject *
3618wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
3619{
3620 objobjargproc func = (objobjargproc)wrapped;
3621 int res;
3622 PyObject *key;
3623
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003624 if (!PyArg_UnpackTuple(args, "", 1, 1, &key))
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003625 return NULL;
3626 res = (*func)(self, key, NULL);
3627 if (res == -1 && PyErr_Occurred())
3628 return NULL;
3629 Py_INCREF(Py_None);
3630 return Py_None;
3631}
3632
Tim Peters6d6c1a32001-08-02 04:15:00 +00003633static PyObject *
3634wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
3635{
3636 cmpfunc func = (cmpfunc)wrapped;
3637 int res;
3638 PyObject *other;
3639
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003640 if (!PyArg_UnpackTuple(args, "", 1, 1, &other))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003641 return NULL;
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00003642 if (other->ob_type->tp_compare != func &&
3643 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00003644 PyErr_Format(
3645 PyExc_TypeError,
3646 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
3647 self->ob_type->tp_name,
3648 self->ob_type->tp_name,
3649 other->ob_type->tp_name);
3650 return NULL;
3651 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003652 res = (*func)(self, other);
3653 if (PyErr_Occurred())
3654 return NULL;
3655 return PyInt_FromLong((long)res);
3656}
3657
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003658/* Helper to check for object.__setattr__ or __delattr__ applied to a type.
Guido van Rossum52b27052003-04-15 20:05:10 +00003659 This is called the Carlo Verre hack after its discoverer. */
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003660static int
3661hackcheck(PyObject *self, setattrofunc func, char *what)
3662{
3663 PyTypeObject *type = self->ob_type;
3664 while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE)
3665 type = type->tp_base;
3666 if (type->tp_setattro != func) {
3667 PyErr_Format(PyExc_TypeError,
3668 "can't apply this %s to %s object",
3669 what,
3670 type->tp_name);
3671 return 0;
3672 }
3673 return 1;
3674}
3675
Tim Peters6d6c1a32001-08-02 04:15:00 +00003676static PyObject *
3677wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
3678{
3679 setattrofunc func = (setattrofunc)wrapped;
3680 int res;
3681 PyObject *name, *value;
3682
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003683 if (!PyArg_UnpackTuple(args, "", 2, 2, &name, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003684 return NULL;
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003685 if (!hackcheck(self, func, "__setattr__"))
3686 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003687 res = (*func)(self, name, value);
3688 if (res < 0)
3689 return NULL;
3690 Py_INCREF(Py_None);
3691 return Py_None;
3692}
3693
3694static PyObject *
3695wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
3696{
3697 setattrofunc func = (setattrofunc)wrapped;
3698 int res;
3699 PyObject *name;
3700
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003701 if (!PyArg_UnpackTuple(args, "", 1, 1, &name))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003702 return NULL;
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003703 if (!hackcheck(self, func, "__delattr__"))
3704 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003705 res = (*func)(self, name, NULL);
3706 if (res < 0)
3707 return NULL;
3708 Py_INCREF(Py_None);
3709 return Py_None;
3710}
3711
Tim Peters6d6c1a32001-08-02 04:15:00 +00003712static PyObject *
3713wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
3714{
3715 hashfunc func = (hashfunc)wrapped;
3716 long res;
3717
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003718 if (!PyArg_UnpackTuple(args, "", 0, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003719 return NULL;
3720 res = (*func)(self);
3721 if (res == -1 && PyErr_Occurred())
3722 return NULL;
3723 return PyInt_FromLong(res);
3724}
3725
Tim Peters6d6c1a32001-08-02 04:15:00 +00003726static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00003727wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003728{
3729 ternaryfunc func = (ternaryfunc)wrapped;
3730
Guido van Rossumc8e56452001-10-22 00:43:43 +00003731 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003732}
3733
Tim Peters6d6c1a32001-08-02 04:15:00 +00003734static PyObject *
3735wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
3736{
3737 richcmpfunc func = (richcmpfunc)wrapped;
3738 PyObject *other;
3739
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003740 if (!PyArg_UnpackTuple(args, "", 1, 1, &other))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003741 return NULL;
3742 return (*func)(self, other, op);
3743}
3744
3745#undef RICHCMP_WRAPPER
3746#define RICHCMP_WRAPPER(NAME, OP) \
3747static PyObject * \
3748richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
3749{ \
3750 return wrap_richcmpfunc(self, args, wrapped, OP); \
3751}
3752
Jack Jansen8e938b42001-08-08 15:29:49 +00003753RICHCMP_WRAPPER(lt, Py_LT)
3754RICHCMP_WRAPPER(le, Py_LE)
3755RICHCMP_WRAPPER(eq, Py_EQ)
3756RICHCMP_WRAPPER(ne, Py_NE)
3757RICHCMP_WRAPPER(gt, Py_GT)
3758RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003759
Tim Peters6d6c1a32001-08-02 04:15:00 +00003760static PyObject *
3761wrap_next(PyObject *self, PyObject *args, void *wrapped)
3762{
3763 unaryfunc func = (unaryfunc)wrapped;
3764 PyObject *res;
3765
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003766 if (!PyArg_UnpackTuple(args, "", 0, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003767 return NULL;
3768 res = (*func)(self);
3769 if (res == NULL && !PyErr_Occurred())
3770 PyErr_SetNone(PyExc_StopIteration);
3771 return res;
3772}
3773
Tim Peters6d6c1a32001-08-02 04:15:00 +00003774static PyObject *
3775wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
3776{
3777 descrgetfunc func = (descrgetfunc)wrapped;
3778 PyObject *obj;
3779 PyObject *type = NULL;
3780
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003781 if (!PyArg_UnpackTuple(args, "", 1, 2, &obj, &type))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003782 return NULL;
Guido van Rossum82ed25c2003-02-11 16:25:43 +00003783 if (obj == Py_None)
3784 obj = NULL;
3785 if (type == Py_None)
3786 type = NULL;
3787 if (type == NULL &&obj == NULL) {
3788 PyErr_SetString(PyExc_TypeError,
3789 "__get__(None, None) is invalid");
3790 return NULL;
3791 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003792 return (*func)(self, obj, type);
3793}
3794
Tim Peters6d6c1a32001-08-02 04:15:00 +00003795static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003796wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003797{
3798 descrsetfunc func = (descrsetfunc)wrapped;
3799 PyObject *obj, *value;
3800 int ret;
3801
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003802 if (!PyArg_UnpackTuple(args, "", 2, 2, &obj, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003803 return NULL;
3804 ret = (*func)(self, obj, value);
3805 if (ret < 0)
3806 return NULL;
3807 Py_INCREF(Py_None);
3808 return Py_None;
3809}
Guido van Rossum22b13872002-08-06 21:41:44 +00003810
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00003811static PyObject *
3812wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
3813{
3814 descrsetfunc func = (descrsetfunc)wrapped;
3815 PyObject *obj;
3816 int ret;
3817
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003818 if (!PyArg_UnpackTuple(args, "", 1, 1, &obj))
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00003819 return NULL;
3820 ret = (*func)(self, obj, NULL);
3821 if (ret < 0)
3822 return NULL;
3823 Py_INCREF(Py_None);
3824 return Py_None;
3825}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003826
Tim Peters6d6c1a32001-08-02 04:15:00 +00003827static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00003828wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003829{
3830 initproc func = (initproc)wrapped;
3831
Guido van Rossumc8e56452001-10-22 00:43:43 +00003832 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003833 return NULL;
3834 Py_INCREF(Py_None);
3835 return Py_None;
3836}
3837
Tim Peters6d6c1a32001-08-02 04:15:00 +00003838static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003839tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003840{
Barry Warsaw60f01882001-08-22 19:24:42 +00003841 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003842 PyObject *arg0, *res;
3843
3844 if (self == NULL || !PyType_Check(self))
3845 Py_FatalError("__new__() called with non-type 'self'");
3846 type = (PyTypeObject *)self;
3847 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003848 PyErr_Format(PyExc_TypeError,
3849 "%s.__new__(): not enough arguments",
3850 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003851 return NULL;
3852 }
3853 arg0 = PyTuple_GET_ITEM(args, 0);
3854 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003855 PyErr_Format(PyExc_TypeError,
3856 "%s.__new__(X): X is not a type object (%s)",
3857 type->tp_name,
3858 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003859 return NULL;
3860 }
3861 subtype = (PyTypeObject *)arg0;
3862 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003863 PyErr_Format(PyExc_TypeError,
3864 "%s.__new__(%s): %s is not a subtype of %s",
3865 type->tp_name,
3866 subtype->tp_name,
3867 subtype->tp_name,
3868 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003869 return NULL;
3870 }
Barry Warsaw60f01882001-08-22 19:24:42 +00003871
3872 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00003873 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00003874 most derived base that's not a heap type is this type. */
3875 staticbase = subtype;
3876 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
3877 staticbase = staticbase->tp_base;
Guido van Rossuma8c60f42001-09-14 19:43:36 +00003878 if (staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003879 PyErr_Format(PyExc_TypeError,
3880 "%s.__new__(%s) is not safe, use %s.__new__()",
3881 type->tp_name,
3882 subtype->tp_name,
3883 staticbase == NULL ? "?" : staticbase->tp_name);
3884 return NULL;
3885 }
3886
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003887 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
3888 if (args == NULL)
3889 return NULL;
3890 res = type->tp_new(subtype, args, kwds);
3891 Py_DECREF(args);
3892 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003893}
3894
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003895static struct PyMethodDef tp_new_methoddef[] = {
3896 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00003897 PyDoc_STR("T.__new__(S, ...) -> "
3898 "a new object with type S, a subtype of T")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00003899 {0}
3900};
3901
3902static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003903add_tp_new_wrapper(PyTypeObject *type)
3904{
Guido van Rossumf040ede2001-08-07 16:40:56 +00003905 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003906
Guido van Rossum687ae002001-10-15 22:03:32 +00003907 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00003908 return 0;
3909 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003910 if (func == NULL)
3911 return -1;
Guido van Rossum687ae002001-10-15 22:03:32 +00003912 return PyDict_SetItemString(type->tp_dict, "__new__", func);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003913}
3914
Guido van Rossumf040ede2001-08-07 16:40:56 +00003915/* Slot wrappers that call the corresponding __foo__ slot. See comments
3916 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003917
Guido van Rossumdc91b992001-08-08 22:26:22 +00003918#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003919static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003920FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003921{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00003922 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003923 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003924}
3925
Guido van Rossumdc91b992001-08-08 22:26:22 +00003926#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003927static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003928FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003929{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003930 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003931 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003932}
3933
Guido van Rossumcd118802003-01-06 22:57:47 +00003934/* Boolean helper for SLOT1BINFULL().
3935 right.__class__ is a nontrivial subclass of left.__class__. */
3936static int
3937method_is_overloaded(PyObject *left, PyObject *right, char *name)
3938{
3939 PyObject *a, *b;
3940 int ok;
3941
3942 b = PyObject_GetAttrString((PyObject *)(right->ob_type), name);
3943 if (b == NULL) {
3944 PyErr_Clear();
3945 /* If right doesn't have it, it's not overloaded */
3946 return 0;
3947 }
3948
3949 a = PyObject_GetAttrString((PyObject *)(left->ob_type), name);
3950 if (a == NULL) {
3951 PyErr_Clear();
3952 Py_DECREF(b);
3953 /* If right has it but left doesn't, it's overloaded */
3954 return 1;
3955 }
3956
3957 ok = PyObject_RichCompareBool(a, b, Py_NE);
3958 Py_DECREF(a);
3959 Py_DECREF(b);
3960 if (ok < 0) {
3961 PyErr_Clear();
3962 return 0;
3963 }
3964
3965 return ok;
3966}
3967
Guido van Rossumdc91b992001-08-08 22:26:22 +00003968
3969#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003970static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003971FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003972{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003973 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00003974 int do_other = self->ob_type != other->ob_type && \
3975 other->ob_type->tp_as_number != NULL && \
3976 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003977 if (self->ob_type->tp_as_number != NULL && \
3978 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
3979 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00003980 if (do_other && \
Guido van Rossumcd118802003-01-06 22:57:47 +00003981 PyType_IsSubtype(other->ob_type, self->ob_type) && \
3982 method_is_overloaded(self, other, ROPSTR)) { \
Guido van Rossum55f20992001-10-01 17:18:22 +00003983 r = call_maybe( \
3984 other, ROPSTR, &rcache_str, "(O)", self); \
3985 if (r != Py_NotImplemented) \
3986 return r; \
3987 Py_DECREF(r); \
3988 do_other = 0; \
3989 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00003990 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00003991 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003992 if (r != Py_NotImplemented || \
3993 other->ob_type == self->ob_type) \
3994 return r; \
3995 Py_DECREF(r); \
3996 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00003997 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00003998 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00003999 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004000 } \
4001 Py_INCREF(Py_NotImplemented); \
4002 return Py_NotImplemented; \
4003}
4004
4005#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
4006 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
4007
4008#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
4009static PyObject * \
4010FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
4011{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004012 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004013 return call_method(self, OPSTR, &cache_str, \
4014 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004015}
4016
4017static int
4018slot_sq_length(PyObject *self)
4019{
Guido van Rossum2730b132001-08-28 18:22:14 +00004020 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00004021 PyObject *res = call_method(self, "__len__", &len_str, "()");
Guido van Rossum26111622001-10-01 16:42:49 +00004022 int len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004023
4024 if (res == NULL)
4025 return -1;
Guido van Rossum26111622001-10-01 16:42:49 +00004026 len = (int)PyInt_AsLong(res);
4027 Py_DECREF(res);
Jeremy Hylton73a088e2002-07-25 16:43:29 +00004028 if (len == -1 && PyErr_Occurred())
4029 return -1;
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00004030 if (len < 0) {
Guido van Rossum22b13872002-08-06 21:41:44 +00004031 PyErr_SetString(PyExc_ValueError,
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00004032 "__len__() should return >= 0");
4033 return -1;
4034 }
Guido van Rossum26111622001-10-01 16:42:49 +00004035 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004036}
4037
Guido van Rossumdc91b992001-08-08 22:26:22 +00004038SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
4039SLOT1(slot_sq_repeat, "__mul__", int, "i")
Guido van Rossumf4593e02001-10-03 12:09:30 +00004040
4041/* Super-optimized version of slot_sq_item.
4042 Other slots could do the same... */
4043static PyObject *
4044slot_sq_item(PyObject *self, int i)
4045{
4046 static PyObject *getitem_str;
4047 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
4048 descrgetfunc f;
4049
4050 if (getitem_str == NULL) {
4051 getitem_str = PyString_InternFromString("__getitem__");
4052 if (getitem_str == NULL)
4053 return NULL;
4054 }
4055 func = _PyType_Lookup(self->ob_type, getitem_str);
4056 if (func != NULL) {
Guido van Rossumf4593e02001-10-03 12:09:30 +00004057 if ((f = func->ob_type->tp_descr_get) == NULL)
4058 Py_INCREF(func);
Neal Norwitz673cd822002-10-18 16:33:13 +00004059 else {
Guido van Rossumf4593e02001-10-03 12:09:30 +00004060 func = f(func, self, (PyObject *)(self->ob_type));
Neal Norwitz673cd822002-10-18 16:33:13 +00004061 if (func == NULL) {
4062 return NULL;
4063 }
4064 }
Guido van Rossumf4593e02001-10-03 12:09:30 +00004065 ival = PyInt_FromLong(i);
4066 if (ival != NULL) {
4067 args = PyTuple_New(1);
4068 if (args != NULL) {
4069 PyTuple_SET_ITEM(args, 0, ival);
4070 retval = PyObject_Call(func, args, NULL);
4071 Py_XDECREF(args);
4072 Py_XDECREF(func);
4073 return retval;
4074 }
4075 }
4076 }
4077 else {
4078 PyErr_SetObject(PyExc_AttributeError, getitem_str);
4079 }
4080 Py_XDECREF(args);
4081 Py_XDECREF(ival);
4082 Py_XDECREF(func);
4083 return NULL;
4084}
4085
Guido van Rossumdc91b992001-08-08 22:26:22 +00004086SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004087
4088static int
4089slot_sq_ass_item(PyObject *self, int index, PyObject *value)
4090{
4091 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004092 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004093
4094 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004095 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004096 "(i)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004097 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004098 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004099 "(iO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004100 if (res == NULL)
4101 return -1;
4102 Py_DECREF(res);
4103 return 0;
4104}
4105
4106static int
4107slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
4108{
4109 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004110 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004111
4112 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004113 res = call_method(self, "__delslice__", &delslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004114 "(ii)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004115 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004116 res = call_method(self, "__setslice__", &setslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004117 "(iiO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004118 if (res == NULL)
4119 return -1;
4120 Py_DECREF(res);
4121 return 0;
4122}
4123
4124static int
4125slot_sq_contains(PyObject *self, PyObject *value)
4126{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004127 PyObject *func, *res, *args;
Tim Petersbf9b2442003-03-23 05:35:36 +00004128 int result = -1;
4129
Guido van Rossum60718732001-08-28 17:47:51 +00004130 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004131
Guido van Rossum55f20992001-10-01 17:18:22 +00004132 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004133 if (func != NULL) {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004134 args = PyTuple_Pack(1, value);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004135 if (args == NULL)
4136 res = NULL;
4137 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004138 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004139 Py_DECREF(args);
4140 }
4141 Py_DECREF(func);
Tim Petersbf9b2442003-03-23 05:35:36 +00004142 if (res != NULL) {
4143 result = PyObject_IsTrue(res);
4144 Py_DECREF(res);
4145 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004146 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004147 else if (! PyErr_Occurred()) {
4148 result = _PySequence_IterSearch(self, value,
4149 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004150 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004151 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004152}
4153
Guido van Rossumdc91b992001-08-08 22:26:22 +00004154SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
4155SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004156
4157#define slot_mp_length slot_sq_length
4158
Guido van Rossumdc91b992001-08-08 22:26:22 +00004159SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004160
4161static int
4162slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
4163{
4164 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004165 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004166
4167 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004168 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004169 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004170 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004171 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004172 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004173 if (res == NULL)
4174 return -1;
4175 Py_DECREF(res);
4176 return 0;
4177}
4178
Guido van Rossumdc91b992001-08-08 22:26:22 +00004179SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
4180SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
4181SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
4182SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
4183SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
4184SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
4185
Jeremy Hylton938ace62002-07-17 16:30:39 +00004186static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00004187
4188SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
4189 nb_power, "__pow__", "__rpow__")
4190
4191static PyObject *
4192slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
4193{
Guido van Rossum2730b132001-08-28 18:22:14 +00004194 static PyObject *pow_str;
4195
Guido van Rossumdc91b992001-08-08 22:26:22 +00004196 if (modulus == Py_None)
4197 return slot_nb_power_binary(self, other);
Guido van Rossum23094982002-06-10 14:30:43 +00004198 /* Three-arg power doesn't use __rpow__. But ternary_op
4199 can call this when the second argument's type uses
4200 slot_nb_power, so check before calling self.__pow__. */
4201 if (self->ob_type->tp_as_number != NULL &&
4202 self->ob_type->tp_as_number->nb_power == slot_nb_power) {
4203 return call_method(self, "__pow__", &pow_str,
4204 "(OO)", other, modulus);
4205 }
4206 Py_INCREF(Py_NotImplemented);
4207 return Py_NotImplemented;
Guido van Rossumdc91b992001-08-08 22:26:22 +00004208}
4209
4210SLOT0(slot_nb_negative, "__neg__")
4211SLOT0(slot_nb_positive, "__pos__")
4212SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004213
4214static int
4215slot_nb_nonzero(PyObject *self)
4216{
Tim Petersea7f75d2002-12-07 21:39:16 +00004217 PyObject *func, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00004218 static PyObject *nonzero_str, *len_str;
Tim Petersea7f75d2002-12-07 21:39:16 +00004219 int result = -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004220
Guido van Rossum55f20992001-10-01 17:18:22 +00004221 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004222 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00004223 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00004224 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00004225 func = lookup_maybe(self, "__len__", &len_str);
Tim Petersea7f75d2002-12-07 21:39:16 +00004226 if (func == NULL)
4227 return PyErr_Occurred() ? -1 : 1;
4228 }
4229 args = PyTuple_New(0);
4230 if (args != NULL) {
4231 PyObject *temp = PyObject_Call(func, args, NULL);
4232 Py_DECREF(args);
4233 if (temp != NULL) {
Jeremy Hylton3e3159c2003-06-27 17:38:27 +00004234 if (PyInt_CheckExact(temp) || PyBool_Check(temp))
Jeremy Hylton090a3492003-06-27 16:46:45 +00004235 result = PyObject_IsTrue(temp);
4236 else {
4237 PyErr_Format(PyExc_TypeError,
4238 "__nonzero__ should return "
4239 "bool or int, returned %s",
4240 temp->ob_type->tp_name);
Jeremy Hylton3e3159c2003-06-27 17:38:27 +00004241 result = -1;
Jeremy Hylton090a3492003-06-27 16:46:45 +00004242 }
Tim Petersea7f75d2002-12-07 21:39:16 +00004243 Py_DECREF(temp);
Guido van Rossum55f20992001-10-01 17:18:22 +00004244 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004245 }
Guido van Rossum55f20992001-10-01 17:18:22 +00004246 Py_DECREF(func);
Tim Petersea7f75d2002-12-07 21:39:16 +00004247 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004248}
4249
Guido van Rossumdc91b992001-08-08 22:26:22 +00004250SLOT0(slot_nb_invert, "__invert__")
4251SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
4252SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
4253SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
4254SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
4255SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004256
4257static int
4258slot_nb_coerce(PyObject **a, PyObject **b)
4259{
4260 static PyObject *coerce_str;
4261 PyObject *self = *a, *other = *b;
4262
4263 if (self->ob_type->tp_as_number != NULL &&
4264 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
4265 PyObject *r;
4266 r = call_maybe(
4267 self, "__coerce__", &coerce_str, "(O)", other);
4268 if (r == NULL)
4269 return -1;
4270 if (r == Py_NotImplemented) {
4271 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004272 }
Guido van Rossum55f20992001-10-01 17:18:22 +00004273 else {
4274 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
4275 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004276 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00004277 Py_DECREF(r);
4278 return -1;
4279 }
4280 *a = PyTuple_GET_ITEM(r, 0);
4281 Py_INCREF(*a);
4282 *b = PyTuple_GET_ITEM(r, 1);
4283 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004284 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00004285 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004286 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004287 }
4288 if (other->ob_type->tp_as_number != NULL &&
4289 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
4290 PyObject *r;
4291 r = call_maybe(
4292 other, "__coerce__", &coerce_str, "(O)", self);
4293 if (r == NULL)
4294 return -1;
4295 if (r == Py_NotImplemented) {
4296 Py_DECREF(r);
4297 return 1;
4298 }
4299 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
4300 PyErr_SetString(PyExc_TypeError,
4301 "__coerce__ didn't return a 2-tuple");
4302 Py_DECREF(r);
4303 return -1;
4304 }
4305 *a = PyTuple_GET_ITEM(r, 1);
4306 Py_INCREF(*a);
4307 *b = PyTuple_GET_ITEM(r, 0);
4308 Py_INCREF(*b);
4309 Py_DECREF(r);
4310 return 0;
4311 }
4312 return 1;
4313}
4314
Guido van Rossumdc91b992001-08-08 22:26:22 +00004315SLOT0(slot_nb_int, "__int__")
4316SLOT0(slot_nb_long, "__long__")
4317SLOT0(slot_nb_float, "__float__")
4318SLOT0(slot_nb_oct, "__oct__")
4319SLOT0(slot_nb_hex, "__hex__")
4320SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
4321SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
4322SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
4323SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
4324SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Guido van Rossum6e5680f2002-10-15 01:01:53 +00004325SLOT1(slot_nb_inplace_power, "__ipow__", PyObject *, "O")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004326SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
4327SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
4328SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
4329SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
4330SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
4331SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
4332 "__floordiv__", "__rfloordiv__")
4333SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
4334SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
4335SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004336
4337static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00004338half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004339{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004340 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004341 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004342 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004343
Guido van Rossum60718732001-08-28 17:47:51 +00004344 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004345 if (func == NULL) {
4346 PyErr_Clear();
4347 }
4348 else {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004349 args = PyTuple_Pack(1, other);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004350 if (args == NULL)
4351 res = NULL;
4352 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004353 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004354 Py_DECREF(args);
4355 }
Raymond Hettingerab5dae32002-06-24 13:08:16 +00004356 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004357 if (res != Py_NotImplemented) {
4358 if (res == NULL)
4359 return -2;
4360 c = PyInt_AsLong(res);
4361 Py_DECREF(res);
4362 if (c == -1 && PyErr_Occurred())
4363 return -2;
4364 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
4365 }
4366 Py_DECREF(res);
4367 }
4368 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004369}
4370
Guido van Rossumab3b0342001-09-18 20:38:53 +00004371/* This slot is published for the benefit of try_3way_compare in object.c */
4372int
4373_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00004374{
4375 int c;
4376
Guido van Rossumab3b0342001-09-18 20:38:53 +00004377 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004378 c = half_compare(self, other);
4379 if (c <= 1)
4380 return c;
4381 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00004382 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004383 c = half_compare(other, self);
4384 if (c < -1)
4385 return -2;
4386 if (c <= 1)
4387 return -c;
4388 }
4389 return (void *)self < (void *)other ? -1 :
4390 (void *)self > (void *)other ? 1 : 0;
4391}
4392
4393static PyObject *
4394slot_tp_repr(PyObject *self)
4395{
4396 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004397 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004398
Guido van Rossum60718732001-08-28 17:47:51 +00004399 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004400 if (func != NULL) {
4401 res = PyEval_CallObject(func, NULL);
4402 Py_DECREF(func);
4403 return res;
4404 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00004405 PyErr_Clear();
4406 return PyString_FromFormat("<%s object at %p>",
4407 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004408}
4409
4410static PyObject *
4411slot_tp_str(PyObject *self)
4412{
4413 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004414 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004415
Guido van Rossum60718732001-08-28 17:47:51 +00004416 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004417 if (func != NULL) {
4418 res = PyEval_CallObject(func, NULL);
4419 Py_DECREF(func);
4420 return res;
4421 }
4422 else {
4423 PyErr_Clear();
4424 return slot_tp_repr(self);
4425 }
4426}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004427
4428static long
4429slot_tp_hash(PyObject *self)
4430{
Tim Peters61ce0a92002-12-06 23:38:02 +00004431 PyObject *func;
Guido van Rossum60718732001-08-28 17:47:51 +00004432 static PyObject *hash_str, *eq_str, *cmp_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004433 long h;
4434
Guido van Rossum60718732001-08-28 17:47:51 +00004435 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004436
4437 if (func != NULL) {
Tim Peters61ce0a92002-12-06 23:38:02 +00004438 PyObject *res = PyEval_CallObject(func, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004439 Py_DECREF(func);
4440 if (res == NULL)
4441 return -1;
4442 h = PyInt_AsLong(res);
Tim Peters61ce0a92002-12-06 23:38:02 +00004443 Py_DECREF(res);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004444 }
4445 else {
4446 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004447 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004448 if (func == NULL) {
4449 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004450 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004451 }
4452 if (func != NULL) {
4453 Py_DECREF(func);
4454 PyErr_SetString(PyExc_TypeError, "unhashable type");
4455 return -1;
4456 }
4457 PyErr_Clear();
4458 h = _Py_HashPointer((void *)self);
4459 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004460 if (h == -1 && !PyErr_Occurred())
4461 h = -2;
4462 return h;
4463}
4464
4465static PyObject *
4466slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
4467{
Guido van Rossum60718732001-08-28 17:47:51 +00004468 static PyObject *call_str;
4469 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004470 PyObject *res;
4471
4472 if (meth == NULL)
4473 return NULL;
4474 res = PyObject_Call(meth, args, kwds);
4475 Py_DECREF(meth);
4476 return res;
4477}
4478
Guido van Rossum14a6f832001-10-17 13:59:09 +00004479/* There are two slot dispatch functions for tp_getattro.
4480
4481 - slot_tp_getattro() is used when __getattribute__ is overridden
4482 but no __getattr__ hook is present;
4483
4484 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
4485
Guido van Rossumc334df52002-04-04 23:44:47 +00004486 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
4487 detects the absence of __getattr__ and then installs the simpler slot if
4488 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00004489
Tim Peters6d6c1a32001-08-02 04:15:00 +00004490static PyObject *
4491slot_tp_getattro(PyObject *self, PyObject *name)
4492{
Guido van Rossum14a6f832001-10-17 13:59:09 +00004493 static PyObject *getattribute_str = NULL;
4494 return call_method(self, "__getattribute__", &getattribute_str,
4495 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004496}
4497
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004498static PyObject *
4499slot_tp_getattr_hook(PyObject *self, PyObject *name)
4500{
4501 PyTypeObject *tp = self->ob_type;
4502 PyObject *getattr, *getattribute, *res;
4503 static PyObject *getattribute_str = NULL;
4504 static PyObject *getattr_str = NULL;
4505
4506 if (getattr_str == NULL) {
4507 getattr_str = PyString_InternFromString("__getattr__");
4508 if (getattr_str == NULL)
4509 return NULL;
4510 }
4511 if (getattribute_str == NULL) {
4512 getattribute_str =
4513 PyString_InternFromString("__getattribute__");
4514 if (getattribute_str == NULL)
4515 return NULL;
4516 }
4517 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004518 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004519 /* No __getattr__ hook: use a simpler dispatcher */
4520 tp->tp_getattro = slot_tp_getattro;
4521 return slot_tp_getattro(self, name);
4522 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004523 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004524 if (getattribute == NULL ||
4525 (getattribute->ob_type == &PyWrapperDescr_Type &&
4526 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
4527 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004528 res = PyObject_GenericGetAttr(self, name);
4529 else
4530 res = PyObject_CallFunction(getattribute, "OO", self, name);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004531 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004532 PyErr_Clear();
4533 res = PyObject_CallFunction(getattr, "OO", self, name);
4534 }
4535 return res;
4536}
4537
Tim Peters6d6c1a32001-08-02 04:15:00 +00004538static int
4539slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
4540{
4541 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004542 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004543
4544 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004545 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004546 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004547 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004548 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004549 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004550 if (res == NULL)
4551 return -1;
4552 Py_DECREF(res);
4553 return 0;
4554}
4555
4556/* Map rich comparison operators to their __xx__ namesakes */
4557static char *name_op[] = {
4558 "__lt__",
4559 "__le__",
4560 "__eq__",
4561 "__ne__",
4562 "__gt__",
4563 "__ge__",
4564};
4565
4566static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00004567half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004568{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004569 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004570 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00004571
Guido van Rossum60718732001-08-28 17:47:51 +00004572 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004573 if (func == NULL) {
4574 PyErr_Clear();
4575 Py_INCREF(Py_NotImplemented);
4576 return Py_NotImplemented;
4577 }
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004578 args = PyTuple_Pack(1, other);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004579 if (args == NULL)
4580 res = NULL;
4581 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004582 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004583 Py_DECREF(args);
4584 }
4585 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004586 return res;
4587}
4588
Guido van Rossumb8f63662001-08-15 23:57:02 +00004589/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
4590static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
4591
4592static PyObject *
4593slot_tp_richcompare(PyObject *self, PyObject *other, int op)
4594{
4595 PyObject *res;
4596
4597 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
4598 res = half_richcompare(self, other, op);
4599 if (res != Py_NotImplemented)
4600 return res;
4601 Py_DECREF(res);
4602 }
4603 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
4604 res = half_richcompare(other, self, swapped_op[op]);
4605 if (res != Py_NotImplemented) {
4606 return res;
4607 }
4608 Py_DECREF(res);
4609 }
4610 Py_INCREF(Py_NotImplemented);
4611 return Py_NotImplemented;
4612}
4613
4614static PyObject *
4615slot_tp_iter(PyObject *self)
4616{
4617 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004618 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004619
Guido van Rossum60718732001-08-28 17:47:51 +00004620 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004621 if (func != NULL) {
Guido van Rossum84b2bed2002-08-16 17:01:09 +00004622 PyObject *args;
4623 args = res = PyTuple_New(0);
4624 if (args != NULL) {
4625 res = PyObject_Call(func, args, NULL);
4626 Py_DECREF(args);
4627 }
4628 Py_DECREF(func);
4629 return res;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004630 }
4631 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004632 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004633 if (func == NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00004634 PyErr_SetString(PyExc_TypeError,
4635 "iteration over non-sequence");
Guido van Rossumb8f63662001-08-15 23:57:02 +00004636 return NULL;
4637 }
4638 Py_DECREF(func);
4639 return PySeqIter_New(self);
4640}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004641
4642static PyObject *
4643slot_tp_iternext(PyObject *self)
4644{
Guido van Rossum2730b132001-08-28 18:22:14 +00004645 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00004646 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004647}
4648
Guido van Rossum1a493502001-08-17 16:47:50 +00004649static PyObject *
4650slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4651{
4652 PyTypeObject *tp = self->ob_type;
4653 PyObject *get;
4654 static PyObject *get_str = NULL;
4655
4656 if (get_str == NULL) {
4657 get_str = PyString_InternFromString("__get__");
4658 if (get_str == NULL)
4659 return NULL;
4660 }
4661 get = _PyType_Lookup(tp, get_str);
4662 if (get == NULL) {
4663 /* Avoid further slowdowns */
4664 if (tp->tp_descr_get == slot_tp_descr_get)
4665 tp->tp_descr_get = NULL;
4666 Py_INCREF(self);
4667 return self;
4668 }
Guido van Rossum2c252392001-08-24 10:13:31 +00004669 if (obj == NULL)
4670 obj = Py_None;
4671 if (type == NULL)
4672 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00004673 return PyObject_CallFunction(get, "OOO", self, obj, type);
4674}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004675
4676static int
4677slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
4678{
Guido van Rossum2c252392001-08-24 10:13:31 +00004679 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004680 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00004681
4682 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00004683 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004684 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00004685 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004686 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004687 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004688 if (res == NULL)
4689 return -1;
4690 Py_DECREF(res);
4691 return 0;
4692}
4693
4694static int
4695slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
4696{
Guido van Rossum60718732001-08-28 17:47:51 +00004697 static PyObject *init_str;
4698 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004699 PyObject *res;
4700
4701 if (meth == NULL)
4702 return -1;
4703 res = PyObject_Call(meth, args, kwds);
4704 Py_DECREF(meth);
4705 if (res == NULL)
4706 return -1;
4707 Py_DECREF(res);
4708 return 0;
4709}
4710
4711static PyObject *
4712slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4713{
Guido van Rossum7bed2132002-08-08 21:57:53 +00004714 static PyObject *new_str;
4715 PyObject *func;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004716 PyObject *newargs, *x;
4717 int i, n;
4718
Guido van Rossum7bed2132002-08-08 21:57:53 +00004719 if (new_str == NULL) {
4720 new_str = PyString_InternFromString("__new__");
4721 if (new_str == NULL)
4722 return NULL;
4723 }
4724 func = PyObject_GetAttr((PyObject *)type, new_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004725 if (func == NULL)
4726 return NULL;
4727 assert(PyTuple_Check(args));
4728 n = PyTuple_GET_SIZE(args);
4729 newargs = PyTuple_New(n+1);
4730 if (newargs == NULL)
4731 return NULL;
4732 Py_INCREF(type);
4733 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
4734 for (i = 0; i < n; i++) {
4735 x = PyTuple_GET_ITEM(args, i);
4736 Py_INCREF(x);
4737 PyTuple_SET_ITEM(newargs, i+1, x);
4738 }
4739 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00004740 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004741 Py_DECREF(func);
4742 return x;
4743}
4744
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004745static void
4746slot_tp_del(PyObject *self)
4747{
4748 static PyObject *del_str = NULL;
4749 PyObject *del, *res;
4750 PyObject *error_type, *error_value, *error_traceback;
4751
4752 /* Temporarily resurrect the object. */
4753 assert(self->ob_refcnt == 0);
4754 self->ob_refcnt = 1;
4755
4756 /* Save the current exception, if any. */
4757 PyErr_Fetch(&error_type, &error_value, &error_traceback);
4758
4759 /* Execute __del__ method, if any. */
4760 del = lookup_maybe(self, "__del__", &del_str);
4761 if (del != NULL) {
4762 res = PyEval_CallObject(del, NULL);
4763 if (res == NULL)
4764 PyErr_WriteUnraisable(del);
4765 else
4766 Py_DECREF(res);
4767 Py_DECREF(del);
4768 }
4769
4770 /* Restore the saved exception. */
4771 PyErr_Restore(error_type, error_value, error_traceback);
4772
4773 /* Undo the temporary resurrection; can't use DECREF here, it would
4774 * cause a recursive call.
4775 */
4776 assert(self->ob_refcnt > 0);
4777 if (--self->ob_refcnt == 0)
4778 return; /* this is the normal path out */
4779
4780 /* __del__ resurrected it! Make it look like the original Py_DECREF
4781 * never happened.
4782 */
4783 {
4784 int refcnt = self->ob_refcnt;
4785 _Py_NewReference(self);
4786 self->ob_refcnt = refcnt;
4787 }
4788 assert(!PyType_IS_GC(self->ob_type) ||
4789 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
4790 /* If Py_REF_DEBUG, the original decref dropped _Py_RefTotal, but
4791 * _Py_NewReference bumped it again, so that's a wash.
4792 * If Py_TRACE_REFS, _Py_NewReference re-added self to the object
4793 * chain, so no more to do there either.
4794 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
4795 * _Py_NewReference bumped tp_allocs: both of those need to be
4796 * undone.
4797 */
4798#ifdef COUNT_ALLOCS
4799 --self->ob_type->tp_frees;
4800 --self->ob_type->tp_allocs;
4801#endif
4802}
4803
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004804
4805/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
Tim Petersbf9b2442003-03-23 05:35:36 +00004806 functions. The offsets here are relative to the 'PyHeapTypeObject'
Guido van Rossume5c691a2003-03-07 15:13:17 +00004807 structure, which incorporates the additional structures used for numbers,
4808 sequences and mappings.
4809 Note that multiple names may map to the same slot (e.g. __eq__,
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004810 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00004811 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
4812 terminated with an all-zero entry. (This table is further initialized and
4813 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004814
Guido van Rossum6d204072001-10-21 00:44:31 +00004815typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004816
4817#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00004818#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004819#undef ETSLOT
4820#undef SQSLOT
4821#undef MPSLOT
4822#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00004823#undef UNSLOT
4824#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004825#undef BINSLOT
4826#undef RBINSLOT
4827
Guido van Rossum6d204072001-10-21 00:44:31 +00004828#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004829 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
4830 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00004831#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
4832 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004833 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00004834#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Guido van Rossume5c691a2003-03-07 15:13:17 +00004835 {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004836 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00004837#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4838 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
4839#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4840 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
4841#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4842 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
4843#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4844 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
4845 "x." NAME "() <==> " DOC)
4846#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4847 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
4848 "x." NAME "(y) <==> x" DOC "y")
4849#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
4850 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
4851 "x." NAME "(y) <==> x" DOC "y")
4852#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
4853 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
4854 "x." NAME "(y) <==> y" DOC "x")
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004855
4856static slotdef slotdefs[] = {
Guido van Rossum6d204072001-10-21 00:44:31 +00004857 SQSLOT("__len__", sq_length, slot_sq_length, wrap_inquiry,
4858 "x.__len__() <==> len(x)"),
4859 SQSLOT("__add__", sq_concat, slot_sq_concat, wrap_binaryfunc,
4860 "x.__add__(y) <==> x+y"),
4861 SQSLOT("__mul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
4862 "x.__mul__(n) <==> x*n"),
4863 SQSLOT("__rmul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
4864 "x.__rmul__(n) <==> n*x"),
4865 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
4866 "x.__getitem__(y) <==> x[y]"),
4867 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_intintargfunc,
Brett Cannon154da9b2003-05-20 02:30:04 +00004868 "x.__getslice__(i, j) <==> x[i:j]\n\
4869 \n\
4870 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00004871 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
Brett Cannonbe67d872003-05-20 02:40:12 +00004872 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum6d204072001-10-21 00:44:31 +00004873 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
Brett Cannonbe67d872003-05-20 02:40:12 +00004874 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004875 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Guido van Rossum6d204072001-10-21 00:44:31 +00004876 wrap_intintobjargproc,
Brett Cannonbe67d872003-05-20 02:40:12 +00004877 "x.__setslice__(i, j, y) <==> x[i:j]=y\n\
4878 \n\
4879 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00004880 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
Brett Cannonbe67d872003-05-20 02:40:12 +00004881 "x.__delslice__(i, j) <==> del x[i:j]\n\
4882 \n\
4883 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00004884 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
4885 "x.__contains__(y) <==> y in x"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004886 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat,
Guido van Rossum6d204072001-10-21 00:44:31 +00004887 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004888 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat,
Guido van Rossum6d204072001-10-21 00:44:31 +00004889 wrap_intargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004890
Guido van Rossum6d204072001-10-21 00:44:31 +00004891 MPSLOT("__len__", mp_length, slot_mp_length, wrap_inquiry,
4892 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00004893 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004894 wrap_binaryfunc,
4895 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004896 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004897 wrap_objobjargproc,
4898 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004899 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004900 wrap_delitem,
4901 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004902
Guido van Rossum6d204072001-10-21 00:44:31 +00004903 BINSLOT("__add__", nb_add, slot_nb_add,
4904 "+"),
4905 RBINSLOT("__radd__", nb_add, slot_nb_add,
4906 "+"),
4907 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
4908 "-"),
4909 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
4910 "-"),
4911 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
4912 "*"),
4913 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
4914 "*"),
4915 BINSLOT("__div__", nb_divide, slot_nb_divide,
4916 "/"),
4917 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
4918 "/"),
4919 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
4920 "%"),
4921 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
4922 "%"),
4923 BINSLOT("__divmod__", nb_divmod, slot_nb_divmod,
4924 "divmod(x, y)"),
4925 RBINSLOT("__rdivmod__", nb_divmod, slot_nb_divmod,
4926 "divmod(y, x)"),
4927 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
4928 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
4929 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
4930 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
4931 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
4932 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
4933 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
4934 "abs(x)"),
Raymond Hettingerf34f2642003-10-11 17:29:04 +00004935 UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquirypred,
Guido van Rossum6d204072001-10-21 00:44:31 +00004936 "x != 0"),
4937 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
4938 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
4939 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
4940 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
4941 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
4942 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
4943 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
4944 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
4945 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
4946 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
4947 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
4948 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
4949 "x.__coerce__(y) <==> coerce(x, y)"),
4950 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
4951 "int(x)"),
4952 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
4953 "long(x)"),
4954 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
4955 "float(x)"),
4956 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
4957 "oct(x)"),
4958 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
4959 "hex(x)"),
4960 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
4961 wrap_binaryfunc, "+"),
4962 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
4963 wrap_binaryfunc, "-"),
4964 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
4965 wrap_binaryfunc, "*"),
4966 IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
4967 wrap_binaryfunc, "/"),
4968 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
4969 wrap_binaryfunc, "%"),
4970 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
Guido van Rossum6e5680f2002-10-15 01:01:53 +00004971 wrap_binaryfunc, "**"),
Guido van Rossum6d204072001-10-21 00:44:31 +00004972 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
4973 wrap_binaryfunc, "<<"),
4974 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
4975 wrap_binaryfunc, ">>"),
4976 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
4977 wrap_binaryfunc, "&"),
4978 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
4979 wrap_binaryfunc, "^"),
4980 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
4981 wrap_binaryfunc, "|"),
4982 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
4983 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
4984 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
4985 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
4986 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
4987 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
4988 IBSLOT("__itruediv__", nb_inplace_true_divide,
4989 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004990
Guido van Rossum6d204072001-10-21 00:44:31 +00004991 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
4992 "x.__str__() <==> str(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00004993 TPSLOT("__str__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00004994 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
4995 "x.__repr__() <==> repr(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00004996 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00004997 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
4998 "x.__cmp__(y) <==> cmp(x,y)"),
4999 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
5000 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00005001 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
5002 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005003 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00005004 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
5005 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
5006 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
5007 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
5008 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
5009 "x.__setattr__('name', value) <==> x.name = value"),
5010 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
5011 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
5012 "x.__delattr__('name') <==> del x.name"),
5013 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
5014 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
5015 "x.__lt__(y) <==> x<y"),
5016 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
5017 "x.__le__(y) <==> x<=y"),
5018 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
5019 "x.__eq__(y) <==> x==y"),
5020 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
5021 "x.__ne__(y) <==> x!=y"),
5022 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
5023 "x.__gt__(y) <==> x>y"),
5024 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
5025 "x.__ge__(y) <==> x>=y"),
5026 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
5027 "x.__iter__() <==> iter(x)"),
5028 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
5029 "x.next() -> the next value, or raise StopIteration"),
5030 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
5031 "descr.__get__(obj[, type]) -> value"),
5032 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
5033 "descr.__set__(obj, value)"),
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00005034 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
5035 wrap_descr_delete, "descr.__delete__(obj)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00005036 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00005037 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00005038 "see x.__class__.__doc__ for signature",
5039 PyWrapperFlag_KEYWORDS),
5040 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005041 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005042 {NULL}
5043};
5044
Guido van Rossumc334df52002-04-04 23:44:47 +00005045/* Given a type pointer and an offset gotten from a slotdef entry, return a
5046 pointer to the actual slot. This is not quite the same as simply adding
5047 the offset to the type pointer, since it takes care to indirect through the
5048 proper indirection pointer (as_buffer, etc.); it returns NULL if the
5049 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005050static void **
5051slotptr(PyTypeObject *type, int offset)
5052{
5053 char *ptr;
5054
Guido van Rossume5c691a2003-03-07 15:13:17 +00005055 /* Note: this depends on the order of the members of PyHeapTypeObject! */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005056 assert(offset >= 0);
Guido van Rossume5c691a2003-03-07 15:13:17 +00005057 assert(offset < offsetof(PyHeapTypeObject, as_buffer));
5058 if (offset >= offsetof(PyHeapTypeObject, as_sequence)) {
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005059 ptr = (void *)type->tp_as_sequence;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005060 offset -= offsetof(PyHeapTypeObject, as_sequence);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005061 }
Guido van Rossume5c691a2003-03-07 15:13:17 +00005062 else if (offset >= offsetof(PyHeapTypeObject, as_mapping)) {
Guido van Rossum09638c12002-06-13 19:17:46 +00005063 ptr = (void *)type->tp_as_mapping;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005064 offset -= offsetof(PyHeapTypeObject, as_mapping);
Guido van Rossum09638c12002-06-13 19:17:46 +00005065 }
Guido van Rossume5c691a2003-03-07 15:13:17 +00005066 else if (offset >= offsetof(PyHeapTypeObject, as_number)) {
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005067 ptr = (void *)type->tp_as_number;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005068 offset -= offsetof(PyHeapTypeObject, as_number);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005069 }
5070 else {
5071 ptr = (void *)type;
5072 }
5073 if (ptr != NULL)
5074 ptr += offset;
5075 return (void **)ptr;
5076}
Guido van Rossumf040ede2001-08-07 16:40:56 +00005077
Guido van Rossumc334df52002-04-04 23:44:47 +00005078/* Length of array of slotdef pointers used to store slots with the
5079 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
5080 the same __name__, for any __name__. Since that's a static property, it is
5081 appropriate to declare fixed-size arrays for this. */
5082#define MAX_EQUIV 10
5083
5084/* Return a slot pointer for a given name, but ONLY if the attribute has
5085 exactly one slot function. The name must be an interned string. */
5086static void **
5087resolve_slotdups(PyTypeObject *type, PyObject *name)
5088{
5089 /* XXX Maybe this could be optimized more -- but is it worth it? */
5090
5091 /* pname and ptrs act as a little cache */
5092 static PyObject *pname;
5093 static slotdef *ptrs[MAX_EQUIV];
5094 slotdef *p, **pp;
5095 void **res, **ptr;
5096
5097 if (pname != name) {
5098 /* Collect all slotdefs that match name into ptrs. */
5099 pname = name;
5100 pp = ptrs;
5101 for (p = slotdefs; p->name_strobj; p++) {
5102 if (p->name_strobj == name)
5103 *pp++ = p;
5104 }
5105 *pp = NULL;
5106 }
5107
5108 /* Look in all matching slots of the type; if exactly one of these has
5109 a filled-in slot, return its value. Otherwise return NULL. */
5110 res = NULL;
5111 for (pp = ptrs; *pp; pp++) {
5112 ptr = slotptr(type, (*pp)->offset);
5113 if (ptr == NULL || *ptr == NULL)
5114 continue;
5115 if (res != NULL)
5116 return NULL;
5117 res = ptr;
5118 }
5119 return res;
5120}
5121
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005122/* Common code for update_slots_callback() and fixup_slot_dispatchers(). This
Guido van Rossumc334df52002-04-04 23:44:47 +00005123 does some incredibly complex thinking and then sticks something into the
5124 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
5125 interests, and then stores a generic wrapper or a specific function into
5126 the slot.) Return a pointer to the next slotdef with a different offset,
5127 because that's convenient for fixup_slot_dispatchers(). */
5128static slotdef *
5129update_one_slot(PyTypeObject *type, slotdef *p)
5130{
5131 PyObject *descr;
5132 PyWrapperDescrObject *d;
5133 void *generic = NULL, *specific = NULL;
5134 int use_generic = 0;
5135 int offset = p->offset;
5136 void **ptr = slotptr(type, offset);
5137
5138 if (ptr == NULL) {
5139 do {
5140 ++p;
5141 } while (p->offset == offset);
5142 return p;
5143 }
5144 do {
5145 descr = _PyType_Lookup(type, p->name_strobj);
5146 if (descr == NULL)
5147 continue;
5148 if (descr->ob_type == &PyWrapperDescr_Type) {
5149 void **tptr = resolve_slotdups(type, p->name_strobj);
5150 if (tptr == NULL || tptr == ptr)
5151 generic = p->function;
5152 d = (PyWrapperDescrObject *)descr;
5153 if (d->d_base->wrapper == p->wrapper &&
5154 PyType_IsSubtype(type, d->d_type))
5155 {
5156 if (specific == NULL ||
5157 specific == d->d_wrapped)
5158 specific = d->d_wrapped;
5159 else
5160 use_generic = 1;
5161 }
5162 }
Guido van Rossum721f62e2002-08-09 02:14:34 +00005163 else if (descr->ob_type == &PyCFunction_Type &&
5164 PyCFunction_GET_FUNCTION(descr) ==
5165 (PyCFunction)tp_new_wrapper &&
5166 strcmp(p->name, "__new__") == 0)
5167 {
5168 /* The __new__ wrapper is not a wrapper descriptor,
5169 so must be special-cased differently.
5170 If we don't do this, creating an instance will
5171 always use slot_tp_new which will look up
5172 __new__ in the MRO which will call tp_new_wrapper
5173 which will look through the base classes looking
5174 for a static base and call its tp_new (usually
5175 PyType_GenericNew), after performing various
5176 sanity checks and constructing a new argument
5177 list. Cut all that nonsense short -- this speeds
5178 up instance creation tremendously. */
Martin v. Löwisa94568a2003-05-10 07:36:56 +00005179 specific = (void *)type->tp_new;
Guido van Rossum721f62e2002-08-09 02:14:34 +00005180 /* XXX I'm not 100% sure that there isn't a hole
5181 in this reasoning that requires additional
5182 sanity checks. I'll buy the first person to
5183 point out a bug in this reasoning a beer. */
5184 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005185 else {
5186 use_generic = 1;
5187 generic = p->function;
5188 }
5189 } while ((++p)->offset == offset);
5190 if (specific && !use_generic)
5191 *ptr = specific;
5192 else
5193 *ptr = generic;
5194 return p;
5195}
5196
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005197/* In the type, update the slots whose slotdefs are gathered in the pp array.
5198 This is a callback for update_subclasses(). */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005199static int
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005200update_slots_callback(PyTypeObject *type, void *data)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005201{
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005202 slotdef **pp = (slotdef **)data;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005203
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005204 for (; *pp; pp++)
Guido van Rossumc334df52002-04-04 23:44:47 +00005205 update_one_slot(type, *pp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005206 return 0;
5207}
5208
Guido van Rossumc334df52002-04-04 23:44:47 +00005209/* Comparison function for qsort() to compare slotdefs by their offset, and
5210 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005211static int
5212slotdef_cmp(const void *aa, const void *bb)
5213{
5214 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
5215 int c = a->offset - b->offset;
5216 if (c != 0)
5217 return c;
5218 else
5219 return a - b;
5220}
5221
Guido van Rossumc334df52002-04-04 23:44:47 +00005222/* Initialize the slotdefs table by adding interned string objects for the
5223 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005224static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005225init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005226{
5227 slotdef *p;
5228 static int initialized = 0;
5229
5230 if (initialized)
5231 return;
5232 for (p = slotdefs; p->name; p++) {
5233 p->name_strobj = PyString_InternFromString(p->name);
5234 if (!p->name_strobj)
Guido van Rossumc334df52002-04-04 23:44:47 +00005235 Py_FatalError("Out of memory interning slotdef names");
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005236 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005237 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
5238 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005239 initialized = 1;
5240}
5241
Guido van Rossumc334df52002-04-04 23:44:47 +00005242/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005243static int
5244update_slot(PyTypeObject *type, PyObject *name)
5245{
Guido van Rossumc334df52002-04-04 23:44:47 +00005246 slotdef *ptrs[MAX_EQUIV];
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005247 slotdef *p;
5248 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005249 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005250
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005251 init_slotdefs();
5252 pp = ptrs;
5253 for (p = slotdefs; p->name; p++) {
5254 /* XXX assume name is interned! */
5255 if (p->name_strobj == name)
5256 *pp++ = p;
5257 }
5258 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005259 for (pp = ptrs; *pp; pp++) {
5260 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005261 offset = p->offset;
5262 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005263 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005264 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005265 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005266 if (ptrs[0] == NULL)
5267 return 0; /* Not an attribute that affects any slots */
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005268 return update_subclasses(type, name,
5269 update_slots_callback, (void *)ptrs);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005270}
5271
Guido van Rossumc334df52002-04-04 23:44:47 +00005272/* Store the proper functions in the slot dispatches at class (type)
5273 definition time, based upon which operations the class overrides in its
5274 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00005275static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005276fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005277{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005278 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005279
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005280 init_slotdefs();
Guido van Rossumc334df52002-04-04 23:44:47 +00005281 for (p = slotdefs; p->name; )
5282 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005283}
Guido van Rossum705f0f52001-08-24 16:47:00 +00005284
Michael W. Hudson98bbc492002-11-26 14:47:27 +00005285static void
5286update_all_slots(PyTypeObject* type)
5287{
5288 slotdef *p;
5289
5290 init_slotdefs();
5291 for (p = slotdefs; p->name; p++) {
5292 /* update_slot returns int but can't actually fail */
5293 update_slot(type, p->name_strobj);
5294 }
5295}
5296
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005297/* recurse_down_subclasses() and update_subclasses() are mutually
5298 recursive functions to call a callback for all subclasses,
5299 but refraining from recursing into subclasses that define 'name'. */
5300
5301static int
5302update_subclasses(PyTypeObject *type, PyObject *name,
5303 update_callback callback, void *data)
5304{
5305 if (callback(type, data) < 0)
5306 return -1;
5307 return recurse_down_subclasses(type, name, callback, data);
5308}
5309
5310static int
5311recurse_down_subclasses(PyTypeObject *type, PyObject *name,
5312 update_callback callback, void *data)
5313{
5314 PyTypeObject *subclass;
5315 PyObject *ref, *subclasses, *dict;
5316 int i, n;
5317
5318 subclasses = type->tp_subclasses;
5319 if (subclasses == NULL)
5320 return 0;
5321 assert(PyList_Check(subclasses));
5322 n = PyList_GET_SIZE(subclasses);
5323 for (i = 0; i < n; i++) {
5324 ref = PyList_GET_ITEM(subclasses, i);
5325 assert(PyWeakref_CheckRef(ref));
5326 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
5327 assert(subclass != NULL);
5328 if ((PyObject *)subclass == Py_None)
5329 continue;
5330 assert(PyType_Check(subclass));
5331 /* Avoid recursing down into unaffected classes */
5332 dict = subclass->tp_dict;
5333 if (dict != NULL && PyDict_Check(dict) &&
5334 PyDict_GetItem(dict, name) != NULL)
5335 continue;
5336 if (update_subclasses(subclass, name, callback, data) < 0)
5337 return -1;
5338 }
5339 return 0;
5340}
5341
Guido van Rossum6d204072001-10-21 00:44:31 +00005342/* This function is called by PyType_Ready() to populate the type's
5343 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00005344 function slot (like tp_repr) that's defined in the type, one or more
5345 corresponding descriptors are added in the type's tp_dict dictionary
5346 under the appropriate name (like __repr__). Some function slots
5347 cause more than one descriptor to be added (for example, the nb_add
5348 slot adds both __add__ and __radd__ descriptors) and some function
5349 slots compete for the same descriptor (for example both sq_item and
5350 mp_subscript generate a __getitem__ descriptor).
5351
5352 In the latter case, the first slotdef entry encoutered wins. Since
Tim Petersbf9b2442003-03-23 05:35:36 +00005353 slotdef entries are sorted by the offset of the slot in the
Guido van Rossume5c691a2003-03-07 15:13:17 +00005354 PyHeapTypeObject, this gives us some control over disambiguating
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005355 between competing slots: the members of PyHeapTypeObject are listed
5356 from most general to least general, so the most general slot is
5357 preferred. In particular, because as_mapping comes before as_sequence,
5358 for a type that defines both mp_subscript and sq_item, mp_subscript
5359 wins.
Guido van Rossum09638c12002-06-13 19:17:46 +00005360
5361 This only adds new descriptors and doesn't overwrite entries in
5362 tp_dict that were previously defined. The descriptors contain a
5363 reference to the C function they must call, so that it's safe if they
5364 are copied into a subtype's __dict__ and the subtype has a different
5365 C function in its slot -- calling the method defined by the
5366 descriptor will call the C function that was used to create it,
5367 rather than the C function present in the slot when it is called.
5368 (This is important because a subtype may have a C function in the
5369 slot that calls the method from the dictionary, and we want to avoid
5370 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00005371
5372static int
5373add_operators(PyTypeObject *type)
5374{
5375 PyObject *dict = type->tp_dict;
5376 slotdef *p;
5377 PyObject *descr;
5378 void **ptr;
5379
5380 init_slotdefs();
5381 for (p = slotdefs; p->name; p++) {
5382 if (p->wrapper == NULL)
5383 continue;
5384 ptr = slotptr(type, p->offset);
5385 if (!ptr || !*ptr)
5386 continue;
5387 if (PyDict_GetItem(dict, p->name_strobj))
5388 continue;
5389 descr = PyDescr_NewWrapper(type, p, *ptr);
5390 if (descr == NULL)
5391 return -1;
5392 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
5393 return -1;
5394 Py_DECREF(descr);
5395 }
5396 if (type->tp_new != NULL) {
5397 if (add_tp_new_wrapper(type) < 0)
5398 return -1;
5399 }
5400 return 0;
5401}
5402
Guido van Rossum705f0f52001-08-24 16:47:00 +00005403
5404/* Cooperative 'super' */
5405
5406typedef struct {
5407 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00005408 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005409 PyObject *obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005410 PyTypeObject *obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005411} superobject;
5412
Guido van Rossum6f799372001-09-20 20:46:19 +00005413static PyMemberDef super_members[] = {
5414 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
5415 "the class invoking super()"},
5416 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
5417 "the instance invoking super(); may be None"},
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005418 {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00005419 "the type of the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005420 {0}
5421};
5422
Guido van Rossum705f0f52001-08-24 16:47:00 +00005423static void
5424super_dealloc(PyObject *self)
5425{
5426 superobject *su = (superobject *)self;
5427
Guido van Rossum048eb752001-10-02 21:24:57 +00005428 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005429 Py_XDECREF(su->obj);
5430 Py_XDECREF(su->type);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005431 Py_XDECREF(su->obj_type);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005432 self->ob_type->tp_free(self);
5433}
5434
5435static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005436super_repr(PyObject *self)
5437{
5438 superobject *su = (superobject *)self;
5439
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005440 if (su->obj_type)
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005441 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005442 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005443 su->type ? su->type->tp_name : "NULL",
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005444 su->obj_type->tp_name);
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005445 else
5446 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005447 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005448 su->type ? su->type->tp_name : "NULL");
5449}
5450
5451static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00005452super_getattro(PyObject *self, PyObject *name)
5453{
5454 superobject *su = (superobject *)self;
Guido van Rossum76ba09f2003-04-16 19:40:58 +00005455 int skip = su->obj_type == NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005456
Guido van Rossum76ba09f2003-04-16 19:40:58 +00005457 if (!skip) {
5458 /* We want __class__ to return the class of the super object
5459 (i.e. super, or a subclass), not the class of su->obj. */
5460 skip = (PyString_Check(name) &&
5461 PyString_GET_SIZE(name) == 9 &&
5462 strcmp(PyString_AS_STRING(name), "__class__") == 0);
5463 }
5464
5465 if (!skip) {
Tim Petersa91e9642001-11-14 23:32:33 +00005466 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005467 PyTypeObject *starttype;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005468 descrgetfunc f;
5469 int i, n;
5470
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005471 starttype = su->obj_type;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005472 mro = starttype->tp_mro;
5473
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005474 if (mro == NULL)
5475 n = 0;
5476 else {
5477 assert(PyTuple_Check(mro));
5478 n = PyTuple_GET_SIZE(mro);
5479 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005480 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00005481 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00005482 break;
5483 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005484 i++;
5485 res = NULL;
5486 for (; i < n; i++) {
5487 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00005488 if (PyType_Check(tmp))
5489 dict = ((PyTypeObject *)tmp)->tp_dict;
5490 else if (PyClass_Check(tmp))
5491 dict = ((PyClassObject *)tmp)->cl_dict;
5492 else
5493 continue;
5494 res = PyDict_GetItem(dict, name);
Guido van Rossum6cc5bb62003-04-16 20:01:36 +00005495 if (res != NULL) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00005496 Py_INCREF(res);
5497 f = res->ob_type->tp_descr_get;
5498 if (f != NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00005499 tmp = f(res, su->obj,
5500 (PyObject *)starttype);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005501 Py_DECREF(res);
5502 res = tmp;
5503 }
5504 return res;
5505 }
5506 }
5507 }
5508 return PyObject_GenericGetAttr(self, name);
5509}
5510
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005511static PyTypeObject *
Guido van Rossum5b443c62001-12-03 15:38:28 +00005512supercheck(PyTypeObject *type, PyObject *obj)
5513{
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005514 /* Check that a super() call makes sense. Return a type object.
5515
5516 obj can be a new-style class, or an instance of one:
5517
5518 - If it is a class, it must be a subclass of 'type'. This case is
5519 used for class methods; the return value is obj.
5520
5521 - If it is an instance, it must be an instance of 'type'. This is
5522 the normal case; the return value is obj.__class__.
5523
5524 But... when obj is an instance, we want to allow for the case where
5525 obj->ob_type is not a subclass of type, but obj.__class__ is!
5526 This will allow using super() with a proxy for obj.
5527 */
5528
Guido van Rossum8e80a722003-02-18 19:22:22 +00005529 /* Check for first bullet above (special case) */
5530 if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
5531 Py_INCREF(obj);
5532 return (PyTypeObject *)obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005533 }
Guido van Rossum8e80a722003-02-18 19:22:22 +00005534
5535 /* Normal case */
5536 if (PyType_IsSubtype(obj->ob_type, type)) {
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005537 Py_INCREF(obj->ob_type);
5538 return obj->ob_type;
5539 }
5540 else {
5541 /* Try the slow way */
5542 static PyObject *class_str = NULL;
5543 PyObject *class_attr;
5544
5545 if (class_str == NULL) {
5546 class_str = PyString_FromString("__class__");
5547 if (class_str == NULL)
5548 return NULL;
5549 }
5550
5551 class_attr = PyObject_GetAttr(obj, class_str);
5552
5553 if (class_attr != NULL &&
5554 PyType_Check(class_attr) &&
5555 (PyTypeObject *)class_attr != obj->ob_type)
5556 {
5557 int ok = PyType_IsSubtype(
5558 (PyTypeObject *)class_attr, type);
5559 if (ok)
5560 return (PyTypeObject *)class_attr;
5561 }
5562
5563 if (class_attr == NULL)
5564 PyErr_Clear();
5565 else
5566 Py_DECREF(class_attr);
5567 }
5568
Tim Peters97e5ff52003-02-18 19:32:50 +00005569 PyErr_SetString(PyExc_TypeError,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005570 "super(type, obj): "
5571 "obj must be an instance or subtype of type");
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005572 return NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005573}
5574
Guido van Rossum705f0f52001-08-24 16:47:00 +00005575static PyObject *
5576super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5577{
5578 superobject *su = (superobject *)self;
5579 superobject *new;
5580
5581 if (obj == NULL || obj == Py_None || su->obj != NULL) {
5582 /* Not binding to an object, or already bound */
5583 Py_INCREF(self);
5584 return self;
5585 }
Guido van Rossum5b443c62001-12-03 15:38:28 +00005586 if (su->ob_type != &PySuper_Type)
Brett Cannon10147f72003-06-11 20:50:33 +00005587 /* If su is not an instance of a subclass of super,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005588 call its type */
5589 return PyObject_CallFunction((PyObject *)su->ob_type,
5590 "OO", su->type, obj);
5591 else {
5592 /* Inline the common case */
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005593 PyTypeObject *obj_type = supercheck(su->type, obj);
5594 if (obj_type == NULL)
Guido van Rossum5b443c62001-12-03 15:38:28 +00005595 return NULL;
5596 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
5597 NULL, NULL);
5598 if (new == NULL)
5599 return NULL;
5600 Py_INCREF(su->type);
5601 Py_INCREF(obj);
5602 new->type = su->type;
5603 new->obj = obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005604 new->obj_type = obj_type;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005605 return (PyObject *)new;
5606 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005607}
5608
5609static int
5610super_init(PyObject *self, PyObject *args, PyObject *kwds)
5611{
5612 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00005613 PyTypeObject *type;
5614 PyObject *obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005615 PyTypeObject *obj_type = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005616
5617 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
5618 return -1;
5619 if (obj == Py_None)
5620 obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005621 if (obj != NULL) {
5622 obj_type = supercheck(type, obj);
5623 if (obj_type == NULL)
5624 return -1;
5625 Py_INCREF(obj);
5626 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005627 Py_INCREF(type);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005628 su->type = type;
5629 su->obj = obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005630 su->obj_type = obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005631 return 0;
5632}
5633
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005634PyDoc_STRVAR(super_doc,
Guido van Rossum705f0f52001-08-24 16:47:00 +00005635"super(type) -> unbound super object\n"
5636"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00005637"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00005638"Typical use to call a cooperative superclass method:\n"
5639"class C(B):\n"
5640" def meth(self, arg):\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005641" super(C, self).meth(arg)");
Guido van Rossum705f0f52001-08-24 16:47:00 +00005642
Guido van Rossum048eb752001-10-02 21:24:57 +00005643static int
5644super_traverse(PyObject *self, visitproc visit, void *arg)
5645{
5646 superobject *su = (superobject *)self;
5647 int err;
5648
5649#define VISIT(SLOT) \
5650 if (SLOT) { \
5651 err = visit((PyObject *)(SLOT), arg); \
5652 if (err) \
5653 return err; \
5654 }
5655
5656 VISIT(su->obj);
5657 VISIT(su->type);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005658 VISIT(su->obj_type);
Guido van Rossum048eb752001-10-02 21:24:57 +00005659
5660#undef VISIT
5661
5662 return 0;
5663}
5664
Guido van Rossum705f0f52001-08-24 16:47:00 +00005665PyTypeObject PySuper_Type = {
5666 PyObject_HEAD_INIT(&PyType_Type)
5667 0, /* ob_size */
5668 "super", /* tp_name */
5669 sizeof(superobject), /* tp_basicsize */
5670 0, /* tp_itemsize */
5671 /* methods */
5672 super_dealloc, /* tp_dealloc */
5673 0, /* tp_print */
5674 0, /* tp_getattr */
5675 0, /* tp_setattr */
5676 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005677 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005678 0, /* tp_as_number */
5679 0, /* tp_as_sequence */
5680 0, /* tp_as_mapping */
5681 0, /* tp_hash */
5682 0, /* tp_call */
5683 0, /* tp_str */
5684 super_getattro, /* tp_getattro */
5685 0, /* tp_setattro */
5686 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00005687 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
5688 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005689 super_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00005690 super_traverse, /* tp_traverse */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005691 0, /* tp_clear */
5692 0, /* tp_richcompare */
5693 0, /* tp_weaklistoffset */
5694 0, /* tp_iter */
5695 0, /* tp_iternext */
5696 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005697 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005698 0, /* tp_getset */
5699 0, /* tp_base */
5700 0, /* tp_dict */
5701 super_descr_get, /* tp_descr_get */
5702 0, /* tp_descr_set */
5703 0, /* tp_dictoffset */
5704 super_init, /* tp_init */
5705 PyType_GenericAlloc, /* tp_alloc */
5706 PyType_GenericNew, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00005707 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005708};