blob: 3e1569763fd28f205cc3637165f6a452eb2ebf74 [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* Type object implementation */
2
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003#include "Python.h"
Tim Peters6d6c1a32001-08-02 04:15:00 +00004#include "structmember.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00005
Guido van Rossum9923ffe2002-06-04 19:52:53 +00006#include <ctype.h>
7
Guido van Rossum6f799372001-09-20 20:46:19 +00008static PyMemberDef type_members[] = {
Tim Peters6d6c1a32001-08-02 04:15:00 +00009 {"__basicsize__", T_INT, offsetof(PyTypeObject,tp_basicsize),READONLY},
10 {"__itemsize__", T_INT, offsetof(PyTypeObject, tp_itemsize), READONLY},
11 {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY},
Guido van Rossum9676b222001-08-17 20:32:36 +000012 {"__weakrefoffset__", T_LONG,
Tim Peters6d6c1a32001-08-02 04:15:00 +000013 offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
14 {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY},
15 {"__dictoffset__", T_LONG,
16 offsetof(PyTypeObject, tp_dictoffset), READONLY},
Tim Peters6d6c1a32001-08-02 04:15:00 +000017 {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY},
18 {0}
19};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000020
Guido van Rossumc0b618a1997-05-02 03:12:38 +000021static PyObject *
Guido van Rossumc3542212001-08-16 09:18:56 +000022type_name(PyTypeObject *type, void *context)
23{
24 char *s;
25
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +000026 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
Guido van Rossume5c691a2003-03-07 15:13:17 +000027 PyHeapTypeObject* et = (PyHeapTypeObject*)type;
Tim Petersea7f75d2002-12-07 21:39:16 +000028
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +000029 Py_INCREF(et->name);
30 return et->name;
31 }
32 else {
33 s = strrchr(type->tp_name, '.');
34 if (s == NULL)
35 s = type->tp_name;
36 else
37 s++;
38 return PyString_FromString(s);
39 }
Guido van Rossumc3542212001-08-16 09:18:56 +000040}
41
Michael W. Hudson98bbc492002-11-26 14:47:27 +000042static int
43type_set_name(PyTypeObject *type, PyObject *value, void *context)
44{
Guido van Rossume5c691a2003-03-07 15:13:17 +000045 PyHeapTypeObject* et;
Michael W. Hudson98bbc492002-11-26 14:47:27 +000046
47 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
48 PyErr_Format(PyExc_TypeError,
49 "can't set %s.__name__", type->tp_name);
50 return -1;
51 }
52 if (!value) {
53 PyErr_Format(PyExc_TypeError,
54 "can't delete %s.__name__", type->tp_name);
55 return -1;
56 }
57 if (!PyString_Check(value)) {
58 PyErr_Format(PyExc_TypeError,
59 "can only assign string to %s.__name__, not '%s'",
60 type->tp_name, value->ob_type->tp_name);
61 return -1;
62 }
Tim Petersea7f75d2002-12-07 21:39:16 +000063 if (strlen(PyString_AS_STRING(value))
Michael W. Hudson98bbc492002-11-26 14:47:27 +000064 != (size_t)PyString_GET_SIZE(value)) {
65 PyErr_Format(PyExc_ValueError,
66 "__name__ must not contain null bytes");
67 return -1;
68 }
69
Guido van Rossume5c691a2003-03-07 15:13:17 +000070 et = (PyHeapTypeObject*)type;
Michael W. Hudson98bbc492002-11-26 14:47:27 +000071
72 Py_INCREF(value);
73
74 Py_DECREF(et->name);
75 et->name = value;
76
77 type->tp_name = PyString_AS_STRING(value);
78
79 return 0;
80}
81
Guido van Rossumc3542212001-08-16 09:18:56 +000082static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +000083type_module(PyTypeObject *type, void *context)
Guido van Rossum29ca26e1995-01-07 11:58:15 +000084{
Guido van Rossumc3542212001-08-16 09:18:56 +000085 PyObject *mod;
86 char *s;
87
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +000088 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
89 mod = PyDict_GetItemString(type->tp_dict, "__module__");
90 Py_XINCREF(mod);
Guido van Rossumc3542212001-08-16 09:18:56 +000091 return mod;
92 }
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +000093 else {
94 s = strrchr(type->tp_name, '.');
95 if (s != NULL)
96 return PyString_FromStringAndSize(
97 type->tp_name, (int)(s - type->tp_name));
98 return PyString_FromString("__builtin__");
99 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000100}
101
Guido van Rossum3926a632001-09-25 16:25:58 +0000102static int
103type_set_module(PyTypeObject *type, PyObject *value, void *context)
104{
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000105 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
Guido van Rossum3926a632001-09-25 16:25:58 +0000106 PyErr_Format(PyExc_TypeError,
107 "can't set %s.__module__", type->tp_name);
108 return -1;
109 }
110 if (!value) {
111 PyErr_Format(PyExc_TypeError,
112 "can't delete %s.__module__", type->tp_name);
113 return -1;
114 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000115
Guido van Rossum3926a632001-09-25 16:25:58 +0000116 return PyDict_SetItemString(type->tp_dict, "__module__", value);
117}
118
Tim Peters6d6c1a32001-08-02 04:15:00 +0000119static PyObject *
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000120type_get_bases(PyTypeObject *type, void *context)
121{
122 Py_INCREF(type->tp_bases);
123 return type->tp_bases;
124}
125
126static PyTypeObject *best_base(PyObject *);
127static int mro_internal(PyTypeObject *);
128static int compatible_for_assignment(PyTypeObject *, PyTypeObject *, char *);
129static int add_subclass(PyTypeObject*, PyTypeObject*);
130static void remove_subclass(PyTypeObject *, PyTypeObject *);
131static void update_all_slots(PyTypeObject *);
132
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000133typedef int (*update_callback)(PyTypeObject *, void *);
134static int update_subclasses(PyTypeObject *type, PyObject *name,
135 update_callback callback, void *data);
136static int recurse_down_subclasses(PyTypeObject *type, PyObject *name,
137 update_callback callback, void *data);
138
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000139static int
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000140mro_subclasses(PyTypeObject *type, PyObject* temp)
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000141{
142 PyTypeObject *subclass;
143 PyObject *ref, *subclasses, *old_mro;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000144 int i, n;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000145
146 subclasses = type->tp_subclasses;
147 if (subclasses == NULL)
148 return 0;
149 assert(PyList_Check(subclasses));
150 n = PyList_GET_SIZE(subclasses);
151 for (i = 0; i < n; i++) {
152 ref = PyList_GET_ITEM(subclasses, i);
153 assert(PyWeakref_CheckRef(ref));
154 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
155 assert(subclass != NULL);
156 if ((PyObject *)subclass == Py_None)
157 continue;
158 assert(PyType_Check(subclass));
159 old_mro = subclass->tp_mro;
160 if (mro_internal(subclass) < 0) {
161 subclass->tp_mro = old_mro;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000162 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000163 }
164 else {
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000165 PyObject* tuple;
166 tuple = Py_BuildValue("OO", subclass, old_mro);
Guido van Rossum19a02ba2003-04-15 22:09:45 +0000167 Py_DECREF(old_mro);
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000168 if (!tuple)
169 return -1;
170 if (PyList_Append(temp, tuple) < 0)
171 return -1;
Guido van Rossum19a02ba2003-04-15 22:09:45 +0000172 Py_DECREF(tuple);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000173 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000174 if (mro_subclasses(subclass, temp) < 0)
175 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000176 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000177 return 0;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000178}
179
180static int
181type_set_bases(PyTypeObject *type, PyObject *value, void *context)
182{
183 int i, r = 0;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000184 PyObject *ob, *temp;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000185 PyTypeObject *new_base, *old_base;
186 PyObject *old_bases, *old_mro;
187
188 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
189 PyErr_Format(PyExc_TypeError,
190 "can't set %s.__bases__", type->tp_name);
191 return -1;
192 }
193 if (!value) {
194 PyErr_Format(PyExc_TypeError,
195 "can't delete %s.__bases__", type->tp_name);
196 return -1;
197 }
198 if (!PyTuple_Check(value)) {
199 PyErr_Format(PyExc_TypeError,
200 "can only assign tuple to %s.__bases__, not %s",
201 type->tp_name, value->ob_type->tp_name);
202 return -1;
203 }
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +0000204 if (PyTuple_GET_SIZE(value) == 0) {
205 PyErr_Format(PyExc_TypeError,
206 "can only assign non-empty tuple to %s.__bases__, not ()",
207 type->tp_name);
208 return -1;
209 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000210 for (i = 0; i < PyTuple_GET_SIZE(value); i++) {
211 ob = PyTuple_GET_ITEM(value, i);
212 if (!PyClass_Check(ob) && !PyType_Check(ob)) {
213 PyErr_Format(
214 PyExc_TypeError,
215 "%s.__bases__ must be tuple of old- or new-style classes, not '%s'",
216 type->tp_name, ob->ob_type->tp_name);
217 return -1;
218 }
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +0000219 if (PyType_Check(ob)) {
220 if (PyType_IsSubtype((PyTypeObject*)ob, type)) {
221 PyErr_SetString(PyExc_TypeError,
222 "a __bases__ item causes an inheritance cycle");
223 return -1;
224 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000225 }
226 }
227
228 new_base = best_base(value);
229
230 if (!new_base) {
231 return -1;
232 }
233
234 if (!compatible_for_assignment(type->tp_base, new_base, "__bases__"))
235 return -1;
236
237 Py_INCREF(new_base);
238 Py_INCREF(value);
239
240 old_bases = type->tp_bases;
241 old_base = type->tp_base;
242 old_mro = type->tp_mro;
243
244 type->tp_bases = value;
245 type->tp_base = new_base;
246
247 if (mro_internal(type) < 0) {
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000248 goto bail;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000249 }
250
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000251 temp = PyList_New(0);
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000252 if (!temp)
253 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000254
255 r = mro_subclasses(type, temp);
256
257 if (r < 0) {
258 for (i = 0; i < PyList_Size(temp); i++) {
259 PyTypeObject* cls;
260 PyObject* mro;
Guido van Rossum19a02ba2003-04-15 22:09:45 +0000261 PyArg_ParseTuple(PyList_GET_ITEM(temp, i),
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000262 "OO", &cls, &mro);
263 Py_DECREF(cls->tp_mro);
264 cls->tp_mro = mro;
265 Py_INCREF(cls->tp_mro);
266 }
267 Py_DECREF(temp);
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000268 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000269 }
270
271 Py_DECREF(temp);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000272
273 /* any base that was in __bases__ but now isn't, we
Raymond Hettingera8285862002-12-14 17:17:56 +0000274 need to remove |type| from its tp_subclasses.
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000275 conversely, any class now in __bases__ that wasn't
Raymond Hettingera8285862002-12-14 17:17:56 +0000276 needs to have |type| added to its subclasses. */
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000277
278 /* for now, sod that: just remove from all old_bases,
279 add to all new_bases */
280
281 for (i = PyTuple_GET_SIZE(old_bases) - 1; i >= 0; i--) {
282 ob = PyTuple_GET_ITEM(old_bases, i);
283 if (PyType_Check(ob)) {
284 remove_subclass(
285 (PyTypeObject*)ob, type);
286 }
287 }
288
289 for (i = PyTuple_GET_SIZE(value) - 1; i >= 0; i--) {
290 ob = PyTuple_GET_ITEM(value, i);
291 if (PyType_Check(ob)) {
292 if (add_subclass((PyTypeObject*)ob, type) < 0)
293 r = -1;
294 }
295 }
296
297 update_all_slots(type);
298
299 Py_DECREF(old_bases);
300 Py_DECREF(old_base);
301 Py_DECREF(old_mro);
302
303 return r;
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000304
305 bail:
306 type->tp_bases = old_bases;
307 type->tp_base = old_base;
308 type->tp_mro = old_mro;
Tim Petersea7f75d2002-12-07 21:39:16 +0000309
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000310 Py_DECREF(value);
311 Py_DECREF(new_base);
Tim Petersea7f75d2002-12-07 21:39:16 +0000312
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000313 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000314}
315
316static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000317type_dict(PyTypeObject *type, void *context)
318{
319 if (type->tp_dict == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000320 Py_INCREF(Py_None);
321 return Py_None;
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000322 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000323 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000324}
325
Tim Peters24008312002-03-17 18:56:20 +0000326static PyObject *
327type_get_doc(PyTypeObject *type, void *context)
328{
329 PyObject *result;
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000330 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL)
Tim Peters24008312002-03-17 18:56:20 +0000331 return PyString_FromString(type->tp_doc);
Tim Peters24008312002-03-17 18:56:20 +0000332 result = PyDict_GetItemString(type->tp_dict, "__doc__");
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000333 if (result == NULL) {
334 result = Py_None;
335 Py_INCREF(result);
336 }
337 else if (result->ob_type->tp_descr_get) {
Tim Peters2b858972002-04-18 04:12:28 +0000338 result = result->ob_type->tp_descr_get(result, NULL,
339 (PyObject *)type);
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000340 }
341 else {
342 Py_INCREF(result);
343 }
Tim Peters24008312002-03-17 18:56:20 +0000344 return result;
345}
346
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000347static PyGetSetDef type_getsets[] = {
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000348 {"__name__", (getter)type_name, (setter)type_set_name, NULL},
349 {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL},
Guido van Rossum3926a632001-09-25 16:25:58 +0000350 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000351 {"__dict__", (getter)type_dict, NULL, NULL},
Tim Peters24008312002-03-17 18:56:20 +0000352 {"__doc__", (getter)type_get_doc, NULL, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000353 {0}
354};
355
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000356static int
357type_compare(PyObject *v, PyObject *w)
358{
359 /* This is called with type objects only. So we
360 can just compare the addresses. */
361 Py_uintptr_t vv = (Py_uintptr_t)v;
362 Py_uintptr_t ww = (Py_uintptr_t)w;
363 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
364}
365
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000366static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000367type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000368{
Barry Warsaw7ce36942001-08-24 18:34:26 +0000369 PyObject *mod, *name, *rtn;
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000370 char *kind;
Guido van Rossumc3542212001-08-16 09:18:56 +0000371
372 mod = type_module(type, NULL);
373 if (mod == NULL)
374 PyErr_Clear();
375 else if (!PyString_Check(mod)) {
376 Py_DECREF(mod);
377 mod = NULL;
378 }
379 name = type_name(type, NULL);
380 if (name == NULL)
381 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000382
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000383 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
384 kind = "class";
385 else
386 kind = "type";
387
Barry Warsaw7ce36942001-08-24 18:34:26 +0000388 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__")) {
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000389 rtn = PyString_FromFormat("<%s '%s.%s'>",
390 kind,
Barry Warsaw7ce36942001-08-24 18:34:26 +0000391 PyString_AS_STRING(mod),
392 PyString_AS_STRING(name));
393 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000394 else
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000395 rtn = PyString_FromFormat("<%s '%s'>", kind, type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000396
Guido van Rossumc3542212001-08-16 09:18:56 +0000397 Py_XDECREF(mod);
398 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000399 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000400}
401
Tim Peters6d6c1a32001-08-02 04:15:00 +0000402static PyObject *
403type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
404{
405 PyObject *obj;
406
407 if (type->tp_new == NULL) {
408 PyErr_Format(PyExc_TypeError,
409 "cannot create '%.100s' instances",
410 type->tp_name);
411 return NULL;
412 }
413
Tim Peters3f996e72001-09-13 19:18:27 +0000414 obj = type->tp_new(type, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000415 if (obj != NULL) {
Guido van Rossumf76de622001-10-18 15:49:21 +0000416 /* Ugly exception: when the call was type(something),
417 don't call tp_init on the result. */
418 if (type == &PyType_Type &&
419 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
420 (kwds == NULL ||
421 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
422 return obj;
Guido van Rossum8ace1ab2002-04-06 01:05:01 +0000423 /* If the returned object is not an instance of type,
424 it won't be initialized. */
425 if (!PyType_IsSubtype(obj->ob_type, type))
426 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000427 type = obj->ob_type;
Jeremy Hylton719841e2002-07-16 19:39:38 +0000428 if (PyType_HasFeature(type, Py_TPFLAGS_HAVE_CLASS) &&
429 type->tp_init != NULL &&
Tim Peters6d6c1a32001-08-02 04:15:00 +0000430 type->tp_init(obj, args, kwds) < 0) {
431 Py_DECREF(obj);
432 obj = NULL;
433 }
434 }
435 return obj;
436}
437
438PyObject *
439PyType_GenericAlloc(PyTypeObject *type, int nitems)
440{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000441 PyObject *obj;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000442 const size_t size = _PyObject_VAR_SIZE(type, nitems+1);
443 /* note that we need to add one, for the sentinel */
Tim Peters406fe3b2001-10-06 19:04:01 +0000444
445 if (PyType_IS_GC(type))
Neil Schemenauer09a2ae52002-04-12 03:06:53 +0000446 obj = _PyObject_GC_Malloc(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000447 else
Neil Schemenauerc806c882001-08-29 23:54:54 +0000448 obj = PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000449
Neil Schemenauerc806c882001-08-29 23:54:54 +0000450 if (obj == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000451 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000452
Neil Schemenauerc806c882001-08-29 23:54:54 +0000453 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000454
Tim Peters6d6c1a32001-08-02 04:15:00 +0000455 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
456 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000457
Tim Peters6d6c1a32001-08-02 04:15:00 +0000458 if (type->tp_itemsize == 0)
459 PyObject_INIT(obj, type);
460 else
461 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000462
Tim Peters6d6c1a32001-08-02 04:15:00 +0000463 if (PyType_IS_GC(type))
Neil Schemenauerc806c882001-08-29 23:54:54 +0000464 _PyObject_GC_TRACK(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000465 return obj;
466}
467
468PyObject *
469PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
470{
471 return type->tp_alloc(type, 0);
472}
473
Guido van Rossum9475a232001-10-05 20:51:39 +0000474/* Helpers for subtyping */
475
476static int
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000477traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
478{
479 int i, n;
480 PyMemberDef *mp;
481
482 n = type->ob_size;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000483 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000484 for (i = 0; i < n; i++, mp++) {
485 if (mp->type == T_OBJECT_EX) {
486 char *addr = (char *)self + mp->offset;
487 PyObject *obj = *(PyObject **)addr;
488 if (obj != NULL) {
489 int err = visit(obj, arg);
490 if (err)
491 return err;
492 }
493 }
494 }
495 return 0;
496}
497
498static int
Guido van Rossum9475a232001-10-05 20:51:39 +0000499subtype_traverse(PyObject *self, visitproc visit, void *arg)
500{
501 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000502 traverseproc basetraverse;
Guido van Rossum9475a232001-10-05 20:51:39 +0000503
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000504 /* Find the nearest base with a different tp_traverse,
505 and traverse slots while we're at it */
Guido van Rossum9475a232001-10-05 20:51:39 +0000506 type = self->ob_type;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000507 base = type;
508 while ((basetraverse = base->tp_traverse) == subtype_traverse) {
509 if (base->ob_size) {
510 int err = traverse_slots(base, self, visit, arg);
511 if (err)
512 return err;
513 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000514 base = base->tp_base;
515 assert(base);
516 }
517
518 if (type->tp_dictoffset != base->tp_dictoffset) {
519 PyObject **dictptr = _PyObject_GetDictPtr(self);
520 if (dictptr && *dictptr) {
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000521 int err = visit(*dictptr, arg);
Guido van Rossum9475a232001-10-05 20:51:39 +0000522 if (err)
523 return err;
524 }
525 }
526
Guido van Rossuma3862092002-06-10 15:24:42 +0000527 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
528 /* For a heaptype, the instances count as references
529 to the type. Traverse the type so the collector
530 can find cycles involving this link. */
531 int err = visit((PyObject *)type, arg);
532 if (err)
533 return err;
534 }
535
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000536 if (basetraverse)
537 return basetraverse(self, visit, arg);
538 return 0;
539}
540
541static void
542clear_slots(PyTypeObject *type, PyObject *self)
543{
544 int i, n;
545 PyMemberDef *mp;
546
547 n = type->ob_size;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000548 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000549 for (i = 0; i < n; i++, mp++) {
550 if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
551 char *addr = (char *)self + mp->offset;
552 PyObject *obj = *(PyObject **)addr;
553 if (obj != NULL) {
554 Py_DECREF(obj);
555 *(PyObject **)addr = NULL;
556 }
557 }
558 }
559}
560
561static int
562subtype_clear(PyObject *self)
563{
564 PyTypeObject *type, *base;
565 inquiry baseclear;
566
567 /* Find the nearest base with a different tp_clear
568 and clear slots while we're at it */
569 type = self->ob_type;
570 base = type;
571 while ((baseclear = base->tp_clear) == subtype_clear) {
572 if (base->ob_size)
573 clear_slots(base, self);
574 base = base->tp_base;
575 assert(base);
576 }
577
Guido van Rossuma3862092002-06-10 15:24:42 +0000578 /* There's no need to clear the instance dict (if any);
579 the collector will call its tp_clear handler. */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000580
581 if (baseclear)
582 return baseclear(self);
Guido van Rossum9475a232001-10-05 20:51:39 +0000583 return 0;
584}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000585
586static void
587subtype_dealloc(PyObject *self)
588{
Guido van Rossum14227b42001-12-06 02:35:58 +0000589 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000590 destructor basedealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000591
Guido van Rossum22b13872002-08-06 21:41:44 +0000592 /* Extract the type; we expect it to be a heap type */
593 type = self->ob_type;
594 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000595
Guido van Rossum22b13872002-08-06 21:41:44 +0000596 /* Test whether the type has GC exactly once */
597
598 if (!PyType_IS_GC(type)) {
599 /* It's really rare to find a dynamic type that doesn't have
600 GC; it can only happen when deriving from 'object' and not
601 adding any slots or instance variables. This allows
602 certain simplifications: there's no need to call
603 clear_slots(), or DECREF the dict, or clear weakrefs. */
604
605 /* Maybe call finalizer; exit early if resurrected */
Guido van Rossumfebd61d2002-08-08 20:55:20 +0000606 if (type->tp_del) {
607 type->tp_del(self);
608 if (self->ob_refcnt > 0)
609 return;
610 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000611
612 /* Find the nearest base with a different tp_dealloc */
613 base = type;
614 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
615 assert(base->ob_size == 0);
616 base = base->tp_base;
617 assert(base);
618 }
619
620 /* Call the base tp_dealloc() */
621 assert(basedealloc);
622 basedealloc(self);
623
624 /* Can't reference self beyond this point */
625 Py_DECREF(type);
626
627 /* Done */
628 return;
629 }
630
631 /* We get here only if the type has GC */
632
633 /* UnTrack and re-Track around the trashcan macro, alas */
Andrew M. Kuchlingc9172d32003-02-06 15:22:49 +0000634 /* See explanation at end of function for full disclosure */
Guido van Rossum0906e072002-08-07 20:42:09 +0000635 PyObject_GC_UnTrack(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000636 ++_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000637 Py_TRASHCAN_SAFE_BEGIN(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000638 --_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000639 _PyObject_GC_TRACK(self); /* We'll untrack for real later */
640
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000641 /* Find the nearest base with a different tp_dealloc
642 and clear slots while we're at it */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000643 base = type;
644 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
645 if (base->ob_size)
646 clear_slots(base, self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000647 base = base->tp_base;
648 assert(base);
Guido van Rossum14227b42001-12-06 02:35:58 +0000649 }
650
Guido van Rossum1987c662003-05-29 14:29:23 +0000651 /* If we added a weaklist, we clear it. Do this *before* calling
652 the finalizer (__del__) or clearing the instance dict. */
653 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
654 PyObject_ClearWeakRefs(self);
655
656 /* Maybe call finalizer; exit early if resurrected */
657 if (type->tp_del) {
658 type->tp_del(self);
659 if (self->ob_refcnt > 0)
660 goto endlabel;
661 }
662
Tim Peters6d6c1a32001-08-02 04:15:00 +0000663 /* If we added a dict, DECREF it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000664 if (type->tp_dictoffset && !base->tp_dictoffset) {
665 PyObject **dictptr = _PyObject_GetDictPtr(self);
666 if (dictptr != NULL) {
667 PyObject *dict = *dictptr;
668 if (dict != NULL) {
669 Py_DECREF(dict);
670 *dictptr = NULL;
671 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000672 }
673 }
674
675 /* Finalize GC if the base doesn't do GC and we do */
Guido van Rossum22b13872002-08-06 21:41:44 +0000676 if (!PyType_IS_GC(base))
Guido van Rossum048eb752001-10-02 21:24:57 +0000677 _PyObject_GC_UNTRACK(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000678
679 /* Call the base tp_dealloc() */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000680 assert(basedealloc);
681 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000682
683 /* Can't reference self beyond this point */
Guido van Rossum22b13872002-08-06 21:41:44 +0000684 Py_DECREF(type);
685
Guido van Rossum0906e072002-08-07 20:42:09 +0000686 endlabel:
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000687 ++_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000688 Py_TRASHCAN_SAFE_END(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000689 --_PyTrash_delete_nesting;
690
691 /* Explanation of the weirdness around the trashcan macros:
692
693 Q. What do the trashcan macros do?
694
695 A. Read the comment titled "Trashcan mechanism" in object.h.
696 For one, this explains why there must be a call to GC-untrack
697 before the trashcan begin macro. Without understanding the
698 trashcan code, the answers to the following questions don't make
699 sense.
700
701 Q. Why do we GC-untrack before the trashcan and then immediately
702 GC-track again afterward?
703
704 A. In the case that the base class is GC-aware, the base class
705 probably GC-untracks the object. If it does that using the
706 UNTRACK macro, this will crash when the object is already
707 untracked. Because we don't know what the base class does, the
708 only safe thing is to make sure the object is tracked when we
709 call the base class dealloc. But... The trashcan begin macro
710 requires that the object is *untracked* before it is called. So
711 the dance becomes:
712
713 GC untrack
714 trashcan begin
715 GC track
716
717 Q. Why the bizarre (net-zero) manipulation of
718 _PyTrash_delete_nesting around the trashcan macros?
719
720 A. Some base classes (e.g. list) also use the trashcan mechanism.
721 The following scenario used to be possible:
722
723 - suppose the trashcan level is one below the trashcan limit
724
725 - subtype_dealloc() is called
726
727 - the trashcan limit is not yet reached, so the trashcan level
728 is incremented and the code between trashcan begin and end is
729 executed
730
731 - this destroys much of the object's contents, including its
732 slots and __dict__
733
734 - basedealloc() is called; this is really list_dealloc(), or
735 some other type which also uses the trashcan macros
736
737 - the trashcan limit is now reached, so the object is put on the
738 trashcan's to-be-deleted-later list
739
740 - basedealloc() returns
741
742 - subtype_dealloc() decrefs the object's type
743
744 - subtype_dealloc() returns
745
746 - later, the trashcan code starts deleting the objects from its
747 to-be-deleted-later list
748
749 - subtype_dealloc() is called *AGAIN* for the same object
750
751 - at the very least (if the destroyed slots and __dict__ don't
752 cause problems) the object's type gets decref'ed a second
753 time, which is *BAD*!!!
754
755 The remedy is to make sure that if the code between trashcan
756 begin and end in subtype_dealloc() is called, the code between
757 trashcan begin and end in basedealloc() will also be called.
758 This is done by decrementing the level after passing into the
759 trashcan block, and incrementing it just before leaving the
760 block.
761
762 But now it's possible that a chain of objects consisting solely
763 of objects whose deallocator is subtype_dealloc() will defeat
764 the trashcan mechanism completely: the decremented level means
765 that the effective level never reaches the limit. Therefore, we
766 *increment* the level *before* entering the trashcan block, and
767 matchingly decrement it after leaving. This means the trashcan
768 code will trigger a little early, but that's no big deal.
769
770 Q. Are there any live examples of code in need of all this
771 complexity?
772
773 A. Yes. See SF bug 668433 for code that crashed (when Python was
774 compiled in debug mode) before the trashcan level manipulations
775 were added. For more discussion, see SF patches 581742, 575073
776 and bug 574207.
777 */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000778}
779
Jeremy Hylton938ace62002-07-17 16:30:39 +0000780static PyTypeObject *solid_base(PyTypeObject *type);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000781
Tim Peters6d6c1a32001-08-02 04:15:00 +0000782/* type test with subclassing support */
783
784int
785PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
786{
787 PyObject *mro;
788
Guido van Rossum9478d072001-09-07 18:52:13 +0000789 if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
790 return b == a || b == &PyBaseObject_Type;
791
Tim Peters6d6c1a32001-08-02 04:15:00 +0000792 mro = a->tp_mro;
793 if (mro != NULL) {
794 /* Deal with multiple inheritance without recursion
795 by walking the MRO tuple */
796 int i, n;
797 assert(PyTuple_Check(mro));
798 n = PyTuple_GET_SIZE(mro);
799 for (i = 0; i < n; i++) {
800 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
801 return 1;
802 }
803 return 0;
804 }
805 else {
806 /* a is not completely initilized yet; follow tp_base */
807 do {
808 if (a == b)
809 return 1;
810 a = a->tp_base;
811 } while (a != NULL);
812 return b == &PyBaseObject_Type;
813 }
814}
815
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000816/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +0000817 without looking in the instance dictionary
818 (so we can't use PyObject_GetAttr) but still binding
819 it to the instance. The arguments are the object,
820 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000821 static variable used to cache the interned Python string.
822
823 Two variants:
824
825 - lookup_maybe() returns NULL without raising an exception
826 when the _PyType_Lookup() call fails;
827
828 - lookup_method() always raises an exception upon errors.
829*/
Guido van Rossum60718732001-08-28 17:47:51 +0000830
831static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000832lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +0000833{
834 PyObject *res;
835
836 if (*attrobj == NULL) {
837 *attrobj = PyString_InternFromString(attrstr);
838 if (*attrobj == NULL)
839 return NULL;
840 }
841 res = _PyType_Lookup(self->ob_type, *attrobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000842 if (res != NULL) {
Guido van Rossum60718732001-08-28 17:47:51 +0000843 descrgetfunc f;
844 if ((f = res->ob_type->tp_descr_get) == NULL)
845 Py_INCREF(res);
846 else
847 res = f(res, self, (PyObject *)(self->ob_type));
848 }
849 return res;
850}
851
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000852static PyObject *
853lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
854{
855 PyObject *res = lookup_maybe(self, attrstr, attrobj);
856 if (res == NULL && !PyErr_Occurred())
857 PyErr_SetObject(PyExc_AttributeError, *attrobj);
858 return res;
859}
860
Guido van Rossum2730b132001-08-28 18:22:14 +0000861/* A variation of PyObject_CallMethod that uses lookup_method()
862 instead of PyObject_GetAttrString(). This uses the same convention
863 as lookup_method to cache the interned name string object. */
864
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000865static PyObject *
Guido van Rossum2730b132001-08-28 18:22:14 +0000866call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
867{
868 va_list va;
869 PyObject *args, *func = 0, *retval;
Guido van Rossum2730b132001-08-28 18:22:14 +0000870 va_start(va, format);
871
Guido van Rossumda21c012001-10-03 00:50:18 +0000872 func = lookup_maybe(o, name, nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000873 if (func == NULL) {
874 va_end(va);
875 if (!PyErr_Occurred())
Guido van Rossumda21c012001-10-03 00:50:18 +0000876 PyErr_SetObject(PyExc_AttributeError, *nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000877 return NULL;
878 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000879
880 if (format && *format)
881 args = Py_VaBuildValue(format, va);
882 else
883 args = PyTuple_New(0);
884
885 va_end(va);
886
887 if (args == NULL)
888 return NULL;
889
890 assert(PyTuple_Check(args));
891 retval = PyObject_Call(func, args, NULL);
892
893 Py_DECREF(args);
894 Py_DECREF(func);
895
896 return retval;
897}
898
899/* Clone of call_method() that returns NotImplemented when the lookup fails. */
900
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000901static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000902call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
903{
904 va_list va;
905 PyObject *args, *func = 0, *retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000906 va_start(va, format);
907
Guido van Rossumda21c012001-10-03 00:50:18 +0000908 func = lookup_maybe(o, name, nameobj);
Guido van Rossum2730b132001-08-28 18:22:14 +0000909 if (func == NULL) {
910 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000911 if (!PyErr_Occurred()) {
912 Py_INCREF(Py_NotImplemented);
913 return Py_NotImplemented;
914 }
Guido van Rossum717ce002001-09-14 16:58:08 +0000915 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +0000916 }
917
918 if (format && *format)
919 args = Py_VaBuildValue(format, va);
920 else
921 args = PyTuple_New(0);
922
923 va_end(va);
924
Guido van Rossum717ce002001-09-14 16:58:08 +0000925 if (args == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +0000926 return NULL;
927
Guido van Rossum717ce002001-09-14 16:58:08 +0000928 assert(PyTuple_Check(args));
929 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +0000930
931 Py_DECREF(args);
932 Py_DECREF(func);
933
934 return retval;
935}
936
Tim Petersa91e9642001-11-14 23:32:33 +0000937static int
938fill_classic_mro(PyObject *mro, PyObject *cls)
939{
940 PyObject *bases, *base;
941 int i, n;
942
943 assert(PyList_Check(mro));
944 assert(PyClass_Check(cls));
945 i = PySequence_Contains(mro, cls);
946 if (i < 0)
947 return -1;
948 if (!i) {
949 if (PyList_Append(mro, cls) < 0)
950 return -1;
951 }
952 bases = ((PyClassObject *)cls)->cl_bases;
953 assert(bases && PyTuple_Check(bases));
954 n = PyTuple_GET_SIZE(bases);
955 for (i = 0; i < n; i++) {
956 base = PyTuple_GET_ITEM(bases, i);
957 if (fill_classic_mro(mro, base) < 0)
958 return -1;
959 }
960 return 0;
961}
962
963static PyObject *
964classic_mro(PyObject *cls)
965{
966 PyObject *mro;
967
968 assert(PyClass_Check(cls));
969 mro = PyList_New(0);
970 if (mro != NULL) {
971 if (fill_classic_mro(mro, cls) == 0)
972 return mro;
973 Py_DECREF(mro);
974 }
975 return NULL;
976}
977
Tim Petersea7f75d2002-12-07 21:39:16 +0000978/*
Guido van Rossum1f121312002-11-14 19:49:16 +0000979 Method resolution order algorithm C3 described in
980 "A Monotonic Superclass Linearization for Dylan",
981 by Kim Barrett, Bob Cassel, Paul Haahr,
Tim Petersea7f75d2002-12-07 21:39:16 +0000982 David A. Moon, Keith Playford, and P. Tucker Withington.
Guido van Rossum1f121312002-11-14 19:49:16 +0000983 (OOPSLA 1996)
984
Guido van Rossum98f33732002-11-25 21:36:54 +0000985 Some notes about the rules implied by C3:
986
Tim Petersea7f75d2002-12-07 21:39:16 +0000987 No duplicate bases.
Guido van Rossum98f33732002-11-25 21:36:54 +0000988 It isn't legal to repeat a class in a list of base classes.
989
990 The next three properties are the 3 constraints in "C3".
991
Tim Petersea7f75d2002-12-07 21:39:16 +0000992 Local precendece order.
Guido van Rossum98f33732002-11-25 21:36:54 +0000993 If A precedes B in C's MRO, then A will precede B in the MRO of all
994 subclasses of C.
995
996 Monotonicity.
997 The MRO of a class must be an extension without reordering of the
998 MRO of each of its superclasses.
999
1000 Extended Precedence Graph (EPG).
1001 Linearization is consistent if there is a path in the EPG from
1002 each class to all its successors in the linearization. See
1003 the paper for definition of EPG.
Guido van Rossum1f121312002-11-14 19:49:16 +00001004 */
1005
Tim Petersea7f75d2002-12-07 21:39:16 +00001006static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001007tail_contains(PyObject *list, int whence, PyObject *o) {
1008 int j, size;
1009 size = PyList_GET_SIZE(list);
1010
1011 for (j = whence+1; j < size; j++) {
1012 if (PyList_GET_ITEM(list, j) == o)
1013 return 1;
1014 }
1015 return 0;
1016}
1017
Guido van Rossum98f33732002-11-25 21:36:54 +00001018static PyObject *
1019class_name(PyObject *cls)
1020{
1021 PyObject *name = PyObject_GetAttrString(cls, "__name__");
1022 if (name == NULL) {
1023 PyErr_Clear();
1024 Py_XDECREF(name);
1025 name = PyObject_Repr(cls);
1026 }
1027 if (name == NULL)
1028 return NULL;
1029 if (!PyString_Check(name)) {
1030 Py_DECREF(name);
1031 return NULL;
1032 }
1033 return name;
1034}
1035
1036static int
1037check_duplicates(PyObject *list)
1038{
1039 int i, j, n;
1040 /* Let's use a quadratic time algorithm,
1041 assuming that the bases lists is short.
1042 */
1043 n = PyList_GET_SIZE(list);
1044 for (i = 0; i < n; i++) {
1045 PyObject *o = PyList_GET_ITEM(list, i);
1046 for (j = i + 1; j < n; j++) {
1047 if (PyList_GET_ITEM(list, j) == o) {
1048 o = class_name(o);
1049 PyErr_Format(PyExc_TypeError,
1050 "duplicate base class %s",
1051 o ? PyString_AS_STRING(o) : "?");
1052 Py_XDECREF(o);
1053 return -1;
1054 }
1055 }
1056 }
1057 return 0;
1058}
1059
1060/* Raise a TypeError for an MRO order disagreement.
1061
1062 It's hard to produce a good error message. In the absence of better
1063 insight into error reporting, report the classes that were candidates
1064 to be put next into the MRO. There is some conflict between the
1065 order in which they should be put in the MRO, but it's hard to
1066 diagnose what constraint can't be satisfied.
1067*/
1068
1069static void
1070set_mro_error(PyObject *to_merge, int *remain)
1071{
1072 int i, n, off, to_merge_size;
1073 char buf[1000];
1074 PyObject *k, *v;
1075 PyObject *set = PyDict_New();
1076
1077 to_merge_size = PyList_GET_SIZE(to_merge);
1078 for (i = 0; i < to_merge_size; i++) {
1079 PyObject *L = PyList_GET_ITEM(to_merge, i);
1080 if (remain[i] < PyList_GET_SIZE(L)) {
1081 PyObject *c = PyList_GET_ITEM(L, remain[i]);
1082 if (PyDict_SetItem(set, c, Py_None) < 0)
1083 return;
1084 }
1085 }
1086 n = PyDict_Size(set);
1087
Raymond Hettingerf394df42003-04-06 19:13:41 +00001088 off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \
1089consistent method resolution\norder (MRO) for bases");
Guido van Rossum98f33732002-11-25 21:36:54 +00001090 i = 0;
1091 while (PyDict_Next(set, &i, &k, &v) && off < sizeof(buf)) {
1092 PyObject *name = class_name(k);
1093 off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s",
1094 name ? PyString_AS_STRING(name) : "?");
1095 Py_XDECREF(name);
1096 if (--n && off+1 < sizeof(buf)) {
1097 buf[off++] = ',';
1098 buf[off] = '\0';
1099 }
1100 }
1101 PyErr_SetString(PyExc_TypeError, buf);
1102 Py_DECREF(set);
1103}
1104
Tim Petersea7f75d2002-12-07 21:39:16 +00001105static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001106pmerge(PyObject *acc, PyObject* to_merge) {
1107 int i, j, to_merge_size;
1108 int *remain;
1109 int ok, empty_cnt;
Tim Petersea7f75d2002-12-07 21:39:16 +00001110
Guido van Rossum1f121312002-11-14 19:49:16 +00001111 to_merge_size = PyList_GET_SIZE(to_merge);
1112
Guido van Rossum98f33732002-11-25 21:36:54 +00001113 /* remain stores an index into each sublist of to_merge.
1114 remain[i] is the index of the next base in to_merge[i]
1115 that is not included in acc.
1116 */
Guido van Rossum1f121312002-11-14 19:49:16 +00001117 remain = PyMem_MALLOC(SIZEOF_INT*to_merge_size);
1118 if (remain == NULL)
1119 return -1;
1120 for (i = 0; i < to_merge_size; i++)
1121 remain[i] = 0;
1122
1123 again:
1124 empty_cnt = 0;
1125 for (i = 0; i < to_merge_size; i++) {
1126 PyObject *candidate;
Tim Petersea7f75d2002-12-07 21:39:16 +00001127
Guido van Rossum1f121312002-11-14 19:49:16 +00001128 PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
1129
1130 if (remain[i] >= PyList_GET_SIZE(cur_list)) {
1131 empty_cnt++;
1132 continue;
1133 }
1134
Guido van Rossum98f33732002-11-25 21:36:54 +00001135 /* Choose next candidate for MRO.
1136
1137 The input sequences alone can determine the choice.
1138 If not, choose the class which appears in the MRO
1139 of the earliest direct superclass of the new class.
1140 */
1141
Guido van Rossum1f121312002-11-14 19:49:16 +00001142 candidate = PyList_GET_ITEM(cur_list, remain[i]);
1143 for (j = 0; j < to_merge_size; j++) {
1144 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum98f33732002-11-25 21:36:54 +00001145 if (tail_contains(j_lst, remain[j], candidate)) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001146 goto skip; /* continue outer loop */
Guido van Rossum98f33732002-11-25 21:36:54 +00001147 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001148 }
1149 ok = PyList_Append(acc, candidate);
1150 if (ok < 0) {
1151 PyMem_Free(remain);
1152 return -1;
1153 }
1154 for (j = 0; j < to_merge_size; j++) {
1155 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum768158c2002-12-31 16:33:01 +00001156 if (remain[j] < PyList_GET_SIZE(j_lst) &&
1157 PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001158 remain[j]++;
1159 }
1160 }
1161 goto again;
Tim Peters9a6b8d82002-11-14 23:22:33 +00001162 skip: ;
Guido van Rossum1f121312002-11-14 19:49:16 +00001163 }
1164
Guido van Rossum98f33732002-11-25 21:36:54 +00001165 if (empty_cnt == to_merge_size) {
1166 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001167 return 0;
Guido van Rossum98f33732002-11-25 21:36:54 +00001168 }
1169 set_mro_error(to_merge, remain);
1170 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001171 return -1;
1172}
1173
Tim Peters6d6c1a32001-08-02 04:15:00 +00001174static PyObject *
1175mro_implementation(PyTypeObject *type)
1176{
1177 int i, n, ok;
1178 PyObject *bases, *result;
Guido van Rossum1f121312002-11-14 19:49:16 +00001179 PyObject *to_merge, *bases_aslist;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001180
Guido van Rossum63517572002-06-18 16:44:57 +00001181 if(type->tp_dict == NULL) {
1182 if(PyType_Ready(type) < 0)
1183 return NULL;
1184 }
1185
Guido van Rossum98f33732002-11-25 21:36:54 +00001186 /* Find a superclass linearization that honors the constraints
1187 of the explicit lists of bases and the constraints implied by
Tim Petersea7f75d2002-12-07 21:39:16 +00001188 each base class.
Guido van Rossum98f33732002-11-25 21:36:54 +00001189
1190 to_merge is a list of lists, where each list is a superclass
1191 linearization implied by a base class. The last element of
1192 to_merge is the declared list of bases.
1193 */
1194
Tim Peters6d6c1a32001-08-02 04:15:00 +00001195 bases = type->tp_bases;
1196 n = PyTuple_GET_SIZE(bases);
Guido van Rossum1f121312002-11-14 19:49:16 +00001197
1198 to_merge = PyList_New(n+1);
1199 if (to_merge == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001200 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001201
Tim Peters6d6c1a32001-08-02 04:15:00 +00001202 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001203 PyObject *base = PyTuple_GET_ITEM(bases, i);
1204 PyObject *parentMRO;
1205 if (PyType_Check(base))
1206 parentMRO = PySequence_List(
1207 ((PyTypeObject*)base)->tp_mro);
1208 else
1209 parentMRO = classic_mro(base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001210 if (parentMRO == NULL) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001211 Py_DECREF(to_merge);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001212 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001213 }
1214
1215 PyList_SET_ITEM(to_merge, i, parentMRO);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001216 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001217
1218 bases_aslist = PySequence_List(bases);
1219 if (bases_aslist == NULL) {
1220 Py_DECREF(to_merge);
1221 return NULL;
1222 }
Guido van Rossum98f33732002-11-25 21:36:54 +00001223 /* This is just a basic sanity check. */
1224 if (check_duplicates(bases_aslist) < 0) {
1225 Py_DECREF(to_merge);
1226 Py_DECREF(bases_aslist);
1227 return NULL;
1228 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001229 PyList_SET_ITEM(to_merge, n, bases_aslist);
1230
1231 result = Py_BuildValue("[O]", (PyObject *)type);
1232 if (result == NULL) {
1233 Py_DECREF(to_merge);
1234 return NULL;
1235 }
1236
1237 ok = pmerge(result, to_merge);
1238 Py_DECREF(to_merge);
1239 if (ok < 0) {
1240 Py_DECREF(result);
1241 return NULL;
1242 }
1243
Tim Peters6d6c1a32001-08-02 04:15:00 +00001244 return result;
1245}
1246
1247static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001248mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001249{
1250 PyTypeObject *type = (PyTypeObject *)self;
1251
Tim Peters6d6c1a32001-08-02 04:15:00 +00001252 return mro_implementation(type);
1253}
1254
1255static int
1256mro_internal(PyTypeObject *type)
1257{
1258 PyObject *mro, *result, *tuple;
1259
1260 if (type->ob_type == &PyType_Type) {
1261 result = mro_implementation(type);
1262 }
1263 else {
Guido van Rossum60718732001-08-28 17:47:51 +00001264 static PyObject *mro_str;
1265 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001266 if (mro == NULL)
1267 return -1;
1268 result = PyObject_CallObject(mro, NULL);
1269 Py_DECREF(mro);
1270 }
1271 if (result == NULL)
1272 return -1;
1273 tuple = PySequence_Tuple(result);
1274 Py_DECREF(result);
1275 type->tp_mro = tuple;
1276 return 0;
1277}
1278
1279
1280/* Calculate the best base amongst multiple base classes.
1281 This is the first one that's on the path to the "solid base". */
1282
1283static PyTypeObject *
1284best_base(PyObject *bases)
1285{
1286 int i, n;
1287 PyTypeObject *base, *winner, *candidate, *base_i;
Tim Petersa91e9642001-11-14 23:32:33 +00001288 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001289
1290 assert(PyTuple_Check(bases));
1291 n = PyTuple_GET_SIZE(bases);
1292 assert(n > 0);
Tim Petersa91e9642001-11-14 23:32:33 +00001293 base = NULL;
1294 winner = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001295 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001296 base_proto = PyTuple_GET_ITEM(bases, i);
1297 if (PyClass_Check(base_proto))
1298 continue;
1299 if (!PyType_Check(base_proto)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001300 PyErr_SetString(
1301 PyExc_TypeError,
1302 "bases must be types");
1303 return NULL;
1304 }
Tim Petersa91e9642001-11-14 23:32:33 +00001305 base_i = (PyTypeObject *)base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001306 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001307 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001308 return NULL;
1309 }
1310 candidate = solid_base(base_i);
Tim Petersa91e9642001-11-14 23:32:33 +00001311 if (winner == NULL) {
1312 winner = candidate;
1313 base = base_i;
1314 }
1315 else if (PyType_IsSubtype(winner, candidate))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001316 ;
1317 else if (PyType_IsSubtype(candidate, winner)) {
1318 winner = candidate;
1319 base = base_i;
1320 }
1321 else {
1322 PyErr_SetString(
1323 PyExc_TypeError,
1324 "multiple bases have "
1325 "instance lay-out conflict");
1326 return NULL;
1327 }
1328 }
Guido van Rossume54616c2001-12-14 04:19:56 +00001329 if (base == NULL)
1330 PyErr_SetString(PyExc_TypeError,
1331 "a new-style class can't have only classic bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001332 return base;
1333}
1334
1335static int
1336extra_ivars(PyTypeObject *type, PyTypeObject *base)
1337{
Neil Schemenauerc806c882001-08-29 23:54:54 +00001338 size_t t_size = type->tp_basicsize;
1339 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001340
Guido van Rossum9676b222001-08-17 20:32:36 +00001341 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001342 if (type->tp_itemsize || base->tp_itemsize) {
1343 /* If itemsize is involved, stricter rules */
1344 return t_size != b_size ||
1345 type->tp_itemsize != base->tp_itemsize;
1346 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001347 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
1348 type->tp_weaklistoffset + sizeof(PyObject *) == t_size)
1349 t_size -= sizeof(PyObject *);
1350 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
1351 type->tp_dictoffset + sizeof(PyObject *) == t_size)
1352 t_size -= sizeof(PyObject *);
1353
1354 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001355}
1356
1357static PyTypeObject *
1358solid_base(PyTypeObject *type)
1359{
1360 PyTypeObject *base;
1361
1362 if (type->tp_base)
1363 base = solid_base(type->tp_base);
1364 else
1365 base = &PyBaseObject_Type;
1366 if (extra_ivars(type, base))
1367 return type;
1368 else
1369 return base;
1370}
1371
Jeremy Hylton938ace62002-07-17 16:30:39 +00001372static void object_dealloc(PyObject *);
1373static int object_init(PyObject *, PyObject *, PyObject *);
1374static int update_slot(PyTypeObject *, PyObject *);
1375static void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001376
1377static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001378subtype_dict(PyObject *obj, void *context)
1379{
1380 PyObject **dictptr = _PyObject_GetDictPtr(obj);
1381 PyObject *dict;
1382
1383 if (dictptr == NULL) {
1384 PyErr_SetString(PyExc_AttributeError,
1385 "This object has no __dict__");
1386 return NULL;
1387 }
1388 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +00001389 if (dict == NULL)
1390 *dictptr = dict = PyDict_New();
1391 Py_XINCREF(dict);
1392 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001393}
1394
Guido van Rossum6661be32001-10-26 04:26:12 +00001395static int
1396subtype_setdict(PyObject *obj, PyObject *value, void *context)
1397{
1398 PyObject **dictptr = _PyObject_GetDictPtr(obj);
1399 PyObject *dict;
1400
1401 if (dictptr == NULL) {
1402 PyErr_SetString(PyExc_AttributeError,
1403 "This object has no __dict__");
1404 return -1;
1405 }
Guido van Rossumd331cb52001-12-05 19:46:42 +00001406 if (value != NULL && !PyDict_Check(value)) {
Guido van Rossum6661be32001-10-26 04:26:12 +00001407 PyErr_SetString(PyExc_TypeError,
1408 "__dict__ must be set to a dictionary");
1409 return -1;
1410 }
1411 dict = *dictptr;
Guido van Rossumd331cb52001-12-05 19:46:42 +00001412 Py_XINCREF(value);
Guido van Rossum6661be32001-10-26 04:26:12 +00001413 *dictptr = value;
1414 Py_XDECREF(dict);
1415 return 0;
1416}
1417
Guido van Rossumad47da02002-08-12 19:05:44 +00001418static PyObject *
1419subtype_getweakref(PyObject *obj, void *context)
1420{
1421 PyObject **weaklistptr;
1422 PyObject *result;
1423
1424 if (obj->ob_type->tp_weaklistoffset == 0) {
1425 PyErr_SetString(PyExc_AttributeError,
1426 "This object has no __weaklist__");
1427 return NULL;
1428 }
1429 assert(obj->ob_type->tp_weaklistoffset > 0);
1430 assert(obj->ob_type->tp_weaklistoffset + sizeof(PyObject *) <=
Guido van Rossum3747a0f2002-08-12 19:25:08 +00001431 (size_t)(obj->ob_type->tp_basicsize));
Guido van Rossumad47da02002-08-12 19:05:44 +00001432 weaklistptr = (PyObject **)
Guido van Rossum3747a0f2002-08-12 19:25:08 +00001433 ((char *)obj + obj->ob_type->tp_weaklistoffset);
Guido van Rossumad47da02002-08-12 19:05:44 +00001434 if (*weaklistptr == NULL)
1435 result = Py_None;
1436 else
1437 result = *weaklistptr;
1438 Py_INCREF(result);
1439 return result;
1440}
1441
Guido van Rossum373c7412003-01-07 13:41:37 +00001442/* Three variants on the subtype_getsets list. */
1443
1444static PyGetSetDef subtype_getsets_full[] = {
Guido van Rossumad47da02002-08-12 19:05:44 +00001445 {"__dict__", subtype_dict, subtype_setdict,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001446 PyDoc_STR("dictionary for instance variables (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001447 {"__weakref__", subtype_getweakref, NULL,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001448 PyDoc_STR("list of weak references to the object (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001449 {0}
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001450};
1451
Guido van Rossum373c7412003-01-07 13:41:37 +00001452static PyGetSetDef subtype_getsets_dict_only[] = {
1453 {"__dict__", subtype_dict, subtype_setdict,
1454 PyDoc_STR("dictionary for instance variables (if defined)")},
1455 {0}
1456};
1457
1458static PyGetSetDef subtype_getsets_weakref_only[] = {
1459 {"__weakref__", subtype_getweakref, NULL,
1460 PyDoc_STR("list of weak references to the object (if defined)")},
1461 {0}
1462};
1463
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001464static int
1465valid_identifier(PyObject *s)
1466{
Guido van Rossum03013a02002-07-16 14:30:28 +00001467 unsigned char *p;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001468 int i, n;
1469
1470 if (!PyString_Check(s)) {
1471 PyErr_SetString(PyExc_TypeError,
1472 "__slots__ must be strings");
1473 return 0;
1474 }
Guido van Rossum03013a02002-07-16 14:30:28 +00001475 p = (unsigned char *) PyString_AS_STRING(s);
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001476 n = PyString_GET_SIZE(s);
1477 /* We must reject an empty name. As a hack, we bump the
1478 length to 1 so that the loop will balk on the trailing \0. */
1479 if (n == 0)
1480 n = 1;
1481 for (i = 0; i < n; i++, p++) {
1482 if (!(i == 0 ? isalpha(*p) : isalnum(*p)) && *p != '_') {
1483 PyErr_SetString(PyExc_TypeError,
1484 "__slots__ must be identifiers");
1485 return 0;
1486 }
1487 }
1488 return 1;
1489}
1490
Martin v. Löwisd919a592002-10-14 21:07:28 +00001491#ifdef Py_USING_UNICODE
1492/* Replace Unicode objects in slots. */
1493
1494static PyObject *
1495_unicode_to_string(PyObject *slots, int nslots)
1496{
1497 PyObject *tmp = slots;
1498 PyObject *o, *o1;
1499 int i;
1500 intintargfunc copy = slots->ob_type->tp_as_sequence->sq_slice;
1501 for (i = 0; i < nslots; i++) {
1502 if (PyUnicode_Check(o = PyTuple_GET_ITEM(tmp, i))) {
1503 if (tmp == slots) {
1504 tmp = copy(slots, 0, PyTuple_GET_SIZE(slots));
1505 if (tmp == NULL)
1506 return NULL;
1507 }
1508 o1 = _PyUnicode_AsDefaultEncodedString
1509 (o, NULL);
1510 if (o1 == NULL) {
1511 Py_DECREF(tmp);
1512 return 0;
1513 }
1514 Py_INCREF(o1);
1515 Py_DECREF(o);
1516 PyTuple_SET_ITEM(tmp, i, o1);
1517 }
1518 }
1519 return tmp;
1520}
1521#endif
1522
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001523static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001524type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
1525{
1526 PyObject *name, *bases, *dict;
1527 static char *kwlist[] = {"name", "bases", "dict", 0};
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001528 PyObject *slots, *tmp, *newslots;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001529 PyTypeObject *type, *base, *tmptype, *winner;
Guido van Rossume5c691a2003-03-07 15:13:17 +00001530 PyHeapTypeObject *et;
Guido van Rossum6f799372001-09-20 20:46:19 +00001531 PyMemberDef *mp;
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001532 int i, nbases, nslots, slotoffset, add_dict, add_weak;
Guido van Rossumad47da02002-08-12 19:05:44 +00001533 int j, may_add_dict, may_add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001534
Tim Peters3abca122001-10-27 19:37:48 +00001535 assert(args != NULL && PyTuple_Check(args));
1536 assert(kwds == NULL || PyDict_Check(kwds));
1537
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001538 /* Special case: type(x) should return x->ob_type */
Tim Peters3abca122001-10-27 19:37:48 +00001539 {
1540 const int nargs = PyTuple_GET_SIZE(args);
1541 const int nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
1542
1543 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
1544 PyObject *x = PyTuple_GET_ITEM(args, 0);
1545 Py_INCREF(x->ob_type);
1546 return (PyObject *) x->ob_type;
1547 }
1548
1549 /* SF bug 475327 -- if that didn't trigger, we need 3
1550 arguments. but PyArg_ParseTupleAndKeywords below may give
1551 a msg saying type() needs exactly 3. */
1552 if (nargs + nkwds != 3) {
1553 PyErr_SetString(PyExc_TypeError,
1554 "type() takes 1 or 3 arguments");
1555 return NULL;
1556 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001557 }
1558
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001559 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001560 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
1561 &name,
1562 &PyTuple_Type, &bases,
1563 &PyDict_Type, &dict))
1564 return NULL;
1565
1566 /* Determine the proper metatype to deal with this,
1567 and check for metatype conflicts while we're at it.
1568 Note that if some other metatype wins to contract,
1569 it's possible that its instances are not types. */
1570 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001571 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001572 for (i = 0; i < nbases; i++) {
1573 tmp = PyTuple_GET_ITEM(bases, i);
1574 tmptype = tmp->ob_type;
Tim Petersa91e9642001-11-14 23:32:33 +00001575 if (tmptype == &PyClass_Type)
1576 continue; /* Special case classic classes */
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001577 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001578 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001579 if (PyType_IsSubtype(tmptype, winner)) {
1580 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001581 continue;
1582 }
1583 PyErr_SetString(PyExc_TypeError,
Guido van Rossum636688d2003-04-23 12:07:22 +00001584 "metaclass conflict: "
1585 "the metaclass of a derived class "
1586 "must be a (non-strict) subclass "
1587 "of the metaclasses of all its bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001588 return NULL;
1589 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001590 if (winner != metatype) {
1591 if (winner->tp_new != type_new) /* Pass it to the winner */
1592 return winner->tp_new(winner, args, kwds);
1593 metatype = winner;
1594 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001595
1596 /* Adjust for empty tuple bases */
1597 if (nbases == 0) {
1598 bases = Py_BuildValue("(O)", &PyBaseObject_Type);
1599 if (bases == NULL)
1600 return NULL;
1601 nbases = 1;
1602 }
1603 else
1604 Py_INCREF(bases);
1605
1606 /* XXX From here until type is allocated, "return NULL" leaks bases! */
1607
1608 /* Calculate best base, and check that all bases are type objects */
1609 base = best_base(bases);
1610 if (base == NULL)
1611 return NULL;
1612 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
1613 PyErr_Format(PyExc_TypeError,
1614 "type '%.100s' is not an acceptable base type",
1615 base->tp_name);
1616 return NULL;
1617 }
1618
Tim Peters6d6c1a32001-08-02 04:15:00 +00001619 /* Check for a __slots__ sequence variable in dict, and count it */
1620 slots = PyDict_GetItemString(dict, "__slots__");
1621 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +00001622 add_dict = 0;
1623 add_weak = 0;
Guido van Rossumad47da02002-08-12 19:05:44 +00001624 may_add_dict = base->tp_dictoffset == 0;
1625 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
1626 if (slots == NULL) {
1627 if (may_add_dict) {
1628 add_dict++;
1629 }
1630 if (may_add_weak) {
1631 add_weak++;
1632 }
1633 }
1634 else {
1635 /* Have slots */
1636
Tim Peters6d6c1a32001-08-02 04:15:00 +00001637 /* Make it into a tuple */
1638 if (PyString_Check(slots))
1639 slots = Py_BuildValue("(O)", slots);
1640 else
1641 slots = PySequence_Tuple(slots);
1642 if (slots == NULL)
1643 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00001644 assert(PyTuple_Check(slots));
1645
1646 /* Are slots allowed? */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001647 nslots = PyTuple_GET_SIZE(slots);
Guido van Rossume5c691a2003-03-07 15:13:17 +00001648 if (nslots > 0 && base->tp_itemsize != 0 && !PyType_Check(base)) {
1649 /* for the special case of meta types, allow slots */
Guido van Rossumc4141872001-08-30 04:43:35 +00001650 PyErr_Format(PyExc_TypeError,
1651 "nonempty __slots__ "
1652 "not supported for subtype of '%s'",
1653 base->tp_name);
Guido van Rossumad47da02002-08-12 19:05:44 +00001654 bad_slots:
1655 Py_DECREF(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +00001656 return NULL;
1657 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001658
Martin v. Löwisd919a592002-10-14 21:07:28 +00001659#ifdef Py_USING_UNICODE
1660 tmp = _unicode_to_string(slots, nslots);
Martin v. Löwis13b1a5c2002-10-14 21:11:34 +00001661 if (tmp != slots) {
1662 Py_DECREF(slots);
1663 slots = tmp;
1664 }
Martin v. Löwisd919a592002-10-14 21:07:28 +00001665 if (!tmp)
1666 return NULL;
1667#endif
Guido van Rossumad47da02002-08-12 19:05:44 +00001668 /* Check for valid slot names and two special cases */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001669 for (i = 0; i < nslots; i++) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001670 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
1671 char *s;
1672 if (!valid_identifier(tmp))
1673 goto bad_slots;
1674 assert(PyString_Check(tmp));
1675 s = PyString_AS_STRING(tmp);
1676 if (strcmp(s, "__dict__") == 0) {
1677 if (!may_add_dict || add_dict) {
1678 PyErr_SetString(PyExc_TypeError,
1679 "__dict__ slot disallowed: "
1680 "we already got one");
1681 goto bad_slots;
1682 }
1683 add_dict++;
1684 }
1685 if (strcmp(s, "__weakref__") == 0) {
1686 if (!may_add_weak || add_weak) {
1687 PyErr_SetString(PyExc_TypeError,
1688 "__weakref__ slot disallowed: "
1689 "either we already got one, "
1690 "or __itemsize__ != 0");
1691 goto bad_slots;
1692 }
1693 add_weak++;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001694 }
1695 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001696
Guido van Rossumad47da02002-08-12 19:05:44 +00001697 /* Copy slots into yet another tuple, demangling names */
1698 newslots = PyTuple_New(nslots - add_dict - add_weak);
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001699 if (newslots == NULL)
Guido van Rossumad47da02002-08-12 19:05:44 +00001700 goto bad_slots;
1701 for (i = j = 0; i < nslots; i++) {
1702 char *s;
Guido van Rossum8e829202002-08-16 03:47:49 +00001703 char buffer[256];
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001704 tmp = PyTuple_GET_ITEM(slots, i);
Guido van Rossumad47da02002-08-12 19:05:44 +00001705 s = PyString_AS_STRING(tmp);
1706 if ((add_dict && strcmp(s, "__dict__") == 0) ||
1707 (add_weak && strcmp(s, "__weakref__") == 0))
1708 continue;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001709 if (_Py_Mangle(PyString_AS_STRING(name),
Guido van Rossumad47da02002-08-12 19:05:44 +00001710 PyString_AS_STRING(tmp),
1711 buffer, sizeof(buffer)))
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001712 {
1713 tmp = PyString_FromString(buffer);
1714 } else {
1715 Py_INCREF(tmp);
1716 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001717 PyTuple_SET_ITEM(newslots, j, tmp);
1718 j++;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001719 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001720 assert(j == nslots - add_dict - add_weak);
1721 nslots = j;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001722 Py_DECREF(slots);
1723 slots = newslots;
1724
Guido van Rossumad47da02002-08-12 19:05:44 +00001725 /* Secondary bases may provide weakrefs or dict */
1726 if (nbases > 1 &&
1727 ((may_add_dict && !add_dict) ||
1728 (may_add_weak && !add_weak))) {
1729 for (i = 0; i < nbases; i++) {
1730 tmp = PyTuple_GET_ITEM(bases, i);
1731 if (tmp == (PyObject *)base)
1732 continue; /* Skip primary base */
1733 if (PyClass_Check(tmp)) {
1734 /* Classic base class provides both */
1735 if (may_add_dict && !add_dict)
1736 add_dict++;
1737 if (may_add_weak && !add_weak)
1738 add_weak++;
1739 break;
1740 }
1741 assert(PyType_Check(tmp));
1742 tmptype = (PyTypeObject *)tmp;
1743 if (may_add_dict && !add_dict &&
1744 tmptype->tp_dictoffset != 0)
1745 add_dict++;
1746 if (may_add_weak && !add_weak &&
1747 tmptype->tp_weaklistoffset != 0)
1748 add_weak++;
1749 if (may_add_dict && !add_dict)
1750 continue;
1751 if (may_add_weak && !add_weak)
1752 continue;
1753 /* Nothing more to check */
1754 break;
1755 }
1756 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001757 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001758
1759 /* XXX From here until type is safely allocated,
1760 "return NULL" may leak slots! */
1761
1762 /* Allocate the type object */
1763 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
Guido van Rossumad47da02002-08-12 19:05:44 +00001764 if (type == NULL) {
1765 Py_XDECREF(slots);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001766 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00001767 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001768
1769 /* Keep name and slots alive in the extended type object */
Guido van Rossume5c691a2003-03-07 15:13:17 +00001770 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001771 Py_INCREF(name);
1772 et->name = name;
1773 et->slots = slots;
1774
Guido van Rossumdc91b992001-08-08 22:26:22 +00001775 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001776 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
1777 Py_TPFLAGS_BASETYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00001778 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
1779 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00001780
1781 /* It's a new-style number unless it specifically inherits any
1782 old-style numeric behavior */
1783 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
1784 (base->tp_as_number == NULL))
1785 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
1786
1787 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001788 type->tp_as_number = &et->as_number;
1789 type->tp_as_sequence = &et->as_sequence;
1790 type->tp_as_mapping = &et->as_mapping;
1791 type->tp_as_buffer = &et->as_buffer;
1792 type->tp_name = PyString_AS_STRING(name);
1793
1794 /* Set tp_base and tp_bases */
1795 type->tp_bases = bases;
1796 Py_INCREF(base);
1797 type->tp_base = base;
1798
Guido van Rossum687ae002001-10-15 22:03:32 +00001799 /* Initialize tp_dict from passed-in dict */
1800 type->tp_dict = dict = PyDict_Copy(dict);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001801 if (dict == NULL) {
1802 Py_DECREF(type);
1803 return NULL;
1804 }
1805
Guido van Rossumc3542212001-08-16 09:18:56 +00001806 /* Set __module__ in the dict */
1807 if (PyDict_GetItemString(dict, "__module__") == NULL) {
1808 tmp = PyEval_GetGlobals();
1809 if (tmp != NULL) {
1810 tmp = PyDict_GetItemString(tmp, "__name__");
1811 if (tmp != NULL) {
1812 if (PyDict_SetItemString(dict, "__module__",
1813 tmp) < 0)
1814 return NULL;
1815 }
1816 }
1817 }
1818
Tim Peters2f93e282001-10-04 05:27:00 +00001819 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
Tim Peters24008312002-03-17 18:56:20 +00001820 and is a string. The __doc__ accessor will first look for tp_doc;
1821 if that fails, it will still look into __dict__.
Tim Peters2f93e282001-10-04 05:27:00 +00001822 */
1823 {
1824 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
1825 if (doc != NULL && PyString_Check(doc)) {
1826 const size_t n = (size_t)PyString_GET_SIZE(doc);
Tim Peters59f809d2001-10-04 05:43:02 +00001827 type->tp_doc = (char *)PyObject_MALLOC(n+1);
Tim Peters2f93e282001-10-04 05:27:00 +00001828 if (type->tp_doc == NULL) {
1829 Py_DECREF(type);
1830 return NULL;
1831 }
1832 memcpy(type->tp_doc, PyString_AS_STRING(doc), n+1);
1833 }
1834 }
1835
Tim Peters6d6c1a32001-08-02 04:15:00 +00001836 /* Special-case __new__: if it's a plain function,
1837 make it a static function */
1838 tmp = PyDict_GetItemString(dict, "__new__");
1839 if (tmp != NULL && PyFunction_Check(tmp)) {
1840 tmp = PyStaticMethod_New(tmp);
1841 if (tmp == NULL) {
1842 Py_DECREF(type);
1843 return NULL;
1844 }
1845 PyDict_SetItemString(dict, "__new__", tmp);
1846 Py_DECREF(tmp);
1847 }
1848
1849 /* Add descriptors for custom slots from __slots__, or for __dict__ */
Guido van Rossume5c691a2003-03-07 15:13:17 +00001850 mp = PyHeapType_GET_MEMBERS(et);
Neil Schemenauerc806c882001-08-29 23:54:54 +00001851 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001852 if (slots != NULL) {
1853 for (i = 0; i < nslots; i++, mp++) {
1854 mp->name = PyString_AS_STRING(
1855 PyTuple_GET_ITEM(slots, i));
Guido van Rossum64b206c2001-12-04 17:13:22 +00001856 mp->type = T_OBJECT_EX;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001857 mp->offset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +00001858 if (base->tp_weaklistoffset == 0 &&
Guido van Rossum64b206c2001-12-04 17:13:22 +00001859 strcmp(mp->name, "__weakref__") == 0) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001860 add_weak++;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001861 mp->type = T_OBJECT;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001862 mp->flags = READONLY;
Guido van Rossum9676b222001-08-17 20:32:36 +00001863 type->tp_weaklistoffset = slotoffset;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001864 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001865 slotoffset += sizeof(PyObject *);
1866 }
1867 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001868 if (add_dict) {
1869 if (base->tp_itemsize)
1870 type->tp_dictoffset = -(long)sizeof(PyObject *);
1871 else
1872 type->tp_dictoffset = slotoffset;
1873 slotoffset += sizeof(PyObject *);
1874 }
1875 if (add_weak) {
1876 assert(!base->tp_itemsize);
1877 type->tp_weaklistoffset = slotoffset;
1878 slotoffset += sizeof(PyObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001879 }
1880 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001881 type->tp_itemsize = base->tp_itemsize;
Guido van Rossume5c691a2003-03-07 15:13:17 +00001882 type->tp_members = PyHeapType_GET_MEMBERS(et);
Guido van Rossum373c7412003-01-07 13:41:37 +00001883
1884 if (type->tp_weaklistoffset && type->tp_dictoffset)
1885 type->tp_getset = subtype_getsets_full;
1886 else if (type->tp_weaklistoffset && !type->tp_dictoffset)
1887 type->tp_getset = subtype_getsets_weakref_only;
1888 else if (!type->tp_weaklistoffset && type->tp_dictoffset)
1889 type->tp_getset = subtype_getsets_dict_only;
1890 else
1891 type->tp_getset = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001892
1893 /* Special case some slots */
1894 if (type->tp_dictoffset != 0 || nslots > 0) {
1895 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
1896 type->tp_getattro = PyObject_GenericGetAttr;
1897 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
1898 type->tp_setattro = PyObject_GenericSetAttr;
1899 }
1900 type->tp_dealloc = subtype_dealloc;
1901
Guido van Rossum9475a232001-10-05 20:51:39 +00001902 /* Enable GC unless there are really no instance variables possible */
1903 if (!(type->tp_basicsize == sizeof(PyObject) &&
1904 type->tp_itemsize == 0))
1905 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
1906
Tim Peters6d6c1a32001-08-02 04:15:00 +00001907 /* Always override allocation strategy to use regular heap */
1908 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00001909 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001910 type->tp_free = PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00001911 type->tp_traverse = subtype_traverse;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001912 type->tp_clear = subtype_clear;
Guido van Rossum048eb752001-10-02 21:24:57 +00001913 }
1914 else
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001915 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001916
1917 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001918 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001919 Py_DECREF(type);
1920 return NULL;
1921 }
1922
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001923 /* Put the proper slots in place */
1924 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00001925
Tim Peters6d6c1a32001-08-02 04:15:00 +00001926 return (PyObject *)type;
1927}
1928
1929/* Internal API to look for a name through the MRO.
1930 This returns a borrowed reference, and doesn't set an exception! */
1931PyObject *
1932_PyType_Lookup(PyTypeObject *type, PyObject *name)
1933{
1934 int i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00001935 PyObject *mro, *res, *base, *dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001936
Guido van Rossum687ae002001-10-15 22:03:32 +00001937 /* Look in tp_dict of types in MRO */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001938 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00001939
1940 /* If mro is NULL, the type is either not yet initialized
1941 by PyType_Ready(), or already cleared by type_clear().
1942 Either way the safest thing to do is to return NULL. */
1943 if (mro == NULL)
1944 return NULL;
1945
Tim Peters6d6c1a32001-08-02 04:15:00 +00001946 assert(PyTuple_Check(mro));
1947 n = PyTuple_GET_SIZE(mro);
1948 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001949 base = PyTuple_GET_ITEM(mro, i);
1950 if (PyClass_Check(base))
1951 dict = ((PyClassObject *)base)->cl_dict;
1952 else {
1953 assert(PyType_Check(base));
1954 dict = ((PyTypeObject *)base)->tp_dict;
1955 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001956 assert(dict && PyDict_Check(dict));
1957 res = PyDict_GetItem(dict, name);
1958 if (res != NULL)
1959 return res;
1960 }
1961 return NULL;
1962}
1963
1964/* This is similar to PyObject_GenericGetAttr(),
1965 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
1966static PyObject *
1967type_getattro(PyTypeObject *type, PyObject *name)
1968{
1969 PyTypeObject *metatype = type->ob_type;
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001970 PyObject *meta_attribute, *attribute;
1971 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001972
1973 /* Initialize this type (we'll assume the metatype is initialized) */
1974 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001975 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001976 return NULL;
1977 }
1978
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001979 /* No readable descriptor found yet */
1980 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00001981
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001982 /* Look for the attribute in the metatype */
1983 meta_attribute = _PyType_Lookup(metatype, name);
1984
1985 if (meta_attribute != NULL) {
1986 meta_get = meta_attribute->ob_type->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00001987
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001988 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
1989 /* Data descriptors implement tp_descr_set to intercept
1990 * writes. Assume the attribute is not overridden in
1991 * type's tp_dict (and bases): call the descriptor now.
1992 */
1993 return meta_get(meta_attribute, (PyObject *)type,
1994 (PyObject *)metatype);
1995 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001996 }
1997
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001998 /* No data descriptor found on metatype. Look in tp_dict of this
1999 * type and its bases */
2000 attribute = _PyType_Lookup(type, name);
2001 if (attribute != NULL) {
2002 /* Implement descriptor functionality, if any */
2003 descrgetfunc local_get = attribute->ob_type->tp_descr_get;
2004 if (local_get != NULL) {
2005 /* NULL 2nd argument indicates the descriptor was
2006 * found on the target object itself (or a base) */
2007 return local_get(attribute, (PyObject *)NULL,
2008 (PyObject *)type);
2009 }
Tim Peters34592512002-07-11 06:23:50 +00002010
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002011 Py_INCREF(attribute);
2012 return attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002013 }
2014
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002015 /* No attribute found in local __dict__ (or bases): use the
2016 * descriptor from the metatype, if any */
2017 if (meta_get != NULL)
2018 return meta_get(meta_attribute, (PyObject *)type,
2019 (PyObject *)metatype);
2020
2021 /* If an ordinary attribute was found on the metatype, return it now */
2022 if (meta_attribute != NULL) {
2023 Py_INCREF(meta_attribute);
2024 return meta_attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002025 }
2026
2027 /* Give up */
2028 PyErr_Format(PyExc_AttributeError,
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002029 "type object '%.50s' has no attribute '%.400s'",
2030 type->tp_name, PyString_AS_STRING(name));
Tim Peters6d6c1a32001-08-02 04:15:00 +00002031 return NULL;
2032}
2033
2034static int
2035type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
2036{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002037 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2038 PyErr_Format(
2039 PyExc_TypeError,
2040 "can't set attributes of built-in/extension type '%s'",
2041 type->tp_name);
2042 return -1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002043 }
Guido van Rossum8d24ee92003-03-24 23:49:49 +00002044 /* XXX Example of how I expect this to be used...
2045 if (update_subclasses(type, name, invalidate_cache, NULL) < 0)
2046 return -1;
2047 */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002048 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
2049 return -1;
2050 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002051}
2052
2053static void
2054type_dealloc(PyTypeObject *type)
2055{
Guido van Rossume5c691a2003-03-07 15:13:17 +00002056 PyHeapTypeObject *et;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002057
2058 /* Assert this is a heap-allocated type object */
2059 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002060 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00002061 PyObject_ClearWeakRefs((PyObject *)type);
Guido van Rossume5c691a2003-03-07 15:13:17 +00002062 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002063 Py_XDECREF(type->tp_base);
2064 Py_XDECREF(type->tp_dict);
2065 Py_XDECREF(type->tp_bases);
2066 Py_XDECREF(type->tp_mro);
Guido van Rossum687ae002001-10-15 22:03:32 +00002067 Py_XDECREF(type->tp_cache);
Guido van Rossum1c450732001-10-08 15:18:27 +00002068 Py_XDECREF(type->tp_subclasses);
Neal Norwitzcee5ca02002-07-30 00:42:06 +00002069 PyObject_Free(type->tp_doc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002070 Py_XDECREF(et->name);
2071 Py_XDECREF(et->slots);
2072 type->ob_type->tp_free((PyObject *)type);
2073}
2074
Guido van Rossum1c450732001-10-08 15:18:27 +00002075static PyObject *
2076type_subclasses(PyTypeObject *type, PyObject *args_ignored)
2077{
2078 PyObject *list, *raw, *ref;
2079 int i, n;
2080
2081 list = PyList_New(0);
2082 if (list == NULL)
2083 return NULL;
2084 raw = type->tp_subclasses;
2085 if (raw == NULL)
2086 return list;
2087 assert(PyList_Check(raw));
2088 n = PyList_GET_SIZE(raw);
2089 for (i = 0; i < n; i++) {
2090 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00002091 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00002092 ref = PyWeakref_GET_OBJECT(ref);
2093 if (ref != Py_None) {
2094 if (PyList_Append(list, ref) < 0) {
2095 Py_DECREF(list);
2096 return NULL;
2097 }
2098 }
2099 }
2100 return list;
2101}
2102
Tim Peters6d6c1a32001-08-02 04:15:00 +00002103static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002104 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002105 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
Guido van Rossum1c450732001-10-08 15:18:27 +00002106 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002107 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002108 {0}
2109};
2110
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002111PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002112"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002113"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002114
Guido van Rossum048eb752001-10-02 21:24:57 +00002115static int
2116type_traverse(PyTypeObject *type, visitproc visit, void *arg)
2117{
Guido van Rossum048eb752001-10-02 21:24:57 +00002118 int err;
2119
Guido van Rossuma3862092002-06-10 15:24:42 +00002120 /* Because of type_is_gc(), the collector only calls this
2121 for heaptypes. */
2122 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002123
2124#define VISIT(SLOT) \
2125 if (SLOT) { \
2126 err = visit((PyObject *)(SLOT), arg); \
2127 if (err) \
2128 return err; \
2129 }
2130
2131 VISIT(type->tp_dict);
Guido van Rossum687ae002001-10-15 22:03:32 +00002132 VISIT(type->tp_cache);
Guido van Rossum048eb752001-10-02 21:24:57 +00002133 VISIT(type->tp_mro);
2134 VISIT(type->tp_bases);
2135 VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00002136
2137 /* There's no need to visit type->tp_subclasses or
Guido van Rossume5c691a2003-03-07 15:13:17 +00002138 ((PyHeapTypeObject *)type)->slots, because they can't be involved
Guido van Rossuma3862092002-06-10 15:24:42 +00002139 in cycles; tp_subclasses is a list of weak references,
2140 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00002141
2142#undef VISIT
2143
2144 return 0;
2145}
2146
2147static int
2148type_clear(PyTypeObject *type)
2149{
Guido van Rossum048eb752001-10-02 21:24:57 +00002150 PyObject *tmp;
2151
Guido van Rossuma3862092002-06-10 15:24:42 +00002152 /* Because of type_is_gc(), the collector only calls this
2153 for heaptypes. */
2154 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002155
2156#define CLEAR(SLOT) \
2157 if (SLOT) { \
2158 tmp = (PyObject *)(SLOT); \
2159 SLOT = NULL; \
2160 Py_DECREF(tmp); \
2161 }
2162
Guido van Rossuma3862092002-06-10 15:24:42 +00002163 /* The only field we need to clear is tp_mro, which is part of a
2164 hard cycle (its first element is the class itself) that won't
2165 be broken otherwise (it's a tuple and tuples don't have a
2166 tp_clear handler). None of the other fields need to be
2167 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00002168
Guido van Rossuma3862092002-06-10 15:24:42 +00002169 tp_dict:
2170 It is a dict, so the collector will call its tp_clear.
2171
2172 tp_cache:
2173 Not used; if it were, it would be a dict.
2174
2175 tp_bases, tp_base:
2176 If these are involved in a cycle, there must be at least
2177 one other, mutable object in the cycle, e.g. a base
2178 class's dict; the cycle will be broken that way.
2179
2180 tp_subclasses:
2181 A list of weak references can't be part of a cycle; and
2182 lists have their own tp_clear.
2183
Guido van Rossume5c691a2003-03-07 15:13:17 +00002184 slots (in PyHeapTypeObject):
Guido van Rossuma3862092002-06-10 15:24:42 +00002185 A tuple of strings can't be part of a cycle.
2186 */
2187
2188 CLEAR(type->tp_mro);
Tim Peters2f93e282001-10-04 05:27:00 +00002189
Guido van Rossum048eb752001-10-02 21:24:57 +00002190#undef CLEAR
2191
2192 return 0;
2193}
2194
2195static int
2196type_is_gc(PyTypeObject *type)
2197{
2198 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
2199}
2200
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002201PyTypeObject PyType_Type = {
2202 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002203 0, /* ob_size */
2204 "type", /* tp_name */
Guido van Rossume5c691a2003-03-07 15:13:17 +00002205 sizeof(PyHeapTypeObject), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00002206 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002207 (destructor)type_dealloc, /* tp_dealloc */
2208 0, /* tp_print */
2209 0, /* tp_getattr */
2210 0, /* tp_setattr */
2211 type_compare, /* tp_compare */
2212 (reprfunc)type_repr, /* tp_repr */
2213 0, /* tp_as_number */
2214 0, /* tp_as_sequence */
2215 0, /* tp_as_mapping */
2216 (hashfunc)_Py_HashPointer, /* tp_hash */
2217 (ternaryfunc)type_call, /* tp_call */
2218 0, /* tp_str */
2219 (getattrofunc)type_getattro, /* tp_getattro */
2220 (setattrofunc)type_setattro, /* tp_setattro */
2221 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00002222 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2223 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002224 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00002225 (traverseproc)type_traverse, /* tp_traverse */
2226 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002227 0, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00002228 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002229 0, /* tp_iter */
2230 0, /* tp_iternext */
2231 type_methods, /* tp_methods */
2232 type_members, /* tp_members */
2233 type_getsets, /* tp_getset */
2234 0, /* tp_base */
2235 0, /* tp_dict */
2236 0, /* tp_descr_get */
2237 0, /* tp_descr_set */
2238 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
2239 0, /* tp_init */
2240 0, /* tp_alloc */
2241 type_new, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002242 PyObject_GC_Del, /* tp_free */
Guido van Rossum048eb752001-10-02 21:24:57 +00002243 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002244};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002245
2246
2247/* The base type of all types (eventually)... except itself. */
2248
2249static int
2250object_init(PyObject *self, PyObject *args, PyObject *kwds)
2251{
2252 return 0;
2253}
2254
Guido van Rossum298e4212003-02-13 16:30:16 +00002255/* If we don't have a tp_new for a new-style class, new will use this one.
2256 Therefore this should take no arguments/keywords. However, this new may
2257 also be inherited by objects that define a tp_init but no tp_new. These
2258 objects WILL pass argumets to tp_new, because it gets the same args as
2259 tp_init. So only allow arguments if we aren't using the default init, in
2260 which case we expect init to handle argument parsing. */
2261static PyObject *
2262object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2263{
2264 if (type->tp_init == object_init && (PyTuple_GET_SIZE(args) ||
2265 (kwds && PyDict_Check(kwds) && PyDict_Size(kwds)))) {
2266 PyErr_SetString(PyExc_TypeError,
2267 "default __new__ takes no parameters");
2268 return NULL;
2269 }
2270 return type->tp_alloc(type, 0);
2271}
2272
Tim Peters6d6c1a32001-08-02 04:15:00 +00002273static void
2274object_dealloc(PyObject *self)
2275{
2276 self->ob_type->tp_free(self);
2277}
2278
Guido van Rossum8e248182001-08-12 05:17:56 +00002279static PyObject *
2280object_repr(PyObject *self)
2281{
Guido van Rossum76e69632001-08-16 18:52:43 +00002282 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00002283 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002284
Guido van Rossum76e69632001-08-16 18:52:43 +00002285 type = self->ob_type;
2286 mod = type_module(type, NULL);
2287 if (mod == NULL)
2288 PyErr_Clear();
2289 else if (!PyString_Check(mod)) {
2290 Py_DECREF(mod);
2291 mod = NULL;
2292 }
2293 name = type_name(type, NULL);
2294 if (name == NULL)
2295 return NULL;
2296 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002297 rtn = PyString_FromFormat("<%s.%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002298 PyString_AS_STRING(mod),
2299 PyString_AS_STRING(name),
2300 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002301 else
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002302 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002303 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002304 Py_XDECREF(mod);
2305 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00002306 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002307}
2308
Guido van Rossumb8f63662001-08-15 23:57:02 +00002309static PyObject *
2310object_str(PyObject *self)
2311{
2312 unaryfunc f;
2313
2314 f = self->ob_type->tp_repr;
2315 if (f == NULL)
2316 f = object_repr;
2317 return f(self);
2318}
2319
Guido van Rossum8e248182001-08-12 05:17:56 +00002320static long
2321object_hash(PyObject *self)
2322{
2323 return _Py_HashPointer(self);
2324}
Guido van Rossum8e248182001-08-12 05:17:56 +00002325
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002326static PyObject *
2327object_get_class(PyObject *self, void *closure)
2328{
2329 Py_INCREF(self->ob_type);
2330 return (PyObject *)(self->ob_type);
2331}
2332
2333static int
2334equiv_structs(PyTypeObject *a, PyTypeObject *b)
2335{
2336 return a == b ||
2337 (a != NULL &&
2338 b != NULL &&
2339 a->tp_basicsize == b->tp_basicsize &&
2340 a->tp_itemsize == b->tp_itemsize &&
2341 a->tp_dictoffset == b->tp_dictoffset &&
2342 a->tp_weaklistoffset == b->tp_weaklistoffset &&
2343 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
2344 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
2345}
2346
2347static int
2348same_slots_added(PyTypeObject *a, PyTypeObject *b)
2349{
2350 PyTypeObject *base = a->tp_base;
2351 int size;
2352
2353 if (base != b->tp_base)
2354 return 0;
2355 if (equiv_structs(a, base) && equiv_structs(b, base))
2356 return 1;
2357 size = base->tp_basicsize;
2358 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
2359 size += sizeof(PyObject *);
2360 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
2361 size += sizeof(PyObject *);
2362 return size == a->tp_basicsize && size == b->tp_basicsize;
2363}
2364
2365static int
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002366compatible_for_assignment(PyTypeObject* old, PyTypeObject* new, char* attr)
2367{
2368 PyTypeObject *newbase, *oldbase;
2369
2370 if (new->tp_dealloc != old->tp_dealloc ||
2371 new->tp_free != old->tp_free)
2372 {
2373 PyErr_Format(PyExc_TypeError,
2374 "%s assignment: "
2375 "'%s' deallocator differs from '%s'",
2376 attr,
2377 new->tp_name,
2378 old->tp_name);
2379 return 0;
2380 }
2381 newbase = new;
2382 oldbase = old;
2383 while (equiv_structs(newbase, newbase->tp_base))
2384 newbase = newbase->tp_base;
2385 while (equiv_structs(oldbase, oldbase->tp_base))
2386 oldbase = oldbase->tp_base;
2387 if (newbase != oldbase &&
2388 (newbase->tp_base != oldbase->tp_base ||
2389 !same_slots_added(newbase, oldbase))) {
2390 PyErr_Format(PyExc_TypeError,
2391 "%s assignment: "
2392 "'%s' object layout differs from '%s'",
2393 attr,
2394 new->tp_name,
2395 old->tp_name);
2396 return 0;
2397 }
Tim Petersea7f75d2002-12-07 21:39:16 +00002398
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002399 return 1;
2400}
2401
2402static int
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002403object_set_class(PyObject *self, PyObject *value, void *closure)
2404{
2405 PyTypeObject *old = self->ob_type;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002406 PyTypeObject *new;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002407
Guido van Rossumb6b89422002-04-15 01:03:30 +00002408 if (value == NULL) {
2409 PyErr_SetString(PyExc_TypeError,
2410 "can't delete __class__ attribute");
2411 return -1;
2412 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002413 if (!PyType_Check(value)) {
2414 PyErr_Format(PyExc_TypeError,
2415 "__class__ must be set to new-style class, not '%s' object",
2416 value->ob_type->tp_name);
2417 return -1;
2418 }
2419 new = (PyTypeObject *)value;
Guido van Rossum40af8892002-08-10 05:42:07 +00002420 if (!(new->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
2421 !(old->tp_flags & Py_TPFLAGS_HEAPTYPE))
2422 {
2423 PyErr_Format(PyExc_TypeError,
2424 "__class__ assignment: only for heap types");
2425 return -1;
2426 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002427 if (compatible_for_assignment(new, old, "__class__")) {
2428 Py_INCREF(new);
2429 self->ob_type = new;
2430 Py_DECREF(old);
2431 return 0;
2432 }
2433 else {
Guido van Rossum9ee4b942002-05-24 18:47:47 +00002434 return -1;
2435 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002436}
2437
2438static PyGetSetDef object_getsets[] = {
2439 {"__class__", object_get_class, object_set_class,
Neal Norwitz858e34f2002-08-13 17:18:45 +00002440 PyDoc_STR("the object's class")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002441 {0}
2442};
2443
Guido van Rossumc53f0092003-02-18 22:05:12 +00002444
Guido van Rossum036f9992003-02-21 22:02:54 +00002445/* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
2446 We fall back to helpers in copy_reg for:
2447 - pickle protocols < 2
2448 - calculating the list of slot names (done only once per class)
2449 - the __newobj__ function (which is used as a token but never called)
2450*/
2451
2452static PyObject *
2453import_copy_reg(void)
2454{
2455 static PyObject *copy_reg_str;
Guido van Rossum3926a632001-09-25 16:25:58 +00002456
2457 if (!copy_reg_str) {
2458 copy_reg_str = PyString_InternFromString("copy_reg");
2459 if (copy_reg_str == NULL)
2460 return NULL;
2461 }
Guido van Rossum036f9992003-02-21 22:02:54 +00002462
2463 return PyImport_Import(copy_reg_str);
2464}
2465
2466static PyObject *
2467slotnames(PyObject *cls)
2468{
2469 PyObject *clsdict;
2470 PyObject *copy_reg;
2471 PyObject *slotnames;
2472
2473 if (!PyType_Check(cls)) {
2474 Py_INCREF(Py_None);
2475 return Py_None;
2476 }
2477
2478 clsdict = ((PyTypeObject *)cls)->tp_dict;
2479 slotnames = PyDict_GetItemString(clsdict, "__slotnames__");
2480 if (slotnames != NULL) {
2481 Py_INCREF(slotnames);
2482 return slotnames;
2483 }
2484
2485 copy_reg = import_copy_reg();
2486 if (copy_reg == NULL)
2487 return NULL;
2488
2489 slotnames = PyObject_CallMethod(copy_reg, "_slotnames", "O", cls);
2490 Py_DECREF(copy_reg);
2491 if (slotnames != NULL &&
2492 slotnames != Py_None &&
2493 !PyList_Check(slotnames))
2494 {
2495 PyErr_SetString(PyExc_TypeError,
2496 "copy_reg._slotnames didn't return a list or None");
2497 Py_DECREF(slotnames);
2498 slotnames = NULL;
2499 }
2500
2501 return slotnames;
2502}
2503
2504static PyObject *
2505reduce_2(PyObject *obj)
2506{
2507 PyObject *cls, *getnewargs;
2508 PyObject *args = NULL, *args2 = NULL;
2509 PyObject *getstate = NULL, *state = NULL, *names = NULL;
2510 PyObject *slots = NULL, *listitems = NULL, *dictitems = NULL;
2511 PyObject *copy_reg = NULL, *newobj = NULL, *res = NULL;
2512 int i, n;
2513
2514 cls = PyObject_GetAttrString(obj, "__class__");
2515 if (cls == NULL)
2516 return NULL;
2517
2518 getnewargs = PyObject_GetAttrString(obj, "__getnewargs__");
2519 if (getnewargs != NULL) {
2520 args = PyObject_CallObject(getnewargs, NULL);
2521 Py_DECREF(getnewargs);
2522 if (args != NULL && !PyTuple_Check(args)) {
2523 PyErr_SetString(PyExc_TypeError,
2524 "__getnewargs__ should return a tuple");
2525 goto end;
2526 }
2527 }
2528 else {
2529 PyErr_Clear();
2530 args = PyTuple_New(0);
2531 }
2532 if (args == NULL)
2533 goto end;
2534
2535 getstate = PyObject_GetAttrString(obj, "__getstate__");
2536 if (getstate != NULL) {
2537 state = PyObject_CallObject(getstate, NULL);
2538 Py_DECREF(getstate);
Neal Norwitze2fdc612003-06-08 13:19:58 +00002539 if (state == NULL)
2540 goto end;
Guido van Rossum036f9992003-02-21 22:02:54 +00002541 }
2542 else {
2543 state = PyObject_GetAttrString(obj, "__dict__");
2544 if (state == NULL) {
2545 PyErr_Clear();
2546 state = Py_None;
2547 Py_INCREF(state);
2548 }
2549 names = slotnames(cls);
2550 if (names == NULL)
2551 goto end;
2552 if (names != Py_None) {
2553 assert(PyList_Check(names));
2554 slots = PyDict_New();
2555 if (slots == NULL)
2556 goto end;
2557 n = 0;
2558 /* Can't pre-compute the list size; the list
2559 is stored on the class so accessible to other
2560 threads, which may be run by DECREF */
2561 for (i = 0; i < PyList_GET_SIZE(names); i++) {
2562 PyObject *name, *value;
2563 name = PyList_GET_ITEM(names, i);
2564 value = PyObject_GetAttr(obj, name);
2565 if (value == NULL)
2566 PyErr_Clear();
2567 else {
2568 int err = PyDict_SetItem(slots, name,
2569 value);
2570 Py_DECREF(value);
2571 if (err)
2572 goto end;
2573 n++;
2574 }
2575 }
2576 if (n) {
2577 state = Py_BuildValue("(NO)", state, slots);
2578 if (state == NULL)
2579 goto end;
2580 }
2581 }
2582 }
2583
2584 if (!PyList_Check(obj)) {
2585 listitems = Py_None;
2586 Py_INCREF(listitems);
2587 }
2588 else {
2589 listitems = PyObject_GetIter(obj);
2590 if (listitems == NULL)
2591 goto end;
2592 }
2593
2594 if (!PyDict_Check(obj)) {
2595 dictitems = Py_None;
2596 Py_INCREF(dictitems);
2597 }
2598 else {
2599 dictitems = PyObject_CallMethod(obj, "iteritems", "");
2600 if (dictitems == NULL)
2601 goto end;
2602 }
2603
2604 copy_reg = import_copy_reg();
2605 if (copy_reg == NULL)
2606 goto end;
2607 newobj = PyObject_GetAttrString(copy_reg, "__newobj__");
2608 if (newobj == NULL)
2609 goto end;
2610
2611 n = PyTuple_GET_SIZE(args);
2612 args2 = PyTuple_New(n+1);
2613 if (args2 == NULL)
2614 goto end;
2615 PyTuple_SET_ITEM(args2, 0, cls);
2616 cls = NULL;
2617 for (i = 0; i < n; i++) {
2618 PyObject *v = PyTuple_GET_ITEM(args, i);
2619 Py_INCREF(v);
2620 PyTuple_SET_ITEM(args2, i+1, v);
2621 }
2622
2623 res = Py_BuildValue("(OOOOO)",
2624 newobj, args2, state, listitems, dictitems);
2625
2626 end:
2627 Py_XDECREF(cls);
2628 Py_XDECREF(args);
2629 Py_XDECREF(args2);
Jeremy Hyltond06483c2003-04-09 21:01:42 +00002630 Py_XDECREF(slots);
Guido van Rossum036f9992003-02-21 22:02:54 +00002631 Py_XDECREF(state);
2632 Py_XDECREF(names);
2633 Py_XDECREF(listitems);
2634 Py_XDECREF(dictitems);
2635 Py_XDECREF(copy_reg);
2636 Py_XDECREF(newobj);
2637 return res;
2638}
2639
2640static PyObject *
2641object_reduce_ex(PyObject *self, PyObject *args)
2642{
2643 /* Call copy_reg._reduce_ex(self, proto) */
2644 PyObject *reduce, *copy_reg, *res;
2645 int proto = 0;
2646
2647 if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
2648 return NULL;
2649
2650 reduce = PyObject_GetAttrString(self, "__reduce__");
2651 if (reduce == NULL)
2652 PyErr_Clear();
2653 else {
2654 PyObject *cls, *clsreduce, *objreduce;
2655 int override;
2656 cls = PyObject_GetAttrString(self, "__class__");
2657 if (cls == NULL) {
2658 Py_DECREF(reduce);
2659 return NULL;
2660 }
2661 clsreduce = PyObject_GetAttrString(cls, "__reduce__");
2662 Py_DECREF(cls);
2663 if (clsreduce == NULL) {
2664 Py_DECREF(reduce);
2665 return NULL;
2666 }
2667 objreduce = PyDict_GetItemString(PyBaseObject_Type.tp_dict,
2668 "__reduce__");
2669 override = (clsreduce != objreduce);
2670 Py_DECREF(clsreduce);
2671 if (override) {
2672 res = PyObject_CallObject(reduce, NULL);
2673 Py_DECREF(reduce);
2674 return res;
2675 }
2676 else
2677 Py_DECREF(reduce);
2678 }
2679
2680 if (proto >= 2)
2681 return reduce_2(self);
2682
2683 copy_reg = import_copy_reg();
Guido van Rossum3926a632001-09-25 16:25:58 +00002684 if (!copy_reg)
2685 return NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00002686
Guido van Rossumc53f0092003-02-18 22:05:12 +00002687 res = PyEval_CallMethod(copy_reg, "_reduce_ex", "(Oi)", self, proto);
Guido van Rossum3926a632001-09-25 16:25:58 +00002688 Py_DECREF(copy_reg);
Guido van Rossum036f9992003-02-21 22:02:54 +00002689
Guido van Rossum3926a632001-09-25 16:25:58 +00002690 return res;
2691}
2692
2693static PyMethodDef object_methods[] = {
Guido van Rossumc53f0092003-02-18 22:05:12 +00002694 {"__reduce_ex__", object_reduce_ex, METH_VARARGS,
2695 PyDoc_STR("helper for pickle")},
2696 {"__reduce__", object_reduce_ex, METH_VARARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002697 PyDoc_STR("helper for pickle")},
Guido van Rossum3926a632001-09-25 16:25:58 +00002698 {0}
2699};
2700
Guido van Rossum036f9992003-02-21 22:02:54 +00002701
Tim Peters6d6c1a32001-08-02 04:15:00 +00002702PyTypeObject PyBaseObject_Type = {
2703 PyObject_HEAD_INIT(&PyType_Type)
2704 0, /* ob_size */
2705 "object", /* tp_name */
2706 sizeof(PyObject), /* tp_basicsize */
2707 0, /* tp_itemsize */
2708 (destructor)object_dealloc, /* tp_dealloc */
2709 0, /* tp_print */
2710 0, /* tp_getattr */
2711 0, /* tp_setattr */
2712 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002713 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002714 0, /* tp_as_number */
2715 0, /* tp_as_sequence */
2716 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002717 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002718 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002719 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002720 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002721 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002722 0, /* tp_as_buffer */
2723 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002724 PyDoc_STR("The most base type"), /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002725 0, /* tp_traverse */
2726 0, /* tp_clear */
2727 0, /* tp_richcompare */
2728 0, /* tp_weaklistoffset */
2729 0, /* tp_iter */
2730 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00002731 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002732 0, /* tp_members */
2733 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002734 0, /* tp_base */
2735 0, /* tp_dict */
2736 0, /* tp_descr_get */
2737 0, /* tp_descr_set */
2738 0, /* tp_dictoffset */
2739 object_init, /* tp_init */
2740 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossum298e4212003-02-13 16:30:16 +00002741 object_new, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002742 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002743};
2744
2745
2746/* Initialize the __dict__ in a type object */
2747
2748static int
2749add_methods(PyTypeObject *type, PyMethodDef *meth)
2750{
Guido van Rossum687ae002001-10-15 22:03:32 +00002751 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002752
2753 for (; meth->ml_name != NULL; meth++) {
2754 PyObject *descr;
2755 if (PyDict_GetItemString(dict, meth->ml_name))
2756 continue;
Fred Drake7bf97152002-03-28 05:33:33 +00002757 if (meth->ml_flags & METH_CLASS) {
2758 if (meth->ml_flags & METH_STATIC) {
2759 PyErr_SetString(PyExc_ValueError,
2760 "method cannot be both class and static");
2761 return -1;
2762 }
Tim Petersbca1cbc2002-12-09 22:56:13 +00002763 descr = PyDescr_NewClassMethod(type, meth);
Fred Drake7bf97152002-03-28 05:33:33 +00002764 }
2765 else if (meth->ml_flags & METH_STATIC) {
Guido van Rossum9af48ff2003-02-11 17:12:46 +00002766 PyObject *cfunc = PyCFunction_New(meth, NULL);
2767 if (cfunc == NULL)
2768 return -1;
2769 descr = PyStaticMethod_New(cfunc);
2770 Py_DECREF(cfunc);
Fred Drake7bf97152002-03-28 05:33:33 +00002771 }
2772 else {
2773 descr = PyDescr_NewMethod(type, meth);
2774 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002775 if (descr == NULL)
2776 return -1;
Fred Drake7bf97152002-03-28 05:33:33 +00002777 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002778 return -1;
2779 Py_DECREF(descr);
2780 }
2781 return 0;
2782}
2783
2784static int
Guido van Rossum6f799372001-09-20 20:46:19 +00002785add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002786{
Guido van Rossum687ae002001-10-15 22:03:32 +00002787 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002788
2789 for (; memb->name != NULL; memb++) {
2790 PyObject *descr;
2791 if (PyDict_GetItemString(dict, memb->name))
2792 continue;
2793 descr = PyDescr_NewMember(type, memb);
2794 if (descr == NULL)
2795 return -1;
2796 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
2797 return -1;
2798 Py_DECREF(descr);
2799 }
2800 return 0;
2801}
2802
2803static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00002804add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002805{
Guido van Rossum687ae002001-10-15 22:03:32 +00002806 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002807
2808 for (; gsp->name != NULL; gsp++) {
2809 PyObject *descr;
2810 if (PyDict_GetItemString(dict, gsp->name))
2811 continue;
2812 descr = PyDescr_NewGetSet(type, gsp);
2813
2814 if (descr == NULL)
2815 return -1;
2816 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
2817 return -1;
2818 Py_DECREF(descr);
2819 }
2820 return 0;
2821}
2822
Guido van Rossum13d52f02001-08-10 21:24:08 +00002823static void
2824inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002825{
2826 int oldsize, newsize;
2827
Guido van Rossum13d52f02001-08-10 21:24:08 +00002828 /* Special flag magic */
2829 if (!type->tp_as_buffer && base->tp_as_buffer) {
2830 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
2831 type->tp_flags |=
2832 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
2833 }
2834 if (!type->tp_as_sequence && base->tp_as_sequence) {
2835 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
2836 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
2837 }
2838 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
2839 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
2840 if ((!type->tp_as_number && base->tp_as_number) ||
2841 (!type->tp_as_sequence && base->tp_as_sequence)) {
2842 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
2843 if (!type->tp_as_number && !type->tp_as_sequence) {
2844 type->tp_flags |= base->tp_flags &
2845 Py_TPFLAGS_HAVE_INPLACEOPS;
2846 }
2847 }
2848 /* Wow */
2849 }
2850 if (!type->tp_as_number && base->tp_as_number) {
2851 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
2852 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
2853 }
2854
2855 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00002856 oldsize = base->tp_basicsize;
2857 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
2858 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
2859 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00002860 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
2861 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00002862 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00002863 if (type->tp_traverse == NULL)
2864 type->tp_traverse = base->tp_traverse;
2865 if (type->tp_clear == NULL)
2866 type->tp_clear = base->tp_clear;
2867 }
2868 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
Guido van Rossumf884b742001-12-17 17:14:22 +00002869 /* The condition below could use some explanation.
2870 It appears that tp_new is not inherited for static types
2871 whose base class is 'object'; this seems to be a precaution
2872 so that old extension types don't suddenly become
2873 callable (object.__new__ wouldn't insure the invariants
2874 that the extension type's own factory function ensures).
2875 Heap types, of course, are under our control, so they do
2876 inherit tp_new; static extension types that specify some
2877 other built-in type as the default are considered
2878 new-style-aware so they also inherit object.__new__. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002879 if (base != &PyBaseObject_Type ||
2880 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2881 if (type->tp_new == NULL)
2882 type->tp_new = base->tp_new;
2883 }
2884 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00002885 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00002886
2887 /* Copy other non-function slots */
2888
2889#undef COPYVAL
2890#define COPYVAL(SLOT) \
2891 if (type->SLOT == 0) type->SLOT = base->SLOT
2892
2893 COPYVAL(tp_itemsize);
2894 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
2895 COPYVAL(tp_weaklistoffset);
2896 }
2897 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2898 COPYVAL(tp_dictoffset);
2899 }
Guido van Rossum13d52f02001-08-10 21:24:08 +00002900}
2901
2902static void
2903inherit_slots(PyTypeObject *type, PyTypeObject *base)
2904{
2905 PyTypeObject *basebase;
2906
2907#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00002908#undef COPYSLOT
2909#undef COPYNUM
2910#undef COPYSEQ
2911#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00002912#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00002913
2914#define SLOTDEFINED(SLOT) \
2915 (base->SLOT != 0 && \
2916 (basebase == NULL || base->SLOT != basebase->SLOT))
2917
Tim Peters6d6c1a32001-08-02 04:15:00 +00002918#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00002919 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00002920
2921#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
2922#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
2923#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00002924#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002925
Guido van Rossum13d52f02001-08-10 21:24:08 +00002926 /* This won't inherit indirect slots (from tp_as_number etc.)
2927 if type doesn't provide the space. */
2928
2929 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
2930 basebase = base->tp_base;
2931 if (basebase->tp_as_number == NULL)
2932 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002933 COPYNUM(nb_add);
2934 COPYNUM(nb_subtract);
2935 COPYNUM(nb_multiply);
2936 COPYNUM(nb_divide);
2937 COPYNUM(nb_remainder);
2938 COPYNUM(nb_divmod);
2939 COPYNUM(nb_power);
2940 COPYNUM(nb_negative);
2941 COPYNUM(nb_positive);
2942 COPYNUM(nb_absolute);
2943 COPYNUM(nb_nonzero);
2944 COPYNUM(nb_invert);
2945 COPYNUM(nb_lshift);
2946 COPYNUM(nb_rshift);
2947 COPYNUM(nb_and);
2948 COPYNUM(nb_xor);
2949 COPYNUM(nb_or);
2950 COPYNUM(nb_coerce);
2951 COPYNUM(nb_int);
2952 COPYNUM(nb_long);
2953 COPYNUM(nb_float);
2954 COPYNUM(nb_oct);
2955 COPYNUM(nb_hex);
2956 COPYNUM(nb_inplace_add);
2957 COPYNUM(nb_inplace_subtract);
2958 COPYNUM(nb_inplace_multiply);
2959 COPYNUM(nb_inplace_divide);
2960 COPYNUM(nb_inplace_remainder);
2961 COPYNUM(nb_inplace_power);
2962 COPYNUM(nb_inplace_lshift);
2963 COPYNUM(nb_inplace_rshift);
2964 COPYNUM(nb_inplace_and);
2965 COPYNUM(nb_inplace_xor);
2966 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00002967 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
2968 COPYNUM(nb_true_divide);
2969 COPYNUM(nb_floor_divide);
2970 COPYNUM(nb_inplace_true_divide);
2971 COPYNUM(nb_inplace_floor_divide);
2972 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002973 }
2974
Guido van Rossum13d52f02001-08-10 21:24:08 +00002975 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
2976 basebase = base->tp_base;
2977 if (basebase->tp_as_sequence == NULL)
2978 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002979 COPYSEQ(sq_length);
2980 COPYSEQ(sq_concat);
2981 COPYSEQ(sq_repeat);
2982 COPYSEQ(sq_item);
2983 COPYSEQ(sq_slice);
2984 COPYSEQ(sq_ass_item);
2985 COPYSEQ(sq_ass_slice);
2986 COPYSEQ(sq_contains);
2987 COPYSEQ(sq_inplace_concat);
2988 COPYSEQ(sq_inplace_repeat);
2989 }
2990
Guido van Rossum13d52f02001-08-10 21:24:08 +00002991 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
2992 basebase = base->tp_base;
2993 if (basebase->tp_as_mapping == NULL)
2994 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002995 COPYMAP(mp_length);
2996 COPYMAP(mp_subscript);
2997 COPYMAP(mp_ass_subscript);
2998 }
2999
Tim Petersfc57ccb2001-10-12 02:38:24 +00003000 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
3001 basebase = base->tp_base;
3002 if (basebase->tp_as_buffer == NULL)
3003 basebase = NULL;
3004 COPYBUF(bf_getreadbuffer);
3005 COPYBUF(bf_getwritebuffer);
3006 COPYBUF(bf_getsegcount);
3007 COPYBUF(bf_getcharbuffer);
3008 }
3009
Guido van Rossum13d52f02001-08-10 21:24:08 +00003010 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003011
Tim Peters6d6c1a32001-08-02 04:15:00 +00003012 COPYSLOT(tp_dealloc);
3013 COPYSLOT(tp_print);
3014 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
3015 type->tp_getattr = base->tp_getattr;
3016 type->tp_getattro = base->tp_getattro;
3017 }
3018 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
3019 type->tp_setattr = base->tp_setattr;
3020 type->tp_setattro = base->tp_setattro;
3021 }
3022 /* tp_compare see tp_richcompare */
3023 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003024 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003025 COPYSLOT(tp_call);
3026 COPYSLOT(tp_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003027 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003028 if (type->tp_compare == NULL &&
3029 type->tp_richcompare == NULL &&
3030 type->tp_hash == NULL)
3031 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003032 type->tp_compare = base->tp_compare;
3033 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003034 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003035 }
3036 }
3037 else {
3038 COPYSLOT(tp_compare);
3039 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003040 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
3041 COPYSLOT(tp_iter);
3042 COPYSLOT(tp_iternext);
3043 }
3044 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
3045 COPYSLOT(tp_descr_get);
3046 COPYSLOT(tp_descr_set);
3047 COPYSLOT(tp_dictoffset);
3048 COPYSLOT(tp_init);
3049 COPYSLOT(tp_alloc);
Guido van Rossumcc8fe042002-04-05 17:10:16 +00003050 COPYSLOT(tp_is_gc);
Tim Peters3cfe7542003-05-21 21:29:48 +00003051 if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) ==
3052 (base->tp_flags & Py_TPFLAGS_HAVE_GC)) {
3053 /* They agree about gc. */
3054 COPYSLOT(tp_free);
3055 }
3056 else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3057 type->tp_free == NULL &&
3058 base->tp_free == _PyObject_Del) {
3059 /* A bit of magic to plug in the correct default
3060 * tp_free function when a derived class adds gc,
3061 * didn't define tp_free, and the base uses the
3062 * default non-gc tp_free.
3063 */
3064 type->tp_free = PyObject_GC_Del;
3065 }
3066 /* else they didn't agree about gc, and there isn't something
3067 * obvious to be done -- the type is on its own.
3068 */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003069 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003070}
3071
Jeremy Hylton938ace62002-07-17 16:30:39 +00003072static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00003073
Tim Peters6d6c1a32001-08-02 04:15:00 +00003074int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00003075PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003076{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003077 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003078 PyTypeObject *base;
3079 int i, n;
3080
Guido van Rossumcab05802002-06-10 15:29:03 +00003081 if (type->tp_flags & Py_TPFLAGS_READY) {
3082 assert(type->tp_dict != NULL);
Guido van Rossumd614f972001-08-10 17:39:49 +00003083 return 0;
Guido van Rossumcab05802002-06-10 15:29:03 +00003084 }
Guido van Rossumd614f972001-08-10 17:39:49 +00003085 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00003086
3087 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003088
Tim Peters36eb4df2003-03-23 03:33:13 +00003089#ifdef Py_TRACE_REFS
3090 /* PyType_Ready is the closest thing we have to a choke point
3091 * for type objects, so is the best place I can think of to try
3092 * to get type objects into the doubly-linked list of all objects.
3093 * Still, not all type objects go thru PyType_Ready.
3094 */
Tim Peters7571a0f2003-03-23 17:52:28 +00003095 _Py_AddToAllObjects((PyObject *)type, 0);
Tim Peters36eb4df2003-03-23 03:33:13 +00003096#endif
3097
Tim Peters6d6c1a32001-08-02 04:15:00 +00003098 /* Initialize tp_base (defaults to BaseObject unless that's us) */
3099 base = type->tp_base;
3100 if (base == NULL && type != &PyBaseObject_Type)
3101 base = type->tp_base = &PyBaseObject_Type;
3102
Guido van Rossum323a9cf2002-08-14 17:26:30 +00003103 /* Initialize the base class */
3104 if (base && base->tp_dict == NULL) {
3105 if (PyType_Ready(base) < 0)
3106 goto error;
3107 }
3108
Guido van Rossum0986d822002-04-08 01:38:42 +00003109 /* Initialize ob_type if NULL. This means extensions that want to be
3110 compilable separately on Windows can call PyType_Ready() instead of
3111 initializing the ob_type field of their type objects. */
3112 if (type->ob_type == NULL)
3113 type->ob_type = base->ob_type;
3114
Tim Peters6d6c1a32001-08-02 04:15:00 +00003115 /* Initialize tp_bases */
3116 bases = type->tp_bases;
3117 if (bases == NULL) {
3118 if (base == NULL)
3119 bases = PyTuple_New(0);
3120 else
3121 bases = Py_BuildValue("(O)", base);
3122 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003123 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003124 type->tp_bases = bases;
3125 }
3126
Guido van Rossum687ae002001-10-15 22:03:32 +00003127 /* Initialize tp_dict */
3128 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003129 if (dict == NULL) {
3130 dict = PyDict_New();
3131 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003132 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00003133 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003134 }
3135
Guido van Rossum687ae002001-10-15 22:03:32 +00003136 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003137 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003138 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003139 if (type->tp_methods != NULL) {
3140 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003141 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003142 }
3143 if (type->tp_members != NULL) {
3144 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003145 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003146 }
3147 if (type->tp_getset != NULL) {
3148 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003149 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003150 }
3151
Tim Peters6d6c1a32001-08-02 04:15:00 +00003152 /* Calculate method resolution order */
3153 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00003154 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003155 }
3156
Guido van Rossum13d52f02001-08-10 21:24:08 +00003157 /* Inherit special flags from dominant base */
3158 if (type->tp_base != NULL)
3159 inherit_special(type, type->tp_base);
3160
Tim Peters6d6c1a32001-08-02 04:15:00 +00003161 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003162 bases = type->tp_mro;
3163 assert(bases != NULL);
3164 assert(PyTuple_Check(bases));
3165 n = PyTuple_GET_SIZE(bases);
3166 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003167 PyObject *b = PyTuple_GET_ITEM(bases, i);
3168 if (PyType_Check(b))
3169 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003170 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003171
Tim Peters3cfe7542003-05-21 21:29:48 +00003172 /* Sanity check for tp_free. */
3173 if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) &&
3174 (type->tp_free == NULL || type->tp_free == PyObject_Del)) {
3175 /* This base class needs to call tp_free, but doesn't have
3176 * one, or its tp_free is for non-gc'ed objects.
3177 */
3178 PyErr_Format(PyExc_TypeError, "type '%.100s' participates in "
3179 "gc and is a base type but has inappropriate "
3180 "tp_free slot",
3181 type->tp_name);
3182 goto error;
3183 }
3184
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003185 /* if the type dictionary doesn't contain a __doc__, set it from
3186 the tp_doc slot.
3187 */
3188 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
3189 if (type->tp_doc != NULL) {
3190 PyObject *doc = PyString_FromString(type->tp_doc);
3191 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
3192 Py_DECREF(doc);
3193 } else {
Guido van Rossumd4641072002-04-03 02:13:37 +00003194 PyDict_SetItemString(type->tp_dict,
3195 "__doc__", Py_None);
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003196 }
3197 }
3198
Guido van Rossum13d52f02001-08-10 21:24:08 +00003199 /* Some more special stuff */
3200 base = type->tp_base;
3201 if (base != NULL) {
3202 if (type->tp_as_number == NULL)
3203 type->tp_as_number = base->tp_as_number;
3204 if (type->tp_as_sequence == NULL)
3205 type->tp_as_sequence = base->tp_as_sequence;
3206 if (type->tp_as_mapping == NULL)
3207 type->tp_as_mapping = base->tp_as_mapping;
Guido van Rossumeea47182003-02-11 20:39:59 +00003208 if (type->tp_as_buffer == NULL)
3209 type->tp_as_buffer = base->tp_as_buffer;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003210 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003211
Guido van Rossum1c450732001-10-08 15:18:27 +00003212 /* Link into each base class's list of subclasses */
3213 bases = type->tp_bases;
3214 n = PyTuple_GET_SIZE(bases);
3215 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003216 PyObject *b = PyTuple_GET_ITEM(bases, i);
3217 if (PyType_Check(b) &&
3218 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00003219 goto error;
3220 }
3221
Guido van Rossum13d52f02001-08-10 21:24:08 +00003222 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00003223 assert(type->tp_dict != NULL);
3224 type->tp_flags =
3225 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003226 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00003227
3228 error:
3229 type->tp_flags &= ~Py_TPFLAGS_READYING;
3230 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003231}
3232
Guido van Rossum1c450732001-10-08 15:18:27 +00003233static int
3234add_subclass(PyTypeObject *base, PyTypeObject *type)
3235{
3236 int i;
3237 PyObject *list, *ref, *new;
3238
3239 list = base->tp_subclasses;
3240 if (list == NULL) {
3241 base->tp_subclasses = list = PyList_New(0);
3242 if (list == NULL)
3243 return -1;
3244 }
3245 assert(PyList_Check(list));
3246 new = PyWeakref_NewRef((PyObject *)type, NULL);
3247 i = PyList_GET_SIZE(list);
3248 while (--i >= 0) {
3249 ref = PyList_GET_ITEM(list, i);
3250 assert(PyWeakref_CheckRef(ref));
Guido van Rossum3930bc32002-10-18 13:51:49 +00003251 if (PyWeakref_GET_OBJECT(ref) == Py_None)
3252 return PyList_SetItem(list, i, new);
Guido van Rossum1c450732001-10-08 15:18:27 +00003253 }
3254 i = PyList_Append(list, new);
3255 Py_DECREF(new);
3256 return i;
3257}
3258
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003259static void
3260remove_subclass(PyTypeObject *base, PyTypeObject *type)
3261{
3262 int i;
3263 PyObject *list, *ref;
3264
3265 list = base->tp_subclasses;
3266 if (list == NULL) {
3267 return;
3268 }
3269 assert(PyList_Check(list));
3270 i = PyList_GET_SIZE(list);
3271 while (--i >= 0) {
3272 ref = PyList_GET_ITEM(list, i);
3273 assert(PyWeakref_CheckRef(ref));
3274 if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
3275 /* this can't fail, right? */
3276 PySequence_DelItem(list, i);
3277 return;
3278 }
3279 }
3280}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003281
3282/* Generic wrappers for overloadable 'operators' such as __getitem__ */
3283
3284/* There's a wrapper *function* for each distinct function typedef used
3285 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
3286 wrapper *table* for each distinct operation (e.g. __len__, __add__).
3287 Most tables have only one entry; the tables for binary operators have two
3288 entries, one regular and one with reversed arguments. */
3289
3290static PyObject *
3291wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
3292{
3293 inquiry func = (inquiry)wrapped;
3294 int res;
3295
3296 if (!PyArg_ParseTuple(args, ""))
3297 return NULL;
3298 res = (*func)(self);
3299 if (res == -1 && PyErr_Occurred())
3300 return NULL;
3301 return PyInt_FromLong((long)res);
3302}
3303
Tim Peters6d6c1a32001-08-02 04:15:00 +00003304static PyObject *
3305wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
3306{
3307 binaryfunc func = (binaryfunc)wrapped;
3308 PyObject *other;
3309
3310 if (!PyArg_ParseTuple(args, "O", &other))
3311 return NULL;
3312 return (*func)(self, other);
3313}
3314
3315static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003316wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
3317{
3318 binaryfunc func = (binaryfunc)wrapped;
3319 PyObject *other;
3320
3321 if (!PyArg_ParseTuple(args, "O", &other))
3322 return NULL;
3323 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003324 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003325 Py_INCREF(Py_NotImplemented);
3326 return Py_NotImplemented;
3327 }
3328 return (*func)(self, other);
3329}
3330
3331static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003332wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3333{
3334 binaryfunc func = (binaryfunc)wrapped;
3335 PyObject *other;
3336
3337 if (!PyArg_ParseTuple(args, "O", &other))
3338 return NULL;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003339 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003340 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003341 Py_INCREF(Py_NotImplemented);
3342 return Py_NotImplemented;
3343 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003344 return (*func)(other, self);
3345}
3346
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003347static PyObject *
3348wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
3349{
3350 coercion func = (coercion)wrapped;
3351 PyObject *other, *res;
3352 int ok;
3353
3354 if (!PyArg_ParseTuple(args, "O", &other))
3355 return NULL;
3356 ok = func(&self, &other);
3357 if (ok < 0)
3358 return NULL;
3359 if (ok > 0) {
3360 Py_INCREF(Py_NotImplemented);
3361 return Py_NotImplemented;
3362 }
3363 res = PyTuple_New(2);
3364 if (res == NULL) {
3365 Py_DECREF(self);
3366 Py_DECREF(other);
3367 return NULL;
3368 }
3369 PyTuple_SET_ITEM(res, 0, self);
3370 PyTuple_SET_ITEM(res, 1, other);
3371 return res;
3372}
3373
Tim Peters6d6c1a32001-08-02 04:15:00 +00003374static PyObject *
3375wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
3376{
3377 ternaryfunc func = (ternaryfunc)wrapped;
3378 PyObject *other;
3379 PyObject *third = Py_None;
3380
3381 /* Note: This wrapper only works for __pow__() */
3382
3383 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
3384 return NULL;
3385 return (*func)(self, other, third);
3386}
3387
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00003388static PyObject *
3389wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3390{
3391 ternaryfunc func = (ternaryfunc)wrapped;
3392 PyObject *other;
3393 PyObject *third = Py_None;
3394
3395 /* Note: This wrapper only works for __pow__() */
3396
3397 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
3398 return NULL;
3399 return (*func)(other, self, third);
3400}
3401
Tim Peters6d6c1a32001-08-02 04:15:00 +00003402static PyObject *
3403wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
3404{
3405 unaryfunc func = (unaryfunc)wrapped;
3406
3407 if (!PyArg_ParseTuple(args, ""))
3408 return NULL;
3409 return (*func)(self);
3410}
3411
Tim Peters6d6c1a32001-08-02 04:15:00 +00003412static PyObject *
3413wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
3414{
3415 intargfunc func = (intargfunc)wrapped;
3416 int i;
3417
3418 if (!PyArg_ParseTuple(args, "i", &i))
3419 return NULL;
3420 return (*func)(self, i);
3421}
3422
Guido van Rossum5d815f32001-08-17 21:57:47 +00003423static int
3424getindex(PyObject *self, PyObject *arg)
3425{
3426 int i;
3427
3428 i = PyInt_AsLong(arg);
3429 if (i == -1 && PyErr_Occurred())
3430 return -1;
3431 if (i < 0) {
3432 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
3433 if (sq && sq->sq_length) {
3434 int n = (*sq->sq_length)(self);
3435 if (n < 0)
3436 return -1;
3437 i += n;
3438 }
3439 }
3440 return i;
3441}
3442
3443static PyObject *
3444wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
3445{
3446 intargfunc func = (intargfunc)wrapped;
3447 PyObject *arg;
3448 int i;
3449
Guido van Rossumf4593e02001-10-03 12:09:30 +00003450 if (PyTuple_GET_SIZE(args) == 1) {
3451 arg = PyTuple_GET_ITEM(args, 0);
3452 i = getindex(self, arg);
3453 if (i == -1 && PyErr_Occurred())
3454 return NULL;
3455 return (*func)(self, i);
3456 }
3457 PyArg_ParseTuple(args, "O", &arg);
3458 assert(PyErr_Occurred());
3459 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003460}
3461
Tim Peters6d6c1a32001-08-02 04:15:00 +00003462static PyObject *
3463wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
3464{
3465 intintargfunc func = (intintargfunc)wrapped;
3466 int i, j;
3467
3468 if (!PyArg_ParseTuple(args, "ii", &i, &j))
3469 return NULL;
3470 return (*func)(self, i, j);
3471}
3472
Tim Peters6d6c1a32001-08-02 04:15:00 +00003473static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003474wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003475{
3476 intobjargproc func = (intobjargproc)wrapped;
3477 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003478 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003479
Guido van Rossum5d815f32001-08-17 21:57:47 +00003480 if (!PyArg_ParseTuple(args, "OO", &arg, &value))
3481 return NULL;
3482 i = getindex(self, arg);
3483 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00003484 return NULL;
3485 res = (*func)(self, i, value);
3486 if (res == -1 && PyErr_Occurred())
3487 return NULL;
3488 Py_INCREF(Py_None);
3489 return Py_None;
3490}
3491
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003492static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003493wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003494{
3495 intobjargproc func = (intobjargproc)wrapped;
3496 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003497 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003498
Guido van Rossum5d815f32001-08-17 21:57:47 +00003499 if (!PyArg_ParseTuple(args, "O", &arg))
3500 return NULL;
3501 i = getindex(self, arg);
3502 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003503 return NULL;
3504 res = (*func)(self, i, NULL);
3505 if (res == -1 && PyErr_Occurred())
3506 return NULL;
3507 Py_INCREF(Py_None);
3508 return Py_None;
3509}
3510
Tim Peters6d6c1a32001-08-02 04:15:00 +00003511static PyObject *
3512wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
3513{
3514 intintobjargproc func = (intintobjargproc)wrapped;
3515 int i, j, res;
3516 PyObject *value;
3517
3518 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
3519 return NULL;
3520 res = (*func)(self, i, j, value);
3521 if (res == -1 && PyErr_Occurred())
3522 return NULL;
3523 Py_INCREF(Py_None);
3524 return Py_None;
3525}
3526
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003527static PyObject *
3528wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
3529{
3530 intintobjargproc func = (intintobjargproc)wrapped;
3531 int i, j, res;
3532
3533 if (!PyArg_ParseTuple(args, "ii", &i, &j))
3534 return NULL;
3535 res = (*func)(self, i, j, NULL);
3536 if (res == -1 && PyErr_Occurred())
3537 return NULL;
3538 Py_INCREF(Py_None);
3539 return Py_None;
3540}
3541
Tim Peters6d6c1a32001-08-02 04:15:00 +00003542/* XXX objobjproc is a misnomer; should be objargpred */
3543static PyObject *
3544wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
3545{
3546 objobjproc func = (objobjproc)wrapped;
3547 int res;
3548 PyObject *value;
3549
3550 if (!PyArg_ParseTuple(args, "O", &value))
3551 return NULL;
3552 res = (*func)(self, value);
3553 if (res == -1 && PyErr_Occurred())
3554 return NULL;
3555 return PyInt_FromLong((long)res);
3556}
3557
Tim Peters6d6c1a32001-08-02 04:15:00 +00003558static PyObject *
3559wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
3560{
3561 objobjargproc func = (objobjargproc)wrapped;
3562 int res;
3563 PyObject *key, *value;
3564
3565 if (!PyArg_ParseTuple(args, "OO", &key, &value))
3566 return NULL;
3567 res = (*func)(self, key, value);
3568 if (res == -1 && PyErr_Occurred())
3569 return NULL;
3570 Py_INCREF(Py_None);
3571 return Py_None;
3572}
3573
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003574static PyObject *
3575wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
3576{
3577 objobjargproc func = (objobjargproc)wrapped;
3578 int res;
3579 PyObject *key;
3580
3581 if (!PyArg_ParseTuple(args, "O", &key))
3582 return NULL;
3583 res = (*func)(self, key, NULL);
3584 if (res == -1 && PyErr_Occurred())
3585 return NULL;
3586 Py_INCREF(Py_None);
3587 return Py_None;
3588}
3589
Tim Peters6d6c1a32001-08-02 04:15:00 +00003590static PyObject *
3591wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
3592{
3593 cmpfunc func = (cmpfunc)wrapped;
3594 int res;
3595 PyObject *other;
3596
3597 if (!PyArg_ParseTuple(args, "O", &other))
3598 return NULL;
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00003599 if (other->ob_type->tp_compare != func &&
3600 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00003601 PyErr_Format(
3602 PyExc_TypeError,
3603 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
3604 self->ob_type->tp_name,
3605 self->ob_type->tp_name,
3606 other->ob_type->tp_name);
3607 return NULL;
3608 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003609 res = (*func)(self, other);
3610 if (PyErr_Occurred())
3611 return NULL;
3612 return PyInt_FromLong((long)res);
3613}
3614
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003615/* Helper to check for object.__setattr__ or __delattr__ applied to a type.
Guido van Rossum52b27052003-04-15 20:05:10 +00003616 This is called the Carlo Verre hack after its discoverer. */
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003617static int
3618hackcheck(PyObject *self, setattrofunc func, char *what)
3619{
3620 PyTypeObject *type = self->ob_type;
3621 while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE)
3622 type = type->tp_base;
3623 if (type->tp_setattro != func) {
3624 PyErr_Format(PyExc_TypeError,
3625 "can't apply this %s to %s object",
3626 what,
3627 type->tp_name);
3628 return 0;
3629 }
3630 return 1;
3631}
3632
Tim Peters6d6c1a32001-08-02 04:15:00 +00003633static PyObject *
3634wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
3635{
3636 setattrofunc func = (setattrofunc)wrapped;
3637 int res;
3638 PyObject *name, *value;
3639
3640 if (!PyArg_ParseTuple(args, "OO", &name, &value))
3641 return NULL;
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003642 if (!hackcheck(self, func, "__setattr__"))
3643 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003644 res = (*func)(self, name, value);
3645 if (res < 0)
3646 return NULL;
3647 Py_INCREF(Py_None);
3648 return Py_None;
3649}
3650
3651static PyObject *
3652wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
3653{
3654 setattrofunc func = (setattrofunc)wrapped;
3655 int res;
3656 PyObject *name;
3657
3658 if (!PyArg_ParseTuple(args, "O", &name))
3659 return NULL;
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003660 if (!hackcheck(self, func, "__delattr__"))
3661 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003662 res = (*func)(self, name, NULL);
3663 if (res < 0)
3664 return NULL;
3665 Py_INCREF(Py_None);
3666 return Py_None;
3667}
3668
Tim Peters6d6c1a32001-08-02 04:15:00 +00003669static PyObject *
3670wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
3671{
3672 hashfunc func = (hashfunc)wrapped;
3673 long res;
3674
3675 if (!PyArg_ParseTuple(args, ""))
3676 return NULL;
3677 res = (*func)(self);
3678 if (res == -1 && PyErr_Occurred())
3679 return NULL;
3680 return PyInt_FromLong(res);
3681}
3682
Tim Peters6d6c1a32001-08-02 04:15:00 +00003683static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00003684wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003685{
3686 ternaryfunc func = (ternaryfunc)wrapped;
3687
Guido van Rossumc8e56452001-10-22 00:43:43 +00003688 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003689}
3690
Tim Peters6d6c1a32001-08-02 04:15:00 +00003691static PyObject *
3692wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
3693{
3694 richcmpfunc func = (richcmpfunc)wrapped;
3695 PyObject *other;
3696
3697 if (!PyArg_ParseTuple(args, "O", &other))
3698 return NULL;
3699 return (*func)(self, other, op);
3700}
3701
3702#undef RICHCMP_WRAPPER
3703#define RICHCMP_WRAPPER(NAME, OP) \
3704static PyObject * \
3705richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
3706{ \
3707 return wrap_richcmpfunc(self, args, wrapped, OP); \
3708}
3709
Jack Jansen8e938b42001-08-08 15:29:49 +00003710RICHCMP_WRAPPER(lt, Py_LT)
3711RICHCMP_WRAPPER(le, Py_LE)
3712RICHCMP_WRAPPER(eq, Py_EQ)
3713RICHCMP_WRAPPER(ne, Py_NE)
3714RICHCMP_WRAPPER(gt, Py_GT)
3715RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003716
Tim Peters6d6c1a32001-08-02 04:15:00 +00003717static PyObject *
3718wrap_next(PyObject *self, PyObject *args, void *wrapped)
3719{
3720 unaryfunc func = (unaryfunc)wrapped;
3721 PyObject *res;
3722
3723 if (!PyArg_ParseTuple(args, ""))
3724 return NULL;
3725 res = (*func)(self);
3726 if (res == NULL && !PyErr_Occurred())
3727 PyErr_SetNone(PyExc_StopIteration);
3728 return res;
3729}
3730
Tim Peters6d6c1a32001-08-02 04:15:00 +00003731static PyObject *
3732wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
3733{
3734 descrgetfunc func = (descrgetfunc)wrapped;
3735 PyObject *obj;
3736 PyObject *type = NULL;
3737
3738 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
3739 return NULL;
Guido van Rossum82ed25c2003-02-11 16:25:43 +00003740 if (obj == Py_None)
3741 obj = NULL;
3742 if (type == Py_None)
3743 type = NULL;
3744 if (type == NULL &&obj == NULL) {
3745 PyErr_SetString(PyExc_TypeError,
3746 "__get__(None, None) is invalid");
3747 return NULL;
3748 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003749 return (*func)(self, obj, type);
3750}
3751
Tim Peters6d6c1a32001-08-02 04:15:00 +00003752static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003753wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003754{
3755 descrsetfunc func = (descrsetfunc)wrapped;
3756 PyObject *obj, *value;
3757 int ret;
3758
3759 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
3760 return NULL;
3761 ret = (*func)(self, obj, value);
3762 if (ret < 0)
3763 return NULL;
3764 Py_INCREF(Py_None);
3765 return Py_None;
3766}
Guido van Rossum22b13872002-08-06 21:41:44 +00003767
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00003768static PyObject *
3769wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
3770{
3771 descrsetfunc func = (descrsetfunc)wrapped;
3772 PyObject *obj;
3773 int ret;
3774
3775 if (!PyArg_ParseTuple(args, "O", &obj))
3776 return NULL;
3777 ret = (*func)(self, obj, NULL);
3778 if (ret < 0)
3779 return NULL;
3780 Py_INCREF(Py_None);
3781 return Py_None;
3782}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003783
Tim Peters6d6c1a32001-08-02 04:15:00 +00003784static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00003785wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003786{
3787 initproc func = (initproc)wrapped;
3788
Guido van Rossumc8e56452001-10-22 00:43:43 +00003789 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003790 return NULL;
3791 Py_INCREF(Py_None);
3792 return Py_None;
3793}
3794
Tim Peters6d6c1a32001-08-02 04:15:00 +00003795static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003796tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003797{
Barry Warsaw60f01882001-08-22 19:24:42 +00003798 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003799 PyObject *arg0, *res;
3800
3801 if (self == NULL || !PyType_Check(self))
3802 Py_FatalError("__new__() called with non-type 'self'");
3803 type = (PyTypeObject *)self;
3804 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003805 PyErr_Format(PyExc_TypeError,
3806 "%s.__new__(): not enough arguments",
3807 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003808 return NULL;
3809 }
3810 arg0 = PyTuple_GET_ITEM(args, 0);
3811 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003812 PyErr_Format(PyExc_TypeError,
3813 "%s.__new__(X): X is not a type object (%s)",
3814 type->tp_name,
3815 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003816 return NULL;
3817 }
3818 subtype = (PyTypeObject *)arg0;
3819 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003820 PyErr_Format(PyExc_TypeError,
3821 "%s.__new__(%s): %s is not a subtype of %s",
3822 type->tp_name,
3823 subtype->tp_name,
3824 subtype->tp_name,
3825 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003826 return NULL;
3827 }
Barry Warsaw60f01882001-08-22 19:24:42 +00003828
3829 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00003830 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00003831 most derived base that's not a heap type is this type. */
3832 staticbase = subtype;
3833 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
3834 staticbase = staticbase->tp_base;
Guido van Rossuma8c60f42001-09-14 19:43:36 +00003835 if (staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003836 PyErr_Format(PyExc_TypeError,
3837 "%s.__new__(%s) is not safe, use %s.__new__()",
3838 type->tp_name,
3839 subtype->tp_name,
3840 staticbase == NULL ? "?" : staticbase->tp_name);
3841 return NULL;
3842 }
3843
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003844 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
3845 if (args == NULL)
3846 return NULL;
3847 res = type->tp_new(subtype, args, kwds);
3848 Py_DECREF(args);
3849 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003850}
3851
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003852static struct PyMethodDef tp_new_methoddef[] = {
3853 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00003854 PyDoc_STR("T.__new__(S, ...) -> "
3855 "a new object with type S, a subtype of T")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00003856 {0}
3857};
3858
3859static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003860add_tp_new_wrapper(PyTypeObject *type)
3861{
Guido van Rossumf040ede2001-08-07 16:40:56 +00003862 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003863
Guido van Rossum687ae002001-10-15 22:03:32 +00003864 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00003865 return 0;
3866 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003867 if (func == NULL)
3868 return -1;
Guido van Rossum687ae002001-10-15 22:03:32 +00003869 return PyDict_SetItemString(type->tp_dict, "__new__", func);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003870}
3871
Guido van Rossumf040ede2001-08-07 16:40:56 +00003872/* Slot wrappers that call the corresponding __foo__ slot. See comments
3873 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003874
Guido van Rossumdc91b992001-08-08 22:26:22 +00003875#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003876static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003877FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003878{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00003879 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003880 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003881}
3882
Guido van Rossumdc91b992001-08-08 22:26:22 +00003883#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003884static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003885FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003886{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003887 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003888 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003889}
3890
Guido van Rossumcd118802003-01-06 22:57:47 +00003891/* Boolean helper for SLOT1BINFULL().
3892 right.__class__ is a nontrivial subclass of left.__class__. */
3893static int
3894method_is_overloaded(PyObject *left, PyObject *right, char *name)
3895{
3896 PyObject *a, *b;
3897 int ok;
3898
3899 b = PyObject_GetAttrString((PyObject *)(right->ob_type), name);
3900 if (b == NULL) {
3901 PyErr_Clear();
3902 /* If right doesn't have it, it's not overloaded */
3903 return 0;
3904 }
3905
3906 a = PyObject_GetAttrString((PyObject *)(left->ob_type), name);
3907 if (a == NULL) {
3908 PyErr_Clear();
3909 Py_DECREF(b);
3910 /* If right has it but left doesn't, it's overloaded */
3911 return 1;
3912 }
3913
3914 ok = PyObject_RichCompareBool(a, b, Py_NE);
3915 Py_DECREF(a);
3916 Py_DECREF(b);
3917 if (ok < 0) {
3918 PyErr_Clear();
3919 return 0;
3920 }
3921
3922 return ok;
3923}
3924
Guido van Rossumdc91b992001-08-08 22:26:22 +00003925
3926#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003927static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003928FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003929{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003930 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00003931 int do_other = self->ob_type != other->ob_type && \
3932 other->ob_type->tp_as_number != NULL && \
3933 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003934 if (self->ob_type->tp_as_number != NULL && \
3935 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
3936 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00003937 if (do_other && \
Guido van Rossumcd118802003-01-06 22:57:47 +00003938 PyType_IsSubtype(other->ob_type, self->ob_type) && \
3939 method_is_overloaded(self, other, ROPSTR)) { \
Guido van Rossum55f20992001-10-01 17:18:22 +00003940 r = call_maybe( \
3941 other, ROPSTR, &rcache_str, "(O)", self); \
3942 if (r != Py_NotImplemented) \
3943 return r; \
3944 Py_DECREF(r); \
3945 do_other = 0; \
3946 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00003947 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00003948 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003949 if (r != Py_NotImplemented || \
3950 other->ob_type == self->ob_type) \
3951 return r; \
3952 Py_DECREF(r); \
3953 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00003954 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00003955 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00003956 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003957 } \
3958 Py_INCREF(Py_NotImplemented); \
3959 return Py_NotImplemented; \
3960}
3961
3962#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
3963 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
3964
3965#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
3966static PyObject * \
3967FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
3968{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003969 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003970 return call_method(self, OPSTR, &cache_str, \
3971 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003972}
3973
3974static int
3975slot_sq_length(PyObject *self)
3976{
Guido van Rossum2730b132001-08-28 18:22:14 +00003977 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00003978 PyObject *res = call_method(self, "__len__", &len_str, "()");
Guido van Rossum26111622001-10-01 16:42:49 +00003979 int len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003980
3981 if (res == NULL)
3982 return -1;
Guido van Rossum26111622001-10-01 16:42:49 +00003983 len = (int)PyInt_AsLong(res);
3984 Py_DECREF(res);
Jeremy Hylton73a088e2002-07-25 16:43:29 +00003985 if (len == -1 && PyErr_Occurred())
3986 return -1;
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00003987 if (len < 0) {
Guido van Rossum22b13872002-08-06 21:41:44 +00003988 PyErr_SetString(PyExc_ValueError,
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00003989 "__len__() should return >= 0");
3990 return -1;
3991 }
Guido van Rossum26111622001-10-01 16:42:49 +00003992 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003993}
3994
Guido van Rossumdc91b992001-08-08 22:26:22 +00003995SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
3996SLOT1(slot_sq_repeat, "__mul__", int, "i")
Guido van Rossumf4593e02001-10-03 12:09:30 +00003997
3998/* Super-optimized version of slot_sq_item.
3999 Other slots could do the same... */
4000static PyObject *
4001slot_sq_item(PyObject *self, int i)
4002{
4003 static PyObject *getitem_str;
4004 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
4005 descrgetfunc f;
4006
4007 if (getitem_str == NULL) {
4008 getitem_str = PyString_InternFromString("__getitem__");
4009 if (getitem_str == NULL)
4010 return NULL;
4011 }
4012 func = _PyType_Lookup(self->ob_type, getitem_str);
4013 if (func != NULL) {
Guido van Rossumf4593e02001-10-03 12:09:30 +00004014 if ((f = func->ob_type->tp_descr_get) == NULL)
4015 Py_INCREF(func);
Neal Norwitz673cd822002-10-18 16:33:13 +00004016 else {
Guido van Rossumf4593e02001-10-03 12:09:30 +00004017 func = f(func, self, (PyObject *)(self->ob_type));
Neal Norwitz673cd822002-10-18 16:33:13 +00004018 if (func == NULL) {
4019 return NULL;
4020 }
4021 }
Guido van Rossumf4593e02001-10-03 12:09:30 +00004022 ival = PyInt_FromLong(i);
4023 if (ival != NULL) {
4024 args = PyTuple_New(1);
4025 if (args != NULL) {
4026 PyTuple_SET_ITEM(args, 0, ival);
4027 retval = PyObject_Call(func, args, NULL);
4028 Py_XDECREF(args);
4029 Py_XDECREF(func);
4030 return retval;
4031 }
4032 }
4033 }
4034 else {
4035 PyErr_SetObject(PyExc_AttributeError, getitem_str);
4036 }
4037 Py_XDECREF(args);
4038 Py_XDECREF(ival);
4039 Py_XDECREF(func);
4040 return NULL;
4041}
4042
Guido van Rossumdc91b992001-08-08 22:26:22 +00004043SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004044
4045static int
4046slot_sq_ass_item(PyObject *self, int index, PyObject *value)
4047{
4048 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004049 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004050
4051 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004052 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004053 "(i)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004054 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004055 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004056 "(iO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004057 if (res == NULL)
4058 return -1;
4059 Py_DECREF(res);
4060 return 0;
4061}
4062
4063static int
4064slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
4065{
4066 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004067 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004068
4069 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004070 res = call_method(self, "__delslice__", &delslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004071 "(ii)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004072 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004073 res = call_method(self, "__setslice__", &setslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004074 "(iiO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004075 if (res == NULL)
4076 return -1;
4077 Py_DECREF(res);
4078 return 0;
4079}
4080
4081static int
4082slot_sq_contains(PyObject *self, PyObject *value)
4083{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004084 PyObject *func, *res, *args;
Tim Petersbf9b2442003-03-23 05:35:36 +00004085 int result = -1;
4086
Guido van Rossum60718732001-08-28 17:47:51 +00004087 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004088
Guido van Rossum55f20992001-10-01 17:18:22 +00004089 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004090 if (func != NULL) {
4091 args = Py_BuildValue("(O)", value);
4092 if (args == NULL)
4093 res = NULL;
4094 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004095 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004096 Py_DECREF(args);
4097 }
4098 Py_DECREF(func);
Tim Petersbf9b2442003-03-23 05:35:36 +00004099 if (res != NULL) {
4100 result = PyObject_IsTrue(res);
4101 Py_DECREF(res);
4102 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004103 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004104 else if (! PyErr_Occurred()) {
4105 result = _PySequence_IterSearch(self, value,
4106 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004107 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004108 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004109}
4110
Guido van Rossumdc91b992001-08-08 22:26:22 +00004111SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
4112SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004113
4114#define slot_mp_length slot_sq_length
4115
Guido van Rossumdc91b992001-08-08 22:26:22 +00004116SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004117
4118static int
4119slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
4120{
4121 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004122 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004123
4124 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004125 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004126 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004127 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004128 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004129 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004130 if (res == NULL)
4131 return -1;
4132 Py_DECREF(res);
4133 return 0;
4134}
4135
Guido van Rossumdc91b992001-08-08 22:26:22 +00004136SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
4137SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
4138SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
4139SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
4140SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
4141SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
4142
Jeremy Hylton938ace62002-07-17 16:30:39 +00004143static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00004144
4145SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
4146 nb_power, "__pow__", "__rpow__")
4147
4148static PyObject *
4149slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
4150{
Guido van Rossum2730b132001-08-28 18:22:14 +00004151 static PyObject *pow_str;
4152
Guido van Rossumdc91b992001-08-08 22:26:22 +00004153 if (modulus == Py_None)
4154 return slot_nb_power_binary(self, other);
Guido van Rossum23094982002-06-10 14:30:43 +00004155 /* Three-arg power doesn't use __rpow__. But ternary_op
4156 can call this when the second argument's type uses
4157 slot_nb_power, so check before calling self.__pow__. */
4158 if (self->ob_type->tp_as_number != NULL &&
4159 self->ob_type->tp_as_number->nb_power == slot_nb_power) {
4160 return call_method(self, "__pow__", &pow_str,
4161 "(OO)", other, modulus);
4162 }
4163 Py_INCREF(Py_NotImplemented);
4164 return Py_NotImplemented;
Guido van Rossumdc91b992001-08-08 22:26:22 +00004165}
4166
4167SLOT0(slot_nb_negative, "__neg__")
4168SLOT0(slot_nb_positive, "__pos__")
4169SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004170
4171static int
4172slot_nb_nonzero(PyObject *self)
4173{
Tim Petersea7f75d2002-12-07 21:39:16 +00004174 PyObject *func, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00004175 static PyObject *nonzero_str, *len_str;
Tim Petersea7f75d2002-12-07 21:39:16 +00004176 int result = -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004177
Guido van Rossum55f20992001-10-01 17:18:22 +00004178 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004179 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00004180 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00004181 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00004182 func = lookup_maybe(self, "__len__", &len_str);
Tim Petersea7f75d2002-12-07 21:39:16 +00004183 if (func == NULL)
4184 return PyErr_Occurred() ? -1 : 1;
4185 }
4186 args = PyTuple_New(0);
4187 if (args != NULL) {
4188 PyObject *temp = PyObject_Call(func, args, NULL);
4189 Py_DECREF(args);
4190 if (temp != NULL) {
4191 result = PyObject_IsTrue(temp);
4192 Py_DECREF(temp);
Guido van Rossum55f20992001-10-01 17:18:22 +00004193 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004194 }
Guido van Rossum55f20992001-10-01 17:18:22 +00004195 Py_DECREF(func);
Tim Petersea7f75d2002-12-07 21:39:16 +00004196 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004197}
4198
Guido van Rossumdc91b992001-08-08 22:26:22 +00004199SLOT0(slot_nb_invert, "__invert__")
4200SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
4201SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
4202SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
4203SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
4204SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004205
4206static int
4207slot_nb_coerce(PyObject **a, PyObject **b)
4208{
4209 static PyObject *coerce_str;
4210 PyObject *self = *a, *other = *b;
4211
4212 if (self->ob_type->tp_as_number != NULL &&
4213 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
4214 PyObject *r;
4215 r = call_maybe(
4216 self, "__coerce__", &coerce_str, "(O)", other);
4217 if (r == NULL)
4218 return -1;
4219 if (r == Py_NotImplemented) {
4220 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004221 }
Guido van Rossum55f20992001-10-01 17:18:22 +00004222 else {
4223 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
4224 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004225 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00004226 Py_DECREF(r);
4227 return -1;
4228 }
4229 *a = PyTuple_GET_ITEM(r, 0);
4230 Py_INCREF(*a);
4231 *b = PyTuple_GET_ITEM(r, 1);
4232 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004233 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00004234 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004235 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004236 }
4237 if (other->ob_type->tp_as_number != NULL &&
4238 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
4239 PyObject *r;
4240 r = call_maybe(
4241 other, "__coerce__", &coerce_str, "(O)", self);
4242 if (r == NULL)
4243 return -1;
4244 if (r == Py_NotImplemented) {
4245 Py_DECREF(r);
4246 return 1;
4247 }
4248 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
4249 PyErr_SetString(PyExc_TypeError,
4250 "__coerce__ didn't return a 2-tuple");
4251 Py_DECREF(r);
4252 return -1;
4253 }
4254 *a = PyTuple_GET_ITEM(r, 1);
4255 Py_INCREF(*a);
4256 *b = PyTuple_GET_ITEM(r, 0);
4257 Py_INCREF(*b);
4258 Py_DECREF(r);
4259 return 0;
4260 }
4261 return 1;
4262}
4263
Guido van Rossumdc91b992001-08-08 22:26:22 +00004264SLOT0(slot_nb_int, "__int__")
4265SLOT0(slot_nb_long, "__long__")
4266SLOT0(slot_nb_float, "__float__")
4267SLOT0(slot_nb_oct, "__oct__")
4268SLOT0(slot_nb_hex, "__hex__")
4269SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
4270SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
4271SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
4272SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
4273SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Guido van Rossum6e5680f2002-10-15 01:01:53 +00004274SLOT1(slot_nb_inplace_power, "__ipow__", PyObject *, "O")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004275SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
4276SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
4277SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
4278SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
4279SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
4280SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
4281 "__floordiv__", "__rfloordiv__")
4282SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
4283SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
4284SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004285
4286static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00004287half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004288{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004289 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004290 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004291 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004292
Guido van Rossum60718732001-08-28 17:47:51 +00004293 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004294 if (func == NULL) {
4295 PyErr_Clear();
4296 }
4297 else {
4298 args = Py_BuildValue("(O)", other);
4299 if (args == NULL)
4300 res = NULL;
4301 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004302 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004303 Py_DECREF(args);
4304 }
Raymond Hettingerab5dae32002-06-24 13:08:16 +00004305 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004306 if (res != Py_NotImplemented) {
4307 if (res == NULL)
4308 return -2;
4309 c = PyInt_AsLong(res);
4310 Py_DECREF(res);
4311 if (c == -1 && PyErr_Occurred())
4312 return -2;
4313 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
4314 }
4315 Py_DECREF(res);
4316 }
4317 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004318}
4319
Guido van Rossumab3b0342001-09-18 20:38:53 +00004320/* This slot is published for the benefit of try_3way_compare in object.c */
4321int
4322_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00004323{
4324 int c;
4325
Guido van Rossumab3b0342001-09-18 20:38:53 +00004326 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004327 c = half_compare(self, other);
4328 if (c <= 1)
4329 return c;
4330 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00004331 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004332 c = half_compare(other, self);
4333 if (c < -1)
4334 return -2;
4335 if (c <= 1)
4336 return -c;
4337 }
4338 return (void *)self < (void *)other ? -1 :
4339 (void *)self > (void *)other ? 1 : 0;
4340}
4341
4342static PyObject *
4343slot_tp_repr(PyObject *self)
4344{
4345 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004346 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004347
Guido van Rossum60718732001-08-28 17:47:51 +00004348 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004349 if (func != NULL) {
4350 res = PyEval_CallObject(func, NULL);
4351 Py_DECREF(func);
4352 return res;
4353 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00004354 PyErr_Clear();
4355 return PyString_FromFormat("<%s object at %p>",
4356 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004357}
4358
4359static PyObject *
4360slot_tp_str(PyObject *self)
4361{
4362 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004363 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004364
Guido van Rossum60718732001-08-28 17:47:51 +00004365 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004366 if (func != NULL) {
4367 res = PyEval_CallObject(func, NULL);
4368 Py_DECREF(func);
4369 return res;
4370 }
4371 else {
4372 PyErr_Clear();
4373 return slot_tp_repr(self);
4374 }
4375}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004376
4377static long
4378slot_tp_hash(PyObject *self)
4379{
Tim Peters61ce0a92002-12-06 23:38:02 +00004380 PyObject *func;
Guido van Rossum60718732001-08-28 17:47:51 +00004381 static PyObject *hash_str, *eq_str, *cmp_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004382 long h;
4383
Guido van Rossum60718732001-08-28 17:47:51 +00004384 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004385
4386 if (func != NULL) {
Tim Peters61ce0a92002-12-06 23:38:02 +00004387 PyObject *res = PyEval_CallObject(func, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004388 Py_DECREF(func);
4389 if (res == NULL)
4390 return -1;
4391 h = PyInt_AsLong(res);
Tim Peters61ce0a92002-12-06 23:38:02 +00004392 Py_DECREF(res);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004393 }
4394 else {
4395 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004396 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004397 if (func == NULL) {
4398 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004399 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004400 }
4401 if (func != NULL) {
4402 Py_DECREF(func);
4403 PyErr_SetString(PyExc_TypeError, "unhashable type");
4404 return -1;
4405 }
4406 PyErr_Clear();
4407 h = _Py_HashPointer((void *)self);
4408 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004409 if (h == -1 && !PyErr_Occurred())
4410 h = -2;
4411 return h;
4412}
4413
4414static PyObject *
4415slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
4416{
Guido van Rossum60718732001-08-28 17:47:51 +00004417 static PyObject *call_str;
4418 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004419 PyObject *res;
4420
4421 if (meth == NULL)
4422 return NULL;
4423 res = PyObject_Call(meth, args, kwds);
4424 Py_DECREF(meth);
4425 return res;
4426}
4427
Guido van Rossum14a6f832001-10-17 13:59:09 +00004428/* There are two slot dispatch functions for tp_getattro.
4429
4430 - slot_tp_getattro() is used when __getattribute__ is overridden
4431 but no __getattr__ hook is present;
4432
4433 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
4434
Guido van Rossumc334df52002-04-04 23:44:47 +00004435 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
4436 detects the absence of __getattr__ and then installs the simpler slot if
4437 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00004438
Tim Peters6d6c1a32001-08-02 04:15:00 +00004439static PyObject *
4440slot_tp_getattro(PyObject *self, PyObject *name)
4441{
Guido van Rossum14a6f832001-10-17 13:59:09 +00004442 static PyObject *getattribute_str = NULL;
4443 return call_method(self, "__getattribute__", &getattribute_str,
4444 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004445}
4446
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004447static PyObject *
4448slot_tp_getattr_hook(PyObject *self, PyObject *name)
4449{
4450 PyTypeObject *tp = self->ob_type;
4451 PyObject *getattr, *getattribute, *res;
4452 static PyObject *getattribute_str = NULL;
4453 static PyObject *getattr_str = NULL;
4454
4455 if (getattr_str == NULL) {
4456 getattr_str = PyString_InternFromString("__getattr__");
4457 if (getattr_str == NULL)
4458 return NULL;
4459 }
4460 if (getattribute_str == NULL) {
4461 getattribute_str =
4462 PyString_InternFromString("__getattribute__");
4463 if (getattribute_str == NULL)
4464 return NULL;
4465 }
4466 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004467 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004468 /* No __getattr__ hook: use a simpler dispatcher */
4469 tp->tp_getattro = slot_tp_getattro;
4470 return slot_tp_getattro(self, name);
4471 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004472 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004473 if (getattribute == NULL ||
4474 (getattribute->ob_type == &PyWrapperDescr_Type &&
4475 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
4476 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004477 res = PyObject_GenericGetAttr(self, name);
4478 else
4479 res = PyObject_CallFunction(getattribute, "OO", self, name);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004480 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004481 PyErr_Clear();
4482 res = PyObject_CallFunction(getattr, "OO", self, name);
4483 }
4484 return res;
4485}
4486
Tim Peters6d6c1a32001-08-02 04:15:00 +00004487static int
4488slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
4489{
4490 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004491 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004492
4493 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004494 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004495 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004496 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004497 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004498 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004499 if (res == NULL)
4500 return -1;
4501 Py_DECREF(res);
4502 return 0;
4503}
4504
4505/* Map rich comparison operators to their __xx__ namesakes */
4506static char *name_op[] = {
4507 "__lt__",
4508 "__le__",
4509 "__eq__",
4510 "__ne__",
4511 "__gt__",
4512 "__ge__",
4513};
4514
4515static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00004516half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004517{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004518 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004519 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00004520
Guido van Rossum60718732001-08-28 17:47:51 +00004521 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004522 if (func == NULL) {
4523 PyErr_Clear();
4524 Py_INCREF(Py_NotImplemented);
4525 return Py_NotImplemented;
4526 }
4527 args = Py_BuildValue("(O)", other);
4528 if (args == NULL)
4529 res = NULL;
4530 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004531 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004532 Py_DECREF(args);
4533 }
4534 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004535 return res;
4536}
4537
Guido van Rossumb8f63662001-08-15 23:57:02 +00004538/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
4539static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
4540
4541static PyObject *
4542slot_tp_richcompare(PyObject *self, PyObject *other, int op)
4543{
4544 PyObject *res;
4545
4546 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
4547 res = half_richcompare(self, other, op);
4548 if (res != Py_NotImplemented)
4549 return res;
4550 Py_DECREF(res);
4551 }
4552 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
4553 res = half_richcompare(other, self, swapped_op[op]);
4554 if (res != Py_NotImplemented) {
4555 return res;
4556 }
4557 Py_DECREF(res);
4558 }
4559 Py_INCREF(Py_NotImplemented);
4560 return Py_NotImplemented;
4561}
4562
4563static PyObject *
4564slot_tp_iter(PyObject *self)
4565{
4566 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004567 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004568
Guido van Rossum60718732001-08-28 17:47:51 +00004569 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004570 if (func != NULL) {
Guido van Rossum84b2bed2002-08-16 17:01:09 +00004571 PyObject *args;
4572 args = res = PyTuple_New(0);
4573 if (args != NULL) {
4574 res = PyObject_Call(func, args, NULL);
4575 Py_DECREF(args);
4576 }
4577 Py_DECREF(func);
4578 return res;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004579 }
4580 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004581 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004582 if (func == NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00004583 PyErr_SetString(PyExc_TypeError,
4584 "iteration over non-sequence");
Guido van Rossumb8f63662001-08-15 23:57:02 +00004585 return NULL;
4586 }
4587 Py_DECREF(func);
4588 return PySeqIter_New(self);
4589}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004590
4591static PyObject *
4592slot_tp_iternext(PyObject *self)
4593{
Guido van Rossum2730b132001-08-28 18:22:14 +00004594 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00004595 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004596}
4597
Guido van Rossum1a493502001-08-17 16:47:50 +00004598static PyObject *
4599slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4600{
4601 PyTypeObject *tp = self->ob_type;
4602 PyObject *get;
4603 static PyObject *get_str = NULL;
4604
4605 if (get_str == NULL) {
4606 get_str = PyString_InternFromString("__get__");
4607 if (get_str == NULL)
4608 return NULL;
4609 }
4610 get = _PyType_Lookup(tp, get_str);
4611 if (get == NULL) {
4612 /* Avoid further slowdowns */
4613 if (tp->tp_descr_get == slot_tp_descr_get)
4614 tp->tp_descr_get = NULL;
4615 Py_INCREF(self);
4616 return self;
4617 }
Guido van Rossum2c252392001-08-24 10:13:31 +00004618 if (obj == NULL)
4619 obj = Py_None;
4620 if (type == NULL)
4621 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00004622 return PyObject_CallFunction(get, "OOO", self, obj, type);
4623}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004624
4625static int
4626slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
4627{
Guido van Rossum2c252392001-08-24 10:13:31 +00004628 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004629 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00004630
4631 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00004632 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004633 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00004634 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004635 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004636 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004637 if (res == NULL)
4638 return -1;
4639 Py_DECREF(res);
4640 return 0;
4641}
4642
4643static int
4644slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
4645{
Guido van Rossum60718732001-08-28 17:47:51 +00004646 static PyObject *init_str;
4647 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004648 PyObject *res;
4649
4650 if (meth == NULL)
4651 return -1;
4652 res = PyObject_Call(meth, args, kwds);
4653 Py_DECREF(meth);
4654 if (res == NULL)
4655 return -1;
4656 Py_DECREF(res);
4657 return 0;
4658}
4659
4660static PyObject *
4661slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4662{
Guido van Rossum7bed2132002-08-08 21:57:53 +00004663 static PyObject *new_str;
4664 PyObject *func;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004665 PyObject *newargs, *x;
4666 int i, n;
4667
Guido van Rossum7bed2132002-08-08 21:57:53 +00004668 if (new_str == NULL) {
4669 new_str = PyString_InternFromString("__new__");
4670 if (new_str == NULL)
4671 return NULL;
4672 }
4673 func = PyObject_GetAttr((PyObject *)type, new_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004674 if (func == NULL)
4675 return NULL;
4676 assert(PyTuple_Check(args));
4677 n = PyTuple_GET_SIZE(args);
4678 newargs = PyTuple_New(n+1);
4679 if (newargs == NULL)
4680 return NULL;
4681 Py_INCREF(type);
4682 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
4683 for (i = 0; i < n; i++) {
4684 x = PyTuple_GET_ITEM(args, i);
4685 Py_INCREF(x);
4686 PyTuple_SET_ITEM(newargs, i+1, x);
4687 }
4688 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00004689 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004690 Py_DECREF(func);
4691 return x;
4692}
4693
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004694static void
4695slot_tp_del(PyObject *self)
4696{
4697 static PyObject *del_str = NULL;
4698 PyObject *del, *res;
4699 PyObject *error_type, *error_value, *error_traceback;
4700
4701 /* Temporarily resurrect the object. */
4702 assert(self->ob_refcnt == 0);
4703 self->ob_refcnt = 1;
4704
4705 /* Save the current exception, if any. */
4706 PyErr_Fetch(&error_type, &error_value, &error_traceback);
4707
4708 /* Execute __del__ method, if any. */
4709 del = lookup_maybe(self, "__del__", &del_str);
4710 if (del != NULL) {
4711 res = PyEval_CallObject(del, NULL);
4712 if (res == NULL)
4713 PyErr_WriteUnraisable(del);
4714 else
4715 Py_DECREF(res);
4716 Py_DECREF(del);
4717 }
4718
4719 /* Restore the saved exception. */
4720 PyErr_Restore(error_type, error_value, error_traceback);
4721
4722 /* Undo the temporary resurrection; can't use DECREF here, it would
4723 * cause a recursive call.
4724 */
4725 assert(self->ob_refcnt > 0);
4726 if (--self->ob_refcnt == 0)
4727 return; /* this is the normal path out */
4728
4729 /* __del__ resurrected it! Make it look like the original Py_DECREF
4730 * never happened.
4731 */
4732 {
4733 int refcnt = self->ob_refcnt;
4734 _Py_NewReference(self);
4735 self->ob_refcnt = refcnt;
4736 }
4737 assert(!PyType_IS_GC(self->ob_type) ||
4738 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
4739 /* If Py_REF_DEBUG, the original decref dropped _Py_RefTotal, but
4740 * _Py_NewReference bumped it again, so that's a wash.
4741 * If Py_TRACE_REFS, _Py_NewReference re-added self to the object
4742 * chain, so no more to do there either.
4743 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
4744 * _Py_NewReference bumped tp_allocs: both of those need to be
4745 * undone.
4746 */
4747#ifdef COUNT_ALLOCS
4748 --self->ob_type->tp_frees;
4749 --self->ob_type->tp_allocs;
4750#endif
4751}
4752
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004753
4754/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
Tim Petersbf9b2442003-03-23 05:35:36 +00004755 functions. The offsets here are relative to the 'PyHeapTypeObject'
Guido van Rossume5c691a2003-03-07 15:13:17 +00004756 structure, which incorporates the additional structures used for numbers,
4757 sequences and mappings.
4758 Note that multiple names may map to the same slot (e.g. __eq__,
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004759 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00004760 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
4761 terminated with an all-zero entry. (This table is further initialized and
4762 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004763
Guido van Rossum6d204072001-10-21 00:44:31 +00004764typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004765
4766#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00004767#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004768#undef ETSLOT
4769#undef SQSLOT
4770#undef MPSLOT
4771#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00004772#undef UNSLOT
4773#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004774#undef BINSLOT
4775#undef RBINSLOT
4776
Guido van Rossum6d204072001-10-21 00:44:31 +00004777#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004778 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
4779 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00004780#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
4781 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004782 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00004783#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Guido van Rossume5c691a2003-03-07 15:13:17 +00004784 {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004785 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00004786#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4787 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
4788#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4789 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
4790#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4791 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
4792#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4793 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
4794 "x." NAME "() <==> " DOC)
4795#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4796 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
4797 "x." NAME "(y) <==> x" DOC "y")
4798#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
4799 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
4800 "x." NAME "(y) <==> x" DOC "y")
4801#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
4802 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
4803 "x." NAME "(y) <==> y" DOC "x")
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004804
4805static slotdef slotdefs[] = {
Guido van Rossum6d204072001-10-21 00:44:31 +00004806 SQSLOT("__len__", sq_length, slot_sq_length, wrap_inquiry,
4807 "x.__len__() <==> len(x)"),
4808 SQSLOT("__add__", sq_concat, slot_sq_concat, wrap_binaryfunc,
4809 "x.__add__(y) <==> x+y"),
4810 SQSLOT("__mul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
4811 "x.__mul__(n) <==> x*n"),
4812 SQSLOT("__rmul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
4813 "x.__rmul__(n) <==> n*x"),
4814 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
4815 "x.__getitem__(y) <==> x[y]"),
4816 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_intintargfunc,
Brett Cannon154da9b2003-05-20 02:30:04 +00004817 "x.__getslice__(i, j) <==> x[i:j]\n\
4818 \n\
4819 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00004820 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
Brett Cannonbe67d872003-05-20 02:40:12 +00004821 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum6d204072001-10-21 00:44:31 +00004822 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
Brett Cannonbe67d872003-05-20 02:40:12 +00004823 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004824 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Guido van Rossum6d204072001-10-21 00:44:31 +00004825 wrap_intintobjargproc,
Brett Cannonbe67d872003-05-20 02:40:12 +00004826 "x.__setslice__(i, j, y) <==> x[i:j]=y\n\
4827 \n\
4828 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00004829 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
Brett Cannonbe67d872003-05-20 02:40:12 +00004830 "x.__delslice__(i, j) <==> del x[i:j]\n\
4831 \n\
4832 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00004833 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
4834 "x.__contains__(y) <==> y in x"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004835 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat,
Guido van Rossum6d204072001-10-21 00:44:31 +00004836 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004837 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat,
Guido van Rossum6d204072001-10-21 00:44:31 +00004838 wrap_intargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004839
Guido van Rossum6d204072001-10-21 00:44:31 +00004840 MPSLOT("__len__", mp_length, slot_mp_length, wrap_inquiry,
4841 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00004842 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004843 wrap_binaryfunc,
4844 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004845 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004846 wrap_objobjargproc,
4847 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004848 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004849 wrap_delitem,
4850 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004851
Guido van Rossum6d204072001-10-21 00:44:31 +00004852 BINSLOT("__add__", nb_add, slot_nb_add,
4853 "+"),
4854 RBINSLOT("__radd__", nb_add, slot_nb_add,
4855 "+"),
4856 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
4857 "-"),
4858 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
4859 "-"),
4860 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
4861 "*"),
4862 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
4863 "*"),
4864 BINSLOT("__div__", nb_divide, slot_nb_divide,
4865 "/"),
4866 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
4867 "/"),
4868 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
4869 "%"),
4870 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
4871 "%"),
4872 BINSLOT("__divmod__", nb_divmod, slot_nb_divmod,
4873 "divmod(x, y)"),
4874 RBINSLOT("__rdivmod__", nb_divmod, slot_nb_divmod,
4875 "divmod(y, x)"),
4876 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
4877 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
4878 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
4879 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
4880 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
4881 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
4882 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
4883 "abs(x)"),
Guido van Rossumdfce3bf2002-03-10 14:11:16 +00004884 UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquiry,
Guido van Rossum6d204072001-10-21 00:44:31 +00004885 "x != 0"),
4886 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
4887 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
4888 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
4889 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
4890 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
4891 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
4892 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
4893 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
4894 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
4895 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
4896 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
4897 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
4898 "x.__coerce__(y) <==> coerce(x, y)"),
4899 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
4900 "int(x)"),
4901 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
4902 "long(x)"),
4903 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
4904 "float(x)"),
4905 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
4906 "oct(x)"),
4907 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
4908 "hex(x)"),
4909 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
4910 wrap_binaryfunc, "+"),
4911 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
4912 wrap_binaryfunc, "-"),
4913 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
4914 wrap_binaryfunc, "*"),
4915 IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
4916 wrap_binaryfunc, "/"),
4917 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
4918 wrap_binaryfunc, "%"),
4919 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
Guido van Rossum6e5680f2002-10-15 01:01:53 +00004920 wrap_binaryfunc, "**"),
Guido van Rossum6d204072001-10-21 00:44:31 +00004921 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
4922 wrap_binaryfunc, "<<"),
4923 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
4924 wrap_binaryfunc, ">>"),
4925 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
4926 wrap_binaryfunc, "&"),
4927 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
4928 wrap_binaryfunc, "^"),
4929 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
4930 wrap_binaryfunc, "|"),
4931 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
4932 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
4933 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
4934 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
4935 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
4936 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
4937 IBSLOT("__itruediv__", nb_inplace_true_divide,
4938 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004939
Guido van Rossum6d204072001-10-21 00:44:31 +00004940 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
4941 "x.__str__() <==> str(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00004942 TPSLOT("__str__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00004943 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
4944 "x.__repr__() <==> repr(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00004945 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00004946 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
4947 "x.__cmp__(y) <==> cmp(x,y)"),
4948 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
4949 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00004950 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
4951 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004952 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00004953 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
4954 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
4955 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
4956 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
4957 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
4958 "x.__setattr__('name', value) <==> x.name = value"),
4959 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
4960 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
4961 "x.__delattr__('name') <==> del x.name"),
4962 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
4963 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
4964 "x.__lt__(y) <==> x<y"),
4965 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
4966 "x.__le__(y) <==> x<=y"),
4967 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
4968 "x.__eq__(y) <==> x==y"),
4969 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
4970 "x.__ne__(y) <==> x!=y"),
4971 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
4972 "x.__gt__(y) <==> x>y"),
4973 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
4974 "x.__ge__(y) <==> x>=y"),
4975 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
4976 "x.__iter__() <==> iter(x)"),
4977 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
4978 "x.next() -> the next value, or raise StopIteration"),
4979 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
4980 "descr.__get__(obj[, type]) -> value"),
4981 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
4982 "descr.__set__(obj, value)"),
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004983 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
4984 wrap_descr_delete, "descr.__delete__(obj)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00004985 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00004986 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00004987 "see x.__class__.__doc__ for signature",
4988 PyWrapperFlag_KEYWORDS),
4989 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004990 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004991 {NULL}
4992};
4993
Guido van Rossumc334df52002-04-04 23:44:47 +00004994/* Given a type pointer and an offset gotten from a slotdef entry, return a
4995 pointer to the actual slot. This is not quite the same as simply adding
4996 the offset to the type pointer, since it takes care to indirect through the
4997 proper indirection pointer (as_buffer, etc.); it returns NULL if the
4998 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004999static void **
5000slotptr(PyTypeObject *type, int offset)
5001{
5002 char *ptr;
5003
Guido van Rossume5c691a2003-03-07 15:13:17 +00005004 /* Note: this depends on the order of the members of PyHeapTypeObject! */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005005 assert(offset >= 0);
Guido van Rossume5c691a2003-03-07 15:13:17 +00005006 assert(offset < offsetof(PyHeapTypeObject, as_buffer));
5007 if (offset >= offsetof(PyHeapTypeObject, as_sequence)) {
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005008 ptr = (void *)type->tp_as_sequence;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005009 offset -= offsetof(PyHeapTypeObject, as_sequence);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005010 }
Guido van Rossume5c691a2003-03-07 15:13:17 +00005011 else if (offset >= offsetof(PyHeapTypeObject, as_mapping)) {
Guido van Rossum09638c12002-06-13 19:17:46 +00005012 ptr = (void *)type->tp_as_mapping;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005013 offset -= offsetof(PyHeapTypeObject, as_mapping);
Guido van Rossum09638c12002-06-13 19:17:46 +00005014 }
Guido van Rossume5c691a2003-03-07 15:13:17 +00005015 else if (offset >= offsetof(PyHeapTypeObject, as_number)) {
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005016 ptr = (void *)type->tp_as_number;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005017 offset -= offsetof(PyHeapTypeObject, as_number);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005018 }
5019 else {
5020 ptr = (void *)type;
5021 }
5022 if (ptr != NULL)
5023 ptr += offset;
5024 return (void **)ptr;
5025}
Guido van Rossumf040ede2001-08-07 16:40:56 +00005026
Guido van Rossumc334df52002-04-04 23:44:47 +00005027/* Length of array of slotdef pointers used to store slots with the
5028 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
5029 the same __name__, for any __name__. Since that's a static property, it is
5030 appropriate to declare fixed-size arrays for this. */
5031#define MAX_EQUIV 10
5032
5033/* Return a slot pointer for a given name, but ONLY if the attribute has
5034 exactly one slot function. The name must be an interned string. */
5035static void **
5036resolve_slotdups(PyTypeObject *type, PyObject *name)
5037{
5038 /* XXX Maybe this could be optimized more -- but is it worth it? */
5039
5040 /* pname and ptrs act as a little cache */
5041 static PyObject *pname;
5042 static slotdef *ptrs[MAX_EQUIV];
5043 slotdef *p, **pp;
5044 void **res, **ptr;
5045
5046 if (pname != name) {
5047 /* Collect all slotdefs that match name into ptrs. */
5048 pname = name;
5049 pp = ptrs;
5050 for (p = slotdefs; p->name_strobj; p++) {
5051 if (p->name_strobj == name)
5052 *pp++ = p;
5053 }
5054 *pp = NULL;
5055 }
5056
5057 /* Look in all matching slots of the type; if exactly one of these has
5058 a filled-in slot, return its value. Otherwise return NULL. */
5059 res = NULL;
5060 for (pp = ptrs; *pp; pp++) {
5061 ptr = slotptr(type, (*pp)->offset);
5062 if (ptr == NULL || *ptr == NULL)
5063 continue;
5064 if (res != NULL)
5065 return NULL;
5066 res = ptr;
5067 }
5068 return res;
5069}
5070
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005071/* Common code for update_slots_callback() and fixup_slot_dispatchers(). This
Guido van Rossumc334df52002-04-04 23:44:47 +00005072 does some incredibly complex thinking and then sticks something into the
5073 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
5074 interests, and then stores a generic wrapper or a specific function into
5075 the slot.) Return a pointer to the next slotdef with a different offset,
5076 because that's convenient for fixup_slot_dispatchers(). */
5077static slotdef *
5078update_one_slot(PyTypeObject *type, slotdef *p)
5079{
5080 PyObject *descr;
5081 PyWrapperDescrObject *d;
5082 void *generic = NULL, *specific = NULL;
5083 int use_generic = 0;
5084 int offset = p->offset;
5085 void **ptr = slotptr(type, offset);
5086
5087 if (ptr == NULL) {
5088 do {
5089 ++p;
5090 } while (p->offset == offset);
5091 return p;
5092 }
5093 do {
5094 descr = _PyType_Lookup(type, p->name_strobj);
5095 if (descr == NULL)
5096 continue;
5097 if (descr->ob_type == &PyWrapperDescr_Type) {
5098 void **tptr = resolve_slotdups(type, p->name_strobj);
5099 if (tptr == NULL || tptr == ptr)
5100 generic = p->function;
5101 d = (PyWrapperDescrObject *)descr;
5102 if (d->d_base->wrapper == p->wrapper &&
5103 PyType_IsSubtype(type, d->d_type))
5104 {
5105 if (specific == NULL ||
5106 specific == d->d_wrapped)
5107 specific = d->d_wrapped;
5108 else
5109 use_generic = 1;
5110 }
5111 }
Guido van Rossum721f62e2002-08-09 02:14:34 +00005112 else if (descr->ob_type == &PyCFunction_Type &&
5113 PyCFunction_GET_FUNCTION(descr) ==
5114 (PyCFunction)tp_new_wrapper &&
5115 strcmp(p->name, "__new__") == 0)
5116 {
5117 /* The __new__ wrapper is not a wrapper descriptor,
5118 so must be special-cased differently.
5119 If we don't do this, creating an instance will
5120 always use slot_tp_new which will look up
5121 __new__ in the MRO which will call tp_new_wrapper
5122 which will look through the base classes looking
5123 for a static base and call its tp_new (usually
5124 PyType_GenericNew), after performing various
5125 sanity checks and constructing a new argument
5126 list. Cut all that nonsense short -- this speeds
5127 up instance creation tremendously. */
Martin v. Löwisa94568a2003-05-10 07:36:56 +00005128 specific = (void *)type->tp_new;
Guido van Rossum721f62e2002-08-09 02:14:34 +00005129 /* XXX I'm not 100% sure that there isn't a hole
5130 in this reasoning that requires additional
5131 sanity checks. I'll buy the first person to
5132 point out a bug in this reasoning a beer. */
5133 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005134 else {
5135 use_generic = 1;
5136 generic = p->function;
5137 }
5138 } while ((++p)->offset == offset);
5139 if (specific && !use_generic)
5140 *ptr = specific;
5141 else
5142 *ptr = generic;
5143 return p;
5144}
5145
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005146/* In the type, update the slots whose slotdefs are gathered in the pp array.
5147 This is a callback for update_subclasses(). */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005148static int
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005149update_slots_callback(PyTypeObject *type, void *data)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005150{
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005151 slotdef **pp = (slotdef **)data;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005152
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005153 for (; *pp; pp++)
Guido van Rossumc334df52002-04-04 23:44:47 +00005154 update_one_slot(type, *pp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005155 return 0;
5156}
5157
Guido van Rossumc334df52002-04-04 23:44:47 +00005158/* Comparison function for qsort() to compare slotdefs by their offset, and
5159 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005160static int
5161slotdef_cmp(const void *aa, const void *bb)
5162{
5163 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
5164 int c = a->offset - b->offset;
5165 if (c != 0)
5166 return c;
5167 else
5168 return a - b;
5169}
5170
Guido van Rossumc334df52002-04-04 23:44:47 +00005171/* Initialize the slotdefs table by adding interned string objects for the
5172 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005173static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005174init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005175{
5176 slotdef *p;
5177 static int initialized = 0;
5178
5179 if (initialized)
5180 return;
5181 for (p = slotdefs; p->name; p++) {
5182 p->name_strobj = PyString_InternFromString(p->name);
5183 if (!p->name_strobj)
Guido van Rossumc334df52002-04-04 23:44:47 +00005184 Py_FatalError("Out of memory interning slotdef names");
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005185 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005186 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
5187 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005188 initialized = 1;
5189}
5190
Guido van Rossumc334df52002-04-04 23:44:47 +00005191/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005192static int
5193update_slot(PyTypeObject *type, PyObject *name)
5194{
Guido van Rossumc334df52002-04-04 23:44:47 +00005195 slotdef *ptrs[MAX_EQUIV];
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005196 slotdef *p;
5197 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005198 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005199
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005200 init_slotdefs();
5201 pp = ptrs;
5202 for (p = slotdefs; p->name; p++) {
5203 /* XXX assume name is interned! */
5204 if (p->name_strobj == name)
5205 *pp++ = p;
5206 }
5207 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005208 for (pp = ptrs; *pp; pp++) {
5209 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005210 offset = p->offset;
5211 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005212 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005213 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005214 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005215 if (ptrs[0] == NULL)
5216 return 0; /* Not an attribute that affects any slots */
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005217 return update_subclasses(type, name,
5218 update_slots_callback, (void *)ptrs);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005219}
5220
Guido van Rossumc334df52002-04-04 23:44:47 +00005221/* Store the proper functions in the slot dispatches at class (type)
5222 definition time, based upon which operations the class overrides in its
5223 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00005224static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005225fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005226{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005227 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005228
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005229 init_slotdefs();
Guido van Rossumc334df52002-04-04 23:44:47 +00005230 for (p = slotdefs; p->name; )
5231 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005232}
Guido van Rossum705f0f52001-08-24 16:47:00 +00005233
Michael W. Hudson98bbc492002-11-26 14:47:27 +00005234static void
5235update_all_slots(PyTypeObject* type)
5236{
5237 slotdef *p;
5238
5239 init_slotdefs();
5240 for (p = slotdefs; p->name; p++) {
5241 /* update_slot returns int but can't actually fail */
5242 update_slot(type, p->name_strobj);
5243 }
5244}
5245
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005246/* recurse_down_subclasses() and update_subclasses() are mutually
5247 recursive functions to call a callback for all subclasses,
5248 but refraining from recursing into subclasses that define 'name'. */
5249
5250static int
5251update_subclasses(PyTypeObject *type, PyObject *name,
5252 update_callback callback, void *data)
5253{
5254 if (callback(type, data) < 0)
5255 return -1;
5256 return recurse_down_subclasses(type, name, callback, data);
5257}
5258
5259static int
5260recurse_down_subclasses(PyTypeObject *type, PyObject *name,
5261 update_callback callback, void *data)
5262{
5263 PyTypeObject *subclass;
5264 PyObject *ref, *subclasses, *dict;
5265 int i, n;
5266
5267 subclasses = type->tp_subclasses;
5268 if (subclasses == NULL)
5269 return 0;
5270 assert(PyList_Check(subclasses));
5271 n = PyList_GET_SIZE(subclasses);
5272 for (i = 0; i < n; i++) {
5273 ref = PyList_GET_ITEM(subclasses, i);
5274 assert(PyWeakref_CheckRef(ref));
5275 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
5276 assert(subclass != NULL);
5277 if ((PyObject *)subclass == Py_None)
5278 continue;
5279 assert(PyType_Check(subclass));
5280 /* Avoid recursing down into unaffected classes */
5281 dict = subclass->tp_dict;
5282 if (dict != NULL && PyDict_Check(dict) &&
5283 PyDict_GetItem(dict, name) != NULL)
5284 continue;
5285 if (update_subclasses(subclass, name, callback, data) < 0)
5286 return -1;
5287 }
5288 return 0;
5289}
5290
Guido van Rossum6d204072001-10-21 00:44:31 +00005291/* This function is called by PyType_Ready() to populate the type's
5292 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00005293 function slot (like tp_repr) that's defined in the type, one or more
5294 corresponding descriptors are added in the type's tp_dict dictionary
5295 under the appropriate name (like __repr__). Some function slots
5296 cause more than one descriptor to be added (for example, the nb_add
5297 slot adds both __add__ and __radd__ descriptors) and some function
5298 slots compete for the same descriptor (for example both sq_item and
5299 mp_subscript generate a __getitem__ descriptor).
5300
5301 In the latter case, the first slotdef entry encoutered wins. Since
Tim Petersbf9b2442003-03-23 05:35:36 +00005302 slotdef entries are sorted by the offset of the slot in the
Guido van Rossume5c691a2003-03-07 15:13:17 +00005303 PyHeapTypeObject, this gives us some control over disambiguating
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005304 between competing slots: the members of PyHeapTypeObject are listed
5305 from most general to least general, so the most general slot is
5306 preferred. In particular, because as_mapping comes before as_sequence,
5307 for a type that defines both mp_subscript and sq_item, mp_subscript
5308 wins.
Guido van Rossum09638c12002-06-13 19:17:46 +00005309
5310 This only adds new descriptors and doesn't overwrite entries in
5311 tp_dict that were previously defined. The descriptors contain a
5312 reference to the C function they must call, so that it's safe if they
5313 are copied into a subtype's __dict__ and the subtype has a different
5314 C function in its slot -- calling the method defined by the
5315 descriptor will call the C function that was used to create it,
5316 rather than the C function present in the slot when it is called.
5317 (This is important because a subtype may have a C function in the
5318 slot that calls the method from the dictionary, and we want to avoid
5319 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00005320
5321static int
5322add_operators(PyTypeObject *type)
5323{
5324 PyObject *dict = type->tp_dict;
5325 slotdef *p;
5326 PyObject *descr;
5327 void **ptr;
5328
5329 init_slotdefs();
5330 for (p = slotdefs; p->name; p++) {
5331 if (p->wrapper == NULL)
5332 continue;
5333 ptr = slotptr(type, p->offset);
5334 if (!ptr || !*ptr)
5335 continue;
5336 if (PyDict_GetItem(dict, p->name_strobj))
5337 continue;
5338 descr = PyDescr_NewWrapper(type, p, *ptr);
5339 if (descr == NULL)
5340 return -1;
5341 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
5342 return -1;
5343 Py_DECREF(descr);
5344 }
5345 if (type->tp_new != NULL) {
5346 if (add_tp_new_wrapper(type) < 0)
5347 return -1;
5348 }
5349 return 0;
5350}
5351
Guido van Rossum705f0f52001-08-24 16:47:00 +00005352
5353/* Cooperative 'super' */
5354
5355typedef struct {
5356 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00005357 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005358 PyObject *obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005359 PyTypeObject *obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005360} superobject;
5361
Guido van Rossum6f799372001-09-20 20:46:19 +00005362static PyMemberDef super_members[] = {
5363 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
5364 "the class invoking super()"},
5365 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
5366 "the instance invoking super(); may be None"},
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005367 {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
5368 "the type of the the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005369 {0}
5370};
5371
Guido van Rossum705f0f52001-08-24 16:47:00 +00005372static void
5373super_dealloc(PyObject *self)
5374{
5375 superobject *su = (superobject *)self;
5376
Guido van Rossum048eb752001-10-02 21:24:57 +00005377 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005378 Py_XDECREF(su->obj);
5379 Py_XDECREF(su->type);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005380 Py_XDECREF(su->obj_type);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005381 self->ob_type->tp_free(self);
5382}
5383
5384static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005385super_repr(PyObject *self)
5386{
5387 superobject *su = (superobject *)self;
5388
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005389 if (su->obj_type)
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005390 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005391 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005392 su->type ? su->type->tp_name : "NULL",
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005393 su->obj_type->tp_name);
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005394 else
5395 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005396 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005397 su->type ? su->type->tp_name : "NULL");
5398}
5399
5400static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00005401super_getattro(PyObject *self, PyObject *name)
5402{
5403 superobject *su = (superobject *)self;
Guido van Rossum76ba09f2003-04-16 19:40:58 +00005404 int skip = su->obj_type == NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005405
Guido van Rossum76ba09f2003-04-16 19:40:58 +00005406 if (!skip) {
5407 /* We want __class__ to return the class of the super object
5408 (i.e. super, or a subclass), not the class of su->obj. */
5409 skip = (PyString_Check(name) &&
5410 PyString_GET_SIZE(name) == 9 &&
5411 strcmp(PyString_AS_STRING(name), "__class__") == 0);
5412 }
5413
5414 if (!skip) {
Tim Petersa91e9642001-11-14 23:32:33 +00005415 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005416 PyTypeObject *starttype;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005417 descrgetfunc f;
5418 int i, n;
5419
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005420 starttype = su->obj_type;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005421 mro = starttype->tp_mro;
5422
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005423 if (mro == NULL)
5424 n = 0;
5425 else {
5426 assert(PyTuple_Check(mro));
5427 n = PyTuple_GET_SIZE(mro);
5428 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005429 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00005430 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00005431 break;
5432 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005433 i++;
5434 res = NULL;
5435 for (; i < n; i++) {
5436 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00005437 if (PyType_Check(tmp))
5438 dict = ((PyTypeObject *)tmp)->tp_dict;
5439 else if (PyClass_Check(tmp))
5440 dict = ((PyClassObject *)tmp)->cl_dict;
5441 else
5442 continue;
5443 res = PyDict_GetItem(dict, name);
Guido van Rossum6cc5bb62003-04-16 20:01:36 +00005444 if (res != NULL) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00005445 Py_INCREF(res);
5446 f = res->ob_type->tp_descr_get;
5447 if (f != NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00005448 tmp = f(res, su->obj,
5449 (PyObject *)starttype);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005450 Py_DECREF(res);
5451 res = tmp;
5452 }
5453 return res;
5454 }
5455 }
5456 }
5457 return PyObject_GenericGetAttr(self, name);
5458}
5459
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005460static PyTypeObject *
Guido van Rossum5b443c62001-12-03 15:38:28 +00005461supercheck(PyTypeObject *type, PyObject *obj)
5462{
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005463 /* Check that a super() call makes sense. Return a type object.
5464
5465 obj can be a new-style class, or an instance of one:
5466
5467 - If it is a class, it must be a subclass of 'type'. This case is
5468 used for class methods; the return value is obj.
5469
5470 - If it is an instance, it must be an instance of 'type'. This is
5471 the normal case; the return value is obj.__class__.
5472
5473 But... when obj is an instance, we want to allow for the case where
5474 obj->ob_type is not a subclass of type, but obj.__class__ is!
5475 This will allow using super() with a proxy for obj.
5476 */
5477
Guido van Rossum8e80a722003-02-18 19:22:22 +00005478 /* Check for first bullet above (special case) */
5479 if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
5480 Py_INCREF(obj);
5481 return (PyTypeObject *)obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005482 }
Guido van Rossum8e80a722003-02-18 19:22:22 +00005483
5484 /* Normal case */
5485 if (PyType_IsSubtype(obj->ob_type, type)) {
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005486 Py_INCREF(obj->ob_type);
5487 return obj->ob_type;
5488 }
5489 else {
5490 /* Try the slow way */
5491 static PyObject *class_str = NULL;
5492 PyObject *class_attr;
5493
5494 if (class_str == NULL) {
5495 class_str = PyString_FromString("__class__");
5496 if (class_str == NULL)
5497 return NULL;
5498 }
5499
5500 class_attr = PyObject_GetAttr(obj, class_str);
5501
5502 if (class_attr != NULL &&
5503 PyType_Check(class_attr) &&
5504 (PyTypeObject *)class_attr != obj->ob_type)
5505 {
5506 int ok = PyType_IsSubtype(
5507 (PyTypeObject *)class_attr, type);
5508 if (ok)
5509 return (PyTypeObject *)class_attr;
5510 }
5511
5512 if (class_attr == NULL)
5513 PyErr_Clear();
5514 else
5515 Py_DECREF(class_attr);
5516 }
5517
Tim Peters97e5ff52003-02-18 19:32:50 +00005518 PyErr_SetString(PyExc_TypeError,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005519 "super(type, obj): "
5520 "obj must be an instance or subtype of type");
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005521 return NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005522}
5523
Guido van Rossum705f0f52001-08-24 16:47:00 +00005524static PyObject *
5525super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5526{
5527 superobject *su = (superobject *)self;
5528 superobject *new;
5529
5530 if (obj == NULL || obj == Py_None || su->obj != NULL) {
5531 /* Not binding to an object, or already bound */
5532 Py_INCREF(self);
5533 return self;
5534 }
Guido van Rossum5b443c62001-12-03 15:38:28 +00005535 if (su->ob_type != &PySuper_Type)
5536 /* If su is an instance of a subclass of super,
5537 call its type */
5538 return PyObject_CallFunction((PyObject *)su->ob_type,
5539 "OO", su->type, obj);
5540 else {
5541 /* Inline the common case */
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005542 PyTypeObject *obj_type = supercheck(su->type, obj);
5543 if (obj_type == NULL)
Guido van Rossum5b443c62001-12-03 15:38:28 +00005544 return NULL;
5545 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
5546 NULL, NULL);
5547 if (new == NULL)
5548 return NULL;
5549 Py_INCREF(su->type);
5550 Py_INCREF(obj);
5551 new->type = su->type;
5552 new->obj = obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005553 new->obj_type = obj_type;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005554 return (PyObject *)new;
5555 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005556}
5557
5558static int
5559super_init(PyObject *self, PyObject *args, PyObject *kwds)
5560{
5561 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00005562 PyTypeObject *type;
5563 PyObject *obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005564 PyTypeObject *obj_type = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005565
5566 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
5567 return -1;
5568 if (obj == Py_None)
5569 obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005570 if (obj != NULL) {
5571 obj_type = supercheck(type, obj);
5572 if (obj_type == NULL)
5573 return -1;
5574 Py_INCREF(obj);
5575 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005576 Py_INCREF(type);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005577 su->type = type;
5578 su->obj = obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005579 su->obj_type = obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005580 return 0;
5581}
5582
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005583PyDoc_STRVAR(super_doc,
Guido van Rossum705f0f52001-08-24 16:47:00 +00005584"super(type) -> unbound super object\n"
5585"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00005586"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00005587"Typical use to call a cooperative superclass method:\n"
5588"class C(B):\n"
5589" def meth(self, arg):\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005590" super(C, self).meth(arg)");
Guido van Rossum705f0f52001-08-24 16:47:00 +00005591
Guido van Rossum048eb752001-10-02 21:24:57 +00005592static int
5593super_traverse(PyObject *self, visitproc visit, void *arg)
5594{
5595 superobject *su = (superobject *)self;
5596 int err;
5597
5598#define VISIT(SLOT) \
5599 if (SLOT) { \
5600 err = visit((PyObject *)(SLOT), arg); \
5601 if (err) \
5602 return err; \
5603 }
5604
5605 VISIT(su->obj);
5606 VISIT(su->type);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005607 VISIT(su->obj_type);
Guido van Rossum048eb752001-10-02 21:24:57 +00005608
5609#undef VISIT
5610
5611 return 0;
5612}
5613
Guido van Rossum705f0f52001-08-24 16:47:00 +00005614PyTypeObject PySuper_Type = {
5615 PyObject_HEAD_INIT(&PyType_Type)
5616 0, /* ob_size */
5617 "super", /* tp_name */
5618 sizeof(superobject), /* tp_basicsize */
5619 0, /* tp_itemsize */
5620 /* methods */
5621 super_dealloc, /* tp_dealloc */
5622 0, /* tp_print */
5623 0, /* tp_getattr */
5624 0, /* tp_setattr */
5625 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005626 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005627 0, /* tp_as_number */
5628 0, /* tp_as_sequence */
5629 0, /* tp_as_mapping */
5630 0, /* tp_hash */
5631 0, /* tp_call */
5632 0, /* tp_str */
5633 super_getattro, /* tp_getattro */
5634 0, /* tp_setattro */
5635 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00005636 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
5637 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005638 super_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00005639 super_traverse, /* tp_traverse */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005640 0, /* tp_clear */
5641 0, /* tp_richcompare */
5642 0, /* tp_weaklistoffset */
5643 0, /* tp_iter */
5644 0, /* tp_iternext */
5645 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005646 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005647 0, /* tp_getset */
5648 0, /* tp_base */
5649 0, /* tp_dict */
5650 super_descr_get, /* tp_descr_get */
5651 0, /* tp_descr_set */
5652 0, /* tp_dictoffset */
5653 super_init, /* tp_init */
5654 PyType_GenericAlloc, /* tp_alloc */
5655 PyType_GenericNew, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00005656 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005657};