blob: d45ee89adb0925450488ee97c369a2e62b30ff2c [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
641 /* Maybe call finalizer; exit early if resurrected */
Guido van Rossumfebd61d2002-08-08 20:55:20 +0000642 if (type->tp_del) {
643 type->tp_del(self);
644 if (self->ob_refcnt > 0)
645 goto endlabel;
646 }
Guido van Rossum7ad2d1e2001-10-29 22:11:00 +0000647
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000648 /* Find the nearest base with a different tp_dealloc
649 and clear slots while we're at it */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000650 base = type;
651 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
652 if (base->ob_size)
653 clear_slots(base, self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000654 base = base->tp_base;
655 assert(base);
Guido van Rossum14227b42001-12-06 02:35:58 +0000656 }
657
Tim Peters6d6c1a32001-08-02 04:15:00 +0000658 /* If we added a dict, DECREF it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000659 if (type->tp_dictoffset && !base->tp_dictoffset) {
660 PyObject **dictptr = _PyObject_GetDictPtr(self);
661 if (dictptr != NULL) {
662 PyObject *dict = *dictptr;
663 if (dict != NULL) {
664 Py_DECREF(dict);
665 *dictptr = NULL;
666 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000667 }
668 }
669
Guido van Rossum9676b222001-08-17 20:32:36 +0000670 /* If we added weaklist, we clear it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000671 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
Guido van Rossum9676b222001-08-17 20:32:36 +0000672 PyObject_ClearWeakRefs(self);
673
Tim Peters6d6c1a32001-08-02 04:15:00 +0000674 /* Finalize GC if the base doesn't do GC and we do */
Guido van Rossum22b13872002-08-06 21:41:44 +0000675 if (!PyType_IS_GC(base))
Guido van Rossum048eb752001-10-02 21:24:57 +0000676 _PyObject_GC_UNTRACK(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000677
678 /* Call the base tp_dealloc() */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000679 assert(basedealloc);
680 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000681
682 /* Can't reference self beyond this point */
Guido van Rossum22b13872002-08-06 21:41:44 +0000683 Py_DECREF(type);
684
Guido van Rossum0906e072002-08-07 20:42:09 +0000685 endlabel:
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000686 ++_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000687 Py_TRASHCAN_SAFE_END(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000688 --_PyTrash_delete_nesting;
689
690 /* Explanation of the weirdness around the trashcan macros:
691
692 Q. What do the trashcan macros do?
693
694 A. Read the comment titled "Trashcan mechanism" in object.h.
695 For one, this explains why there must be a call to GC-untrack
696 before the trashcan begin macro. Without understanding the
697 trashcan code, the answers to the following questions don't make
698 sense.
699
700 Q. Why do we GC-untrack before the trashcan and then immediately
701 GC-track again afterward?
702
703 A. In the case that the base class is GC-aware, the base class
704 probably GC-untracks the object. If it does that using the
705 UNTRACK macro, this will crash when the object is already
706 untracked. Because we don't know what the base class does, the
707 only safe thing is to make sure the object is tracked when we
708 call the base class dealloc. But... The trashcan begin macro
709 requires that the object is *untracked* before it is called. So
710 the dance becomes:
711
712 GC untrack
713 trashcan begin
714 GC track
715
716 Q. Why the bizarre (net-zero) manipulation of
717 _PyTrash_delete_nesting around the trashcan macros?
718
719 A. Some base classes (e.g. list) also use the trashcan mechanism.
720 The following scenario used to be possible:
721
722 - suppose the trashcan level is one below the trashcan limit
723
724 - subtype_dealloc() is called
725
726 - the trashcan limit is not yet reached, so the trashcan level
727 is incremented and the code between trashcan begin and end is
728 executed
729
730 - this destroys much of the object's contents, including its
731 slots and __dict__
732
733 - basedealloc() is called; this is really list_dealloc(), or
734 some other type which also uses the trashcan macros
735
736 - the trashcan limit is now reached, so the object is put on the
737 trashcan's to-be-deleted-later list
738
739 - basedealloc() returns
740
741 - subtype_dealloc() decrefs the object's type
742
743 - subtype_dealloc() returns
744
745 - later, the trashcan code starts deleting the objects from its
746 to-be-deleted-later list
747
748 - subtype_dealloc() is called *AGAIN* for the same object
749
750 - at the very least (if the destroyed slots and __dict__ don't
751 cause problems) the object's type gets decref'ed a second
752 time, which is *BAD*!!!
753
754 The remedy is to make sure that if the code between trashcan
755 begin and end in subtype_dealloc() is called, the code between
756 trashcan begin and end in basedealloc() will also be called.
757 This is done by decrementing the level after passing into the
758 trashcan block, and incrementing it just before leaving the
759 block.
760
761 But now it's possible that a chain of objects consisting solely
762 of objects whose deallocator is subtype_dealloc() will defeat
763 the trashcan mechanism completely: the decremented level means
764 that the effective level never reaches the limit. Therefore, we
765 *increment* the level *before* entering the trashcan block, and
766 matchingly decrement it after leaving. This means the trashcan
767 code will trigger a little early, but that's no big deal.
768
769 Q. Are there any live examples of code in need of all this
770 complexity?
771
772 A. Yes. See SF bug 668433 for code that crashed (when Python was
773 compiled in debug mode) before the trashcan level manipulations
774 were added. For more discussion, see SF patches 581742, 575073
775 and bug 574207.
776 */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000777}
778
Jeremy Hylton938ace62002-07-17 16:30:39 +0000779static PyTypeObject *solid_base(PyTypeObject *type);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000780
Tim Peters6d6c1a32001-08-02 04:15:00 +0000781/* type test with subclassing support */
782
783int
784PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
785{
786 PyObject *mro;
787
Guido van Rossum9478d072001-09-07 18:52:13 +0000788 if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
789 return b == a || b == &PyBaseObject_Type;
790
Tim Peters6d6c1a32001-08-02 04:15:00 +0000791 mro = a->tp_mro;
792 if (mro != NULL) {
793 /* Deal with multiple inheritance without recursion
794 by walking the MRO tuple */
795 int i, n;
796 assert(PyTuple_Check(mro));
797 n = PyTuple_GET_SIZE(mro);
798 for (i = 0; i < n; i++) {
799 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
800 return 1;
801 }
802 return 0;
803 }
804 else {
805 /* a is not completely initilized yet; follow tp_base */
806 do {
807 if (a == b)
808 return 1;
809 a = a->tp_base;
810 } while (a != NULL);
811 return b == &PyBaseObject_Type;
812 }
813}
814
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000815/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +0000816 without looking in the instance dictionary
817 (so we can't use PyObject_GetAttr) but still binding
818 it to the instance. The arguments are the object,
819 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000820 static variable used to cache the interned Python string.
821
822 Two variants:
823
824 - lookup_maybe() returns NULL without raising an exception
825 when the _PyType_Lookup() call fails;
826
827 - lookup_method() always raises an exception upon errors.
828*/
Guido van Rossum60718732001-08-28 17:47:51 +0000829
830static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000831lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +0000832{
833 PyObject *res;
834
835 if (*attrobj == NULL) {
836 *attrobj = PyString_InternFromString(attrstr);
837 if (*attrobj == NULL)
838 return NULL;
839 }
840 res = _PyType_Lookup(self->ob_type, *attrobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000841 if (res != NULL) {
Guido van Rossum60718732001-08-28 17:47:51 +0000842 descrgetfunc f;
843 if ((f = res->ob_type->tp_descr_get) == NULL)
844 Py_INCREF(res);
845 else
846 res = f(res, self, (PyObject *)(self->ob_type));
847 }
848 return res;
849}
850
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000851static PyObject *
852lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
853{
854 PyObject *res = lookup_maybe(self, attrstr, attrobj);
855 if (res == NULL && !PyErr_Occurred())
856 PyErr_SetObject(PyExc_AttributeError, *attrobj);
857 return res;
858}
859
Guido van Rossum2730b132001-08-28 18:22:14 +0000860/* A variation of PyObject_CallMethod that uses lookup_method()
861 instead of PyObject_GetAttrString(). This uses the same convention
862 as lookup_method to cache the interned name string object. */
863
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000864static PyObject *
Guido van Rossum2730b132001-08-28 18:22:14 +0000865call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
866{
867 va_list va;
868 PyObject *args, *func = 0, *retval;
Guido van Rossum2730b132001-08-28 18:22:14 +0000869 va_start(va, format);
870
Guido van Rossumda21c012001-10-03 00:50:18 +0000871 func = lookup_maybe(o, name, nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000872 if (func == NULL) {
873 va_end(va);
874 if (!PyErr_Occurred())
Guido van Rossumda21c012001-10-03 00:50:18 +0000875 PyErr_SetObject(PyExc_AttributeError, *nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000876 return NULL;
877 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000878
879 if (format && *format)
880 args = Py_VaBuildValue(format, va);
881 else
882 args = PyTuple_New(0);
883
884 va_end(va);
885
886 if (args == NULL)
887 return NULL;
888
889 assert(PyTuple_Check(args));
890 retval = PyObject_Call(func, args, NULL);
891
892 Py_DECREF(args);
893 Py_DECREF(func);
894
895 return retval;
896}
897
898/* Clone of call_method() that returns NotImplemented when the lookup fails. */
899
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000900static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000901call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
902{
903 va_list va;
904 PyObject *args, *func = 0, *retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000905 va_start(va, format);
906
Guido van Rossumda21c012001-10-03 00:50:18 +0000907 func = lookup_maybe(o, name, nameobj);
Guido van Rossum2730b132001-08-28 18:22:14 +0000908 if (func == NULL) {
909 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000910 if (!PyErr_Occurred()) {
911 Py_INCREF(Py_NotImplemented);
912 return Py_NotImplemented;
913 }
Guido van Rossum717ce002001-09-14 16:58:08 +0000914 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +0000915 }
916
917 if (format && *format)
918 args = Py_VaBuildValue(format, va);
919 else
920 args = PyTuple_New(0);
921
922 va_end(va);
923
Guido van Rossum717ce002001-09-14 16:58:08 +0000924 if (args == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +0000925 return NULL;
926
Guido van Rossum717ce002001-09-14 16:58:08 +0000927 assert(PyTuple_Check(args));
928 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +0000929
930 Py_DECREF(args);
931 Py_DECREF(func);
932
933 return retval;
934}
935
Tim Petersa91e9642001-11-14 23:32:33 +0000936static int
937fill_classic_mro(PyObject *mro, PyObject *cls)
938{
939 PyObject *bases, *base;
940 int i, n;
941
942 assert(PyList_Check(mro));
943 assert(PyClass_Check(cls));
944 i = PySequence_Contains(mro, cls);
945 if (i < 0)
946 return -1;
947 if (!i) {
948 if (PyList_Append(mro, cls) < 0)
949 return -1;
950 }
951 bases = ((PyClassObject *)cls)->cl_bases;
952 assert(bases && PyTuple_Check(bases));
953 n = PyTuple_GET_SIZE(bases);
954 for (i = 0; i < n; i++) {
955 base = PyTuple_GET_ITEM(bases, i);
956 if (fill_classic_mro(mro, base) < 0)
957 return -1;
958 }
959 return 0;
960}
961
962static PyObject *
963classic_mro(PyObject *cls)
964{
965 PyObject *mro;
966
967 assert(PyClass_Check(cls));
968 mro = PyList_New(0);
969 if (mro != NULL) {
970 if (fill_classic_mro(mro, cls) == 0)
971 return mro;
972 Py_DECREF(mro);
973 }
974 return NULL;
975}
976
Tim Petersea7f75d2002-12-07 21:39:16 +0000977/*
Guido van Rossum1f121312002-11-14 19:49:16 +0000978 Method resolution order algorithm C3 described in
979 "A Monotonic Superclass Linearization for Dylan",
980 by Kim Barrett, Bob Cassel, Paul Haahr,
Tim Petersea7f75d2002-12-07 21:39:16 +0000981 David A. Moon, Keith Playford, and P. Tucker Withington.
Guido van Rossum1f121312002-11-14 19:49:16 +0000982 (OOPSLA 1996)
983
Guido van Rossum98f33732002-11-25 21:36:54 +0000984 Some notes about the rules implied by C3:
985
Tim Petersea7f75d2002-12-07 21:39:16 +0000986 No duplicate bases.
Guido van Rossum98f33732002-11-25 21:36:54 +0000987 It isn't legal to repeat a class in a list of base classes.
988
989 The next three properties are the 3 constraints in "C3".
990
Tim Petersea7f75d2002-12-07 21:39:16 +0000991 Local precendece order.
Guido van Rossum98f33732002-11-25 21:36:54 +0000992 If A precedes B in C's MRO, then A will precede B in the MRO of all
993 subclasses of C.
994
995 Monotonicity.
996 The MRO of a class must be an extension without reordering of the
997 MRO of each of its superclasses.
998
999 Extended Precedence Graph (EPG).
1000 Linearization is consistent if there is a path in the EPG from
1001 each class to all its successors in the linearization. See
1002 the paper for definition of EPG.
Guido van Rossum1f121312002-11-14 19:49:16 +00001003 */
1004
Tim Petersea7f75d2002-12-07 21:39:16 +00001005static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001006tail_contains(PyObject *list, int whence, PyObject *o) {
1007 int j, size;
1008 size = PyList_GET_SIZE(list);
1009
1010 for (j = whence+1; j < size; j++) {
1011 if (PyList_GET_ITEM(list, j) == o)
1012 return 1;
1013 }
1014 return 0;
1015}
1016
Guido van Rossum98f33732002-11-25 21:36:54 +00001017static PyObject *
1018class_name(PyObject *cls)
1019{
1020 PyObject *name = PyObject_GetAttrString(cls, "__name__");
1021 if (name == NULL) {
1022 PyErr_Clear();
1023 Py_XDECREF(name);
1024 name = PyObject_Repr(cls);
1025 }
1026 if (name == NULL)
1027 return NULL;
1028 if (!PyString_Check(name)) {
1029 Py_DECREF(name);
1030 return NULL;
1031 }
1032 return name;
1033}
1034
1035static int
1036check_duplicates(PyObject *list)
1037{
1038 int i, j, n;
1039 /* Let's use a quadratic time algorithm,
1040 assuming that the bases lists is short.
1041 */
1042 n = PyList_GET_SIZE(list);
1043 for (i = 0; i < n; i++) {
1044 PyObject *o = PyList_GET_ITEM(list, i);
1045 for (j = i + 1; j < n; j++) {
1046 if (PyList_GET_ITEM(list, j) == o) {
1047 o = class_name(o);
1048 PyErr_Format(PyExc_TypeError,
1049 "duplicate base class %s",
1050 o ? PyString_AS_STRING(o) : "?");
1051 Py_XDECREF(o);
1052 return -1;
1053 }
1054 }
1055 }
1056 return 0;
1057}
1058
1059/* Raise a TypeError for an MRO order disagreement.
1060
1061 It's hard to produce a good error message. In the absence of better
1062 insight into error reporting, report the classes that were candidates
1063 to be put next into the MRO. There is some conflict between the
1064 order in which they should be put in the MRO, but it's hard to
1065 diagnose what constraint can't be satisfied.
1066*/
1067
1068static void
1069set_mro_error(PyObject *to_merge, int *remain)
1070{
1071 int i, n, off, to_merge_size;
1072 char buf[1000];
1073 PyObject *k, *v;
1074 PyObject *set = PyDict_New();
1075
1076 to_merge_size = PyList_GET_SIZE(to_merge);
1077 for (i = 0; i < to_merge_size; i++) {
1078 PyObject *L = PyList_GET_ITEM(to_merge, i);
1079 if (remain[i] < PyList_GET_SIZE(L)) {
1080 PyObject *c = PyList_GET_ITEM(L, remain[i]);
1081 if (PyDict_SetItem(set, c, Py_None) < 0)
1082 return;
1083 }
1084 }
1085 n = PyDict_Size(set);
1086
Raymond Hettingerf394df42003-04-06 19:13:41 +00001087 off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \
1088consistent method resolution\norder (MRO) for bases");
Guido van Rossum98f33732002-11-25 21:36:54 +00001089 i = 0;
1090 while (PyDict_Next(set, &i, &k, &v) && off < sizeof(buf)) {
1091 PyObject *name = class_name(k);
1092 off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s",
1093 name ? PyString_AS_STRING(name) : "?");
1094 Py_XDECREF(name);
1095 if (--n && off+1 < sizeof(buf)) {
1096 buf[off++] = ',';
1097 buf[off] = '\0';
1098 }
1099 }
1100 PyErr_SetString(PyExc_TypeError, buf);
1101 Py_DECREF(set);
1102}
1103
Tim Petersea7f75d2002-12-07 21:39:16 +00001104static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001105pmerge(PyObject *acc, PyObject* to_merge) {
1106 int i, j, to_merge_size;
1107 int *remain;
1108 int ok, empty_cnt;
Tim Petersea7f75d2002-12-07 21:39:16 +00001109
Guido van Rossum1f121312002-11-14 19:49:16 +00001110 to_merge_size = PyList_GET_SIZE(to_merge);
1111
Guido van Rossum98f33732002-11-25 21:36:54 +00001112 /* remain stores an index into each sublist of to_merge.
1113 remain[i] is the index of the next base in to_merge[i]
1114 that is not included in acc.
1115 */
Guido van Rossum1f121312002-11-14 19:49:16 +00001116 remain = PyMem_MALLOC(SIZEOF_INT*to_merge_size);
1117 if (remain == NULL)
1118 return -1;
1119 for (i = 0; i < to_merge_size; i++)
1120 remain[i] = 0;
1121
1122 again:
1123 empty_cnt = 0;
1124 for (i = 0; i < to_merge_size; i++) {
1125 PyObject *candidate;
Tim Petersea7f75d2002-12-07 21:39:16 +00001126
Guido van Rossum1f121312002-11-14 19:49:16 +00001127 PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
1128
1129 if (remain[i] >= PyList_GET_SIZE(cur_list)) {
1130 empty_cnt++;
1131 continue;
1132 }
1133
Guido van Rossum98f33732002-11-25 21:36:54 +00001134 /* Choose next candidate for MRO.
1135
1136 The input sequences alone can determine the choice.
1137 If not, choose the class which appears in the MRO
1138 of the earliest direct superclass of the new class.
1139 */
1140
Guido van Rossum1f121312002-11-14 19:49:16 +00001141 candidate = PyList_GET_ITEM(cur_list, remain[i]);
1142 for (j = 0; j < to_merge_size; j++) {
1143 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum98f33732002-11-25 21:36:54 +00001144 if (tail_contains(j_lst, remain[j], candidate)) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001145 goto skip; /* continue outer loop */
Guido van Rossum98f33732002-11-25 21:36:54 +00001146 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001147 }
1148 ok = PyList_Append(acc, candidate);
1149 if (ok < 0) {
1150 PyMem_Free(remain);
1151 return -1;
1152 }
1153 for (j = 0; j < to_merge_size; j++) {
1154 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum768158c2002-12-31 16:33:01 +00001155 if (remain[j] < PyList_GET_SIZE(j_lst) &&
1156 PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001157 remain[j]++;
1158 }
1159 }
1160 goto again;
Tim Peters9a6b8d82002-11-14 23:22:33 +00001161 skip: ;
Guido van Rossum1f121312002-11-14 19:49:16 +00001162 }
1163
Guido van Rossum98f33732002-11-25 21:36:54 +00001164 if (empty_cnt == to_merge_size) {
1165 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001166 return 0;
Guido van Rossum98f33732002-11-25 21:36:54 +00001167 }
1168 set_mro_error(to_merge, remain);
1169 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001170 return -1;
1171}
1172
Tim Peters6d6c1a32001-08-02 04:15:00 +00001173static PyObject *
1174mro_implementation(PyTypeObject *type)
1175{
1176 int i, n, ok;
1177 PyObject *bases, *result;
Guido van Rossum1f121312002-11-14 19:49:16 +00001178 PyObject *to_merge, *bases_aslist;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001179
Guido van Rossum63517572002-06-18 16:44:57 +00001180 if(type->tp_dict == NULL) {
1181 if(PyType_Ready(type) < 0)
1182 return NULL;
1183 }
1184
Guido van Rossum98f33732002-11-25 21:36:54 +00001185 /* Find a superclass linearization that honors the constraints
1186 of the explicit lists of bases and the constraints implied by
Tim Petersea7f75d2002-12-07 21:39:16 +00001187 each base class.
Guido van Rossum98f33732002-11-25 21:36:54 +00001188
1189 to_merge is a list of lists, where each list is a superclass
1190 linearization implied by a base class. The last element of
1191 to_merge is the declared list of bases.
1192 */
1193
Tim Peters6d6c1a32001-08-02 04:15:00 +00001194 bases = type->tp_bases;
1195 n = PyTuple_GET_SIZE(bases);
Guido van Rossum1f121312002-11-14 19:49:16 +00001196
1197 to_merge = PyList_New(n+1);
1198 if (to_merge == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001199 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001200
Tim Peters6d6c1a32001-08-02 04:15:00 +00001201 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001202 PyObject *base = PyTuple_GET_ITEM(bases, i);
1203 PyObject *parentMRO;
1204 if (PyType_Check(base))
1205 parentMRO = PySequence_List(
1206 ((PyTypeObject*)base)->tp_mro);
1207 else
1208 parentMRO = classic_mro(base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001209 if (parentMRO == NULL) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001210 Py_DECREF(to_merge);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001211 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001212 }
1213
1214 PyList_SET_ITEM(to_merge, i, parentMRO);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001215 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001216
1217 bases_aslist = PySequence_List(bases);
1218 if (bases_aslist == NULL) {
1219 Py_DECREF(to_merge);
1220 return NULL;
1221 }
Guido van Rossum98f33732002-11-25 21:36:54 +00001222 /* This is just a basic sanity check. */
1223 if (check_duplicates(bases_aslist) < 0) {
1224 Py_DECREF(to_merge);
1225 Py_DECREF(bases_aslist);
1226 return NULL;
1227 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001228 PyList_SET_ITEM(to_merge, n, bases_aslist);
1229
1230 result = Py_BuildValue("[O]", (PyObject *)type);
1231 if (result == NULL) {
1232 Py_DECREF(to_merge);
1233 return NULL;
1234 }
1235
1236 ok = pmerge(result, to_merge);
1237 Py_DECREF(to_merge);
1238 if (ok < 0) {
1239 Py_DECREF(result);
1240 return NULL;
1241 }
1242
Tim Peters6d6c1a32001-08-02 04:15:00 +00001243 return result;
1244}
1245
1246static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001247mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001248{
1249 PyTypeObject *type = (PyTypeObject *)self;
1250
Tim Peters6d6c1a32001-08-02 04:15:00 +00001251 return mro_implementation(type);
1252}
1253
1254static int
1255mro_internal(PyTypeObject *type)
1256{
1257 PyObject *mro, *result, *tuple;
1258
1259 if (type->ob_type == &PyType_Type) {
1260 result = mro_implementation(type);
1261 }
1262 else {
Guido van Rossum60718732001-08-28 17:47:51 +00001263 static PyObject *mro_str;
1264 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001265 if (mro == NULL)
1266 return -1;
1267 result = PyObject_CallObject(mro, NULL);
1268 Py_DECREF(mro);
1269 }
1270 if (result == NULL)
1271 return -1;
1272 tuple = PySequence_Tuple(result);
1273 Py_DECREF(result);
1274 type->tp_mro = tuple;
1275 return 0;
1276}
1277
1278
1279/* Calculate the best base amongst multiple base classes.
1280 This is the first one that's on the path to the "solid base". */
1281
1282static PyTypeObject *
1283best_base(PyObject *bases)
1284{
1285 int i, n;
1286 PyTypeObject *base, *winner, *candidate, *base_i;
Tim Petersa91e9642001-11-14 23:32:33 +00001287 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001288
1289 assert(PyTuple_Check(bases));
1290 n = PyTuple_GET_SIZE(bases);
1291 assert(n > 0);
Tim Petersa91e9642001-11-14 23:32:33 +00001292 base = NULL;
1293 winner = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001294 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001295 base_proto = PyTuple_GET_ITEM(bases, i);
1296 if (PyClass_Check(base_proto))
1297 continue;
1298 if (!PyType_Check(base_proto)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001299 PyErr_SetString(
1300 PyExc_TypeError,
1301 "bases must be types");
1302 return NULL;
1303 }
Tim Petersa91e9642001-11-14 23:32:33 +00001304 base_i = (PyTypeObject *)base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001305 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001306 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001307 return NULL;
1308 }
1309 candidate = solid_base(base_i);
Tim Petersa91e9642001-11-14 23:32:33 +00001310 if (winner == NULL) {
1311 winner = candidate;
1312 base = base_i;
1313 }
1314 else if (PyType_IsSubtype(winner, candidate))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001315 ;
1316 else if (PyType_IsSubtype(candidate, winner)) {
1317 winner = candidate;
1318 base = base_i;
1319 }
1320 else {
1321 PyErr_SetString(
1322 PyExc_TypeError,
1323 "multiple bases have "
1324 "instance lay-out conflict");
1325 return NULL;
1326 }
1327 }
Guido van Rossume54616c2001-12-14 04:19:56 +00001328 if (base == NULL)
1329 PyErr_SetString(PyExc_TypeError,
1330 "a new-style class can't have only classic bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001331 return base;
1332}
1333
1334static int
1335extra_ivars(PyTypeObject *type, PyTypeObject *base)
1336{
Neil Schemenauerc806c882001-08-29 23:54:54 +00001337 size_t t_size = type->tp_basicsize;
1338 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001339
Guido van Rossum9676b222001-08-17 20:32:36 +00001340 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001341 if (type->tp_itemsize || base->tp_itemsize) {
1342 /* If itemsize is involved, stricter rules */
1343 return t_size != b_size ||
1344 type->tp_itemsize != base->tp_itemsize;
1345 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001346 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
1347 type->tp_weaklistoffset + sizeof(PyObject *) == t_size)
1348 t_size -= sizeof(PyObject *);
1349 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
1350 type->tp_dictoffset + sizeof(PyObject *) == t_size)
1351 t_size -= sizeof(PyObject *);
1352
1353 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001354}
1355
1356static PyTypeObject *
1357solid_base(PyTypeObject *type)
1358{
1359 PyTypeObject *base;
1360
1361 if (type->tp_base)
1362 base = solid_base(type->tp_base);
1363 else
1364 base = &PyBaseObject_Type;
1365 if (extra_ivars(type, base))
1366 return type;
1367 else
1368 return base;
1369}
1370
Jeremy Hylton938ace62002-07-17 16:30:39 +00001371static void object_dealloc(PyObject *);
1372static int object_init(PyObject *, PyObject *, PyObject *);
1373static int update_slot(PyTypeObject *, PyObject *);
1374static void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001375
1376static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001377subtype_dict(PyObject *obj, void *context)
1378{
1379 PyObject **dictptr = _PyObject_GetDictPtr(obj);
1380 PyObject *dict;
1381
1382 if (dictptr == NULL) {
1383 PyErr_SetString(PyExc_AttributeError,
1384 "This object has no __dict__");
1385 return NULL;
1386 }
1387 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +00001388 if (dict == NULL)
1389 *dictptr = dict = PyDict_New();
1390 Py_XINCREF(dict);
1391 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001392}
1393
Guido van Rossum6661be32001-10-26 04:26:12 +00001394static int
1395subtype_setdict(PyObject *obj, PyObject *value, void *context)
1396{
1397 PyObject **dictptr = _PyObject_GetDictPtr(obj);
1398 PyObject *dict;
1399
1400 if (dictptr == NULL) {
1401 PyErr_SetString(PyExc_AttributeError,
1402 "This object has no __dict__");
1403 return -1;
1404 }
Guido van Rossumd331cb52001-12-05 19:46:42 +00001405 if (value != NULL && !PyDict_Check(value)) {
Guido van Rossum6661be32001-10-26 04:26:12 +00001406 PyErr_SetString(PyExc_TypeError,
1407 "__dict__ must be set to a dictionary");
1408 return -1;
1409 }
1410 dict = *dictptr;
Guido van Rossumd331cb52001-12-05 19:46:42 +00001411 Py_XINCREF(value);
Guido van Rossum6661be32001-10-26 04:26:12 +00001412 *dictptr = value;
1413 Py_XDECREF(dict);
1414 return 0;
1415}
1416
Guido van Rossumad47da02002-08-12 19:05:44 +00001417static PyObject *
1418subtype_getweakref(PyObject *obj, void *context)
1419{
1420 PyObject **weaklistptr;
1421 PyObject *result;
1422
1423 if (obj->ob_type->tp_weaklistoffset == 0) {
1424 PyErr_SetString(PyExc_AttributeError,
1425 "This object has no __weaklist__");
1426 return NULL;
1427 }
1428 assert(obj->ob_type->tp_weaklistoffset > 0);
1429 assert(obj->ob_type->tp_weaklistoffset + sizeof(PyObject *) <=
Guido van Rossum3747a0f2002-08-12 19:25:08 +00001430 (size_t)(obj->ob_type->tp_basicsize));
Guido van Rossumad47da02002-08-12 19:05:44 +00001431 weaklistptr = (PyObject **)
Guido van Rossum3747a0f2002-08-12 19:25:08 +00001432 ((char *)obj + obj->ob_type->tp_weaklistoffset);
Guido van Rossumad47da02002-08-12 19:05:44 +00001433 if (*weaklistptr == NULL)
1434 result = Py_None;
1435 else
1436 result = *weaklistptr;
1437 Py_INCREF(result);
1438 return result;
1439}
1440
Guido van Rossum373c7412003-01-07 13:41:37 +00001441/* Three variants on the subtype_getsets list. */
1442
1443static PyGetSetDef subtype_getsets_full[] = {
Guido van Rossumad47da02002-08-12 19:05:44 +00001444 {"__dict__", subtype_dict, subtype_setdict,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001445 PyDoc_STR("dictionary for instance variables (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001446 {"__weakref__", subtype_getweakref, NULL,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001447 PyDoc_STR("list of weak references to the object (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001448 {0}
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001449};
1450
Guido van Rossum373c7412003-01-07 13:41:37 +00001451static PyGetSetDef subtype_getsets_dict_only[] = {
1452 {"__dict__", subtype_dict, subtype_setdict,
1453 PyDoc_STR("dictionary for instance variables (if defined)")},
1454 {0}
1455};
1456
1457static PyGetSetDef subtype_getsets_weakref_only[] = {
1458 {"__weakref__", subtype_getweakref, NULL,
1459 PyDoc_STR("list of weak references to the object (if defined)")},
1460 {0}
1461};
1462
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001463static int
1464valid_identifier(PyObject *s)
1465{
Guido van Rossum03013a02002-07-16 14:30:28 +00001466 unsigned char *p;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001467 int i, n;
1468
1469 if (!PyString_Check(s)) {
1470 PyErr_SetString(PyExc_TypeError,
1471 "__slots__ must be strings");
1472 return 0;
1473 }
Guido van Rossum03013a02002-07-16 14:30:28 +00001474 p = (unsigned char *) PyString_AS_STRING(s);
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001475 n = PyString_GET_SIZE(s);
1476 /* We must reject an empty name. As a hack, we bump the
1477 length to 1 so that the loop will balk on the trailing \0. */
1478 if (n == 0)
1479 n = 1;
1480 for (i = 0; i < n; i++, p++) {
1481 if (!(i == 0 ? isalpha(*p) : isalnum(*p)) && *p != '_') {
1482 PyErr_SetString(PyExc_TypeError,
1483 "__slots__ must be identifiers");
1484 return 0;
1485 }
1486 }
1487 return 1;
1488}
1489
Martin v. Löwisd919a592002-10-14 21:07:28 +00001490#ifdef Py_USING_UNICODE
1491/* Replace Unicode objects in slots. */
1492
1493static PyObject *
1494_unicode_to_string(PyObject *slots, int nslots)
1495{
1496 PyObject *tmp = slots;
1497 PyObject *o, *o1;
1498 int i;
1499 intintargfunc copy = slots->ob_type->tp_as_sequence->sq_slice;
1500 for (i = 0; i < nslots; i++) {
1501 if (PyUnicode_Check(o = PyTuple_GET_ITEM(tmp, i))) {
1502 if (tmp == slots) {
1503 tmp = copy(slots, 0, PyTuple_GET_SIZE(slots));
1504 if (tmp == NULL)
1505 return NULL;
1506 }
1507 o1 = _PyUnicode_AsDefaultEncodedString
1508 (o, NULL);
1509 if (o1 == NULL) {
1510 Py_DECREF(tmp);
1511 return 0;
1512 }
1513 Py_INCREF(o1);
1514 Py_DECREF(o);
1515 PyTuple_SET_ITEM(tmp, i, o1);
1516 }
1517 }
1518 return tmp;
1519}
1520#endif
1521
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001522static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001523type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
1524{
1525 PyObject *name, *bases, *dict;
1526 static char *kwlist[] = {"name", "bases", "dict", 0};
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001527 PyObject *slots, *tmp, *newslots;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001528 PyTypeObject *type, *base, *tmptype, *winner;
Guido van Rossume5c691a2003-03-07 15:13:17 +00001529 PyHeapTypeObject *et;
Guido van Rossum6f799372001-09-20 20:46:19 +00001530 PyMemberDef *mp;
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001531 int i, nbases, nslots, slotoffset, add_dict, add_weak;
Guido van Rossumad47da02002-08-12 19:05:44 +00001532 int j, may_add_dict, may_add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001533
Tim Peters3abca122001-10-27 19:37:48 +00001534 assert(args != NULL && PyTuple_Check(args));
1535 assert(kwds == NULL || PyDict_Check(kwds));
1536
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001537 /* Special case: type(x) should return x->ob_type */
Tim Peters3abca122001-10-27 19:37:48 +00001538 {
1539 const int nargs = PyTuple_GET_SIZE(args);
1540 const int nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
1541
1542 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
1543 PyObject *x = PyTuple_GET_ITEM(args, 0);
1544 Py_INCREF(x->ob_type);
1545 return (PyObject *) x->ob_type;
1546 }
1547
1548 /* SF bug 475327 -- if that didn't trigger, we need 3
1549 arguments. but PyArg_ParseTupleAndKeywords below may give
1550 a msg saying type() needs exactly 3. */
1551 if (nargs + nkwds != 3) {
1552 PyErr_SetString(PyExc_TypeError,
1553 "type() takes 1 or 3 arguments");
1554 return NULL;
1555 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001556 }
1557
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001558 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001559 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
1560 &name,
1561 &PyTuple_Type, &bases,
1562 &PyDict_Type, &dict))
1563 return NULL;
1564
1565 /* Determine the proper metatype to deal with this,
1566 and check for metatype conflicts while we're at it.
1567 Note that if some other metatype wins to contract,
1568 it's possible that its instances are not types. */
1569 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001570 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001571 for (i = 0; i < nbases; i++) {
1572 tmp = PyTuple_GET_ITEM(bases, i);
1573 tmptype = tmp->ob_type;
Tim Petersa91e9642001-11-14 23:32:33 +00001574 if (tmptype == &PyClass_Type)
1575 continue; /* Special case classic classes */
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001576 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001577 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001578 if (PyType_IsSubtype(tmptype, winner)) {
1579 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001580 continue;
1581 }
1582 PyErr_SetString(PyExc_TypeError,
1583 "metatype conflict among bases");
1584 return NULL;
1585 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001586 if (winner != metatype) {
1587 if (winner->tp_new != type_new) /* Pass it to the winner */
1588 return winner->tp_new(winner, args, kwds);
1589 metatype = winner;
1590 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001591
1592 /* Adjust for empty tuple bases */
1593 if (nbases == 0) {
1594 bases = Py_BuildValue("(O)", &PyBaseObject_Type);
1595 if (bases == NULL)
1596 return NULL;
1597 nbases = 1;
1598 }
1599 else
1600 Py_INCREF(bases);
1601
1602 /* XXX From here until type is allocated, "return NULL" leaks bases! */
1603
1604 /* Calculate best base, and check that all bases are type objects */
1605 base = best_base(bases);
1606 if (base == NULL)
1607 return NULL;
1608 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
1609 PyErr_Format(PyExc_TypeError,
1610 "type '%.100s' is not an acceptable base type",
1611 base->tp_name);
1612 return NULL;
1613 }
1614
Tim Peters6d6c1a32001-08-02 04:15:00 +00001615 /* Check for a __slots__ sequence variable in dict, and count it */
1616 slots = PyDict_GetItemString(dict, "__slots__");
1617 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +00001618 add_dict = 0;
1619 add_weak = 0;
Guido van Rossumad47da02002-08-12 19:05:44 +00001620 may_add_dict = base->tp_dictoffset == 0;
1621 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
1622 if (slots == NULL) {
1623 if (may_add_dict) {
1624 add_dict++;
1625 }
1626 if (may_add_weak) {
1627 add_weak++;
1628 }
1629 }
1630 else {
1631 /* Have slots */
1632
Tim Peters6d6c1a32001-08-02 04:15:00 +00001633 /* Make it into a tuple */
1634 if (PyString_Check(slots))
1635 slots = Py_BuildValue("(O)", slots);
1636 else
1637 slots = PySequence_Tuple(slots);
1638 if (slots == NULL)
1639 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00001640 assert(PyTuple_Check(slots));
1641
1642 /* Are slots allowed? */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001643 nslots = PyTuple_GET_SIZE(slots);
Guido van Rossume5c691a2003-03-07 15:13:17 +00001644 if (nslots > 0 && base->tp_itemsize != 0 && !PyType_Check(base)) {
1645 /* for the special case of meta types, allow slots */
Guido van Rossumc4141872001-08-30 04:43:35 +00001646 PyErr_Format(PyExc_TypeError,
1647 "nonempty __slots__ "
1648 "not supported for subtype of '%s'",
1649 base->tp_name);
Guido van Rossumad47da02002-08-12 19:05:44 +00001650 bad_slots:
1651 Py_DECREF(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +00001652 return NULL;
1653 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001654
Martin v. Löwisd919a592002-10-14 21:07:28 +00001655#ifdef Py_USING_UNICODE
1656 tmp = _unicode_to_string(slots, nslots);
Martin v. Löwis13b1a5c2002-10-14 21:11:34 +00001657 if (tmp != slots) {
1658 Py_DECREF(slots);
1659 slots = tmp;
1660 }
Martin v. Löwisd919a592002-10-14 21:07:28 +00001661 if (!tmp)
1662 return NULL;
1663#endif
Guido van Rossumad47da02002-08-12 19:05:44 +00001664 /* Check for valid slot names and two special cases */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001665 for (i = 0; i < nslots; i++) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001666 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
1667 char *s;
1668 if (!valid_identifier(tmp))
1669 goto bad_slots;
1670 assert(PyString_Check(tmp));
1671 s = PyString_AS_STRING(tmp);
1672 if (strcmp(s, "__dict__") == 0) {
1673 if (!may_add_dict || add_dict) {
1674 PyErr_SetString(PyExc_TypeError,
1675 "__dict__ slot disallowed: "
1676 "we already got one");
1677 goto bad_slots;
1678 }
1679 add_dict++;
1680 }
1681 if (strcmp(s, "__weakref__") == 0) {
1682 if (!may_add_weak || add_weak) {
1683 PyErr_SetString(PyExc_TypeError,
1684 "__weakref__ slot disallowed: "
1685 "either we already got one, "
1686 "or __itemsize__ != 0");
1687 goto bad_slots;
1688 }
1689 add_weak++;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001690 }
1691 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001692
Guido van Rossumad47da02002-08-12 19:05:44 +00001693 /* Copy slots into yet another tuple, demangling names */
1694 newslots = PyTuple_New(nslots - add_dict - add_weak);
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001695 if (newslots == NULL)
Guido van Rossumad47da02002-08-12 19:05:44 +00001696 goto bad_slots;
1697 for (i = j = 0; i < nslots; i++) {
1698 char *s;
Guido van Rossum8e829202002-08-16 03:47:49 +00001699 char buffer[256];
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001700 tmp = PyTuple_GET_ITEM(slots, i);
Guido van Rossumad47da02002-08-12 19:05:44 +00001701 s = PyString_AS_STRING(tmp);
1702 if ((add_dict && strcmp(s, "__dict__") == 0) ||
1703 (add_weak && strcmp(s, "__weakref__") == 0))
1704 continue;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001705 if (_Py_Mangle(PyString_AS_STRING(name),
Guido van Rossumad47da02002-08-12 19:05:44 +00001706 PyString_AS_STRING(tmp),
1707 buffer, sizeof(buffer)))
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001708 {
1709 tmp = PyString_FromString(buffer);
1710 } else {
1711 Py_INCREF(tmp);
1712 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001713 PyTuple_SET_ITEM(newslots, j, tmp);
1714 j++;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001715 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001716 assert(j == nslots - add_dict - add_weak);
1717 nslots = j;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001718 Py_DECREF(slots);
1719 slots = newslots;
1720
Guido van Rossumad47da02002-08-12 19:05:44 +00001721 /* Secondary bases may provide weakrefs or dict */
1722 if (nbases > 1 &&
1723 ((may_add_dict && !add_dict) ||
1724 (may_add_weak && !add_weak))) {
1725 for (i = 0; i < nbases; i++) {
1726 tmp = PyTuple_GET_ITEM(bases, i);
1727 if (tmp == (PyObject *)base)
1728 continue; /* Skip primary base */
1729 if (PyClass_Check(tmp)) {
1730 /* Classic base class provides both */
1731 if (may_add_dict && !add_dict)
1732 add_dict++;
1733 if (may_add_weak && !add_weak)
1734 add_weak++;
1735 break;
1736 }
1737 assert(PyType_Check(tmp));
1738 tmptype = (PyTypeObject *)tmp;
1739 if (may_add_dict && !add_dict &&
1740 tmptype->tp_dictoffset != 0)
1741 add_dict++;
1742 if (may_add_weak && !add_weak &&
1743 tmptype->tp_weaklistoffset != 0)
1744 add_weak++;
1745 if (may_add_dict && !add_dict)
1746 continue;
1747 if (may_add_weak && !add_weak)
1748 continue;
1749 /* Nothing more to check */
1750 break;
1751 }
1752 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001753 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001754
1755 /* XXX From here until type is safely allocated,
1756 "return NULL" may leak slots! */
1757
1758 /* Allocate the type object */
1759 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
Guido van Rossumad47da02002-08-12 19:05:44 +00001760 if (type == NULL) {
1761 Py_XDECREF(slots);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001762 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00001763 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001764
1765 /* Keep name and slots alive in the extended type object */
Guido van Rossume5c691a2003-03-07 15:13:17 +00001766 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001767 Py_INCREF(name);
1768 et->name = name;
1769 et->slots = slots;
1770
Guido van Rossumdc91b992001-08-08 22:26:22 +00001771 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001772 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
1773 Py_TPFLAGS_BASETYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00001774 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
1775 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00001776
1777 /* It's a new-style number unless it specifically inherits any
1778 old-style numeric behavior */
1779 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
1780 (base->tp_as_number == NULL))
1781 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
1782
1783 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001784 type->tp_as_number = &et->as_number;
1785 type->tp_as_sequence = &et->as_sequence;
1786 type->tp_as_mapping = &et->as_mapping;
1787 type->tp_as_buffer = &et->as_buffer;
1788 type->tp_name = PyString_AS_STRING(name);
1789
1790 /* Set tp_base and tp_bases */
1791 type->tp_bases = bases;
1792 Py_INCREF(base);
1793 type->tp_base = base;
1794
Guido van Rossum687ae002001-10-15 22:03:32 +00001795 /* Initialize tp_dict from passed-in dict */
1796 type->tp_dict = dict = PyDict_Copy(dict);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001797 if (dict == NULL) {
1798 Py_DECREF(type);
1799 return NULL;
1800 }
1801
Guido van Rossumc3542212001-08-16 09:18:56 +00001802 /* Set __module__ in the dict */
1803 if (PyDict_GetItemString(dict, "__module__") == NULL) {
1804 tmp = PyEval_GetGlobals();
1805 if (tmp != NULL) {
1806 tmp = PyDict_GetItemString(tmp, "__name__");
1807 if (tmp != NULL) {
1808 if (PyDict_SetItemString(dict, "__module__",
1809 tmp) < 0)
1810 return NULL;
1811 }
1812 }
1813 }
1814
Tim Peters2f93e282001-10-04 05:27:00 +00001815 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
Tim Peters24008312002-03-17 18:56:20 +00001816 and is a string. The __doc__ accessor will first look for tp_doc;
1817 if that fails, it will still look into __dict__.
Tim Peters2f93e282001-10-04 05:27:00 +00001818 */
1819 {
1820 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
1821 if (doc != NULL && PyString_Check(doc)) {
1822 const size_t n = (size_t)PyString_GET_SIZE(doc);
Tim Peters59f809d2001-10-04 05:43:02 +00001823 type->tp_doc = (char *)PyObject_MALLOC(n+1);
Tim Peters2f93e282001-10-04 05:27:00 +00001824 if (type->tp_doc == NULL) {
1825 Py_DECREF(type);
1826 return NULL;
1827 }
1828 memcpy(type->tp_doc, PyString_AS_STRING(doc), n+1);
1829 }
1830 }
1831
Tim Peters6d6c1a32001-08-02 04:15:00 +00001832 /* Special-case __new__: if it's a plain function,
1833 make it a static function */
1834 tmp = PyDict_GetItemString(dict, "__new__");
1835 if (tmp != NULL && PyFunction_Check(tmp)) {
1836 tmp = PyStaticMethod_New(tmp);
1837 if (tmp == NULL) {
1838 Py_DECREF(type);
1839 return NULL;
1840 }
1841 PyDict_SetItemString(dict, "__new__", tmp);
1842 Py_DECREF(tmp);
1843 }
1844
1845 /* Add descriptors for custom slots from __slots__, or for __dict__ */
Guido van Rossume5c691a2003-03-07 15:13:17 +00001846 mp = PyHeapType_GET_MEMBERS(et);
Neil Schemenauerc806c882001-08-29 23:54:54 +00001847 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001848 if (slots != NULL) {
1849 for (i = 0; i < nslots; i++, mp++) {
1850 mp->name = PyString_AS_STRING(
1851 PyTuple_GET_ITEM(slots, i));
Guido van Rossum64b206c2001-12-04 17:13:22 +00001852 mp->type = T_OBJECT_EX;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001853 mp->offset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +00001854 if (base->tp_weaklistoffset == 0 &&
Guido van Rossum64b206c2001-12-04 17:13:22 +00001855 strcmp(mp->name, "__weakref__") == 0) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001856 add_weak++;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001857 mp->type = T_OBJECT;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001858 mp->flags = READONLY;
Guido van Rossum9676b222001-08-17 20:32:36 +00001859 type->tp_weaklistoffset = slotoffset;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001860 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001861 slotoffset += sizeof(PyObject *);
1862 }
1863 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001864 if (add_dict) {
1865 if (base->tp_itemsize)
1866 type->tp_dictoffset = -(long)sizeof(PyObject *);
1867 else
1868 type->tp_dictoffset = slotoffset;
1869 slotoffset += sizeof(PyObject *);
1870 }
1871 if (add_weak) {
1872 assert(!base->tp_itemsize);
1873 type->tp_weaklistoffset = slotoffset;
1874 slotoffset += sizeof(PyObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001875 }
1876 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001877 type->tp_itemsize = base->tp_itemsize;
Guido van Rossume5c691a2003-03-07 15:13:17 +00001878 type->tp_members = PyHeapType_GET_MEMBERS(et);
Guido van Rossum373c7412003-01-07 13:41:37 +00001879
1880 if (type->tp_weaklistoffset && type->tp_dictoffset)
1881 type->tp_getset = subtype_getsets_full;
1882 else if (type->tp_weaklistoffset && !type->tp_dictoffset)
1883 type->tp_getset = subtype_getsets_weakref_only;
1884 else if (!type->tp_weaklistoffset && type->tp_dictoffset)
1885 type->tp_getset = subtype_getsets_dict_only;
1886 else
1887 type->tp_getset = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001888
1889 /* Special case some slots */
1890 if (type->tp_dictoffset != 0 || nslots > 0) {
1891 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
1892 type->tp_getattro = PyObject_GenericGetAttr;
1893 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
1894 type->tp_setattro = PyObject_GenericSetAttr;
1895 }
1896 type->tp_dealloc = subtype_dealloc;
1897
Guido van Rossum9475a232001-10-05 20:51:39 +00001898 /* Enable GC unless there are really no instance variables possible */
1899 if (!(type->tp_basicsize == sizeof(PyObject) &&
1900 type->tp_itemsize == 0))
1901 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
1902
Tim Peters6d6c1a32001-08-02 04:15:00 +00001903 /* Always override allocation strategy to use regular heap */
1904 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00001905 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001906 type->tp_free = PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00001907 type->tp_traverse = subtype_traverse;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001908 type->tp_clear = subtype_clear;
Guido van Rossum048eb752001-10-02 21:24:57 +00001909 }
1910 else
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001911 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001912
1913 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001914 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001915 Py_DECREF(type);
1916 return NULL;
1917 }
1918
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001919 /* Put the proper slots in place */
1920 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00001921
Tim Peters6d6c1a32001-08-02 04:15:00 +00001922 return (PyObject *)type;
1923}
1924
1925/* Internal API to look for a name through the MRO.
1926 This returns a borrowed reference, and doesn't set an exception! */
1927PyObject *
1928_PyType_Lookup(PyTypeObject *type, PyObject *name)
1929{
1930 int i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00001931 PyObject *mro, *res, *base, *dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001932
Guido van Rossum687ae002001-10-15 22:03:32 +00001933 /* Look in tp_dict of types in MRO */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001934 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00001935
1936 /* If mro is NULL, the type is either not yet initialized
1937 by PyType_Ready(), or already cleared by type_clear().
1938 Either way the safest thing to do is to return NULL. */
1939 if (mro == NULL)
1940 return NULL;
1941
Tim Peters6d6c1a32001-08-02 04:15:00 +00001942 assert(PyTuple_Check(mro));
1943 n = PyTuple_GET_SIZE(mro);
1944 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001945 base = PyTuple_GET_ITEM(mro, i);
1946 if (PyClass_Check(base))
1947 dict = ((PyClassObject *)base)->cl_dict;
1948 else {
1949 assert(PyType_Check(base));
1950 dict = ((PyTypeObject *)base)->tp_dict;
1951 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001952 assert(dict && PyDict_Check(dict));
1953 res = PyDict_GetItem(dict, name);
1954 if (res != NULL)
1955 return res;
1956 }
1957 return NULL;
1958}
1959
1960/* This is similar to PyObject_GenericGetAttr(),
1961 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
1962static PyObject *
1963type_getattro(PyTypeObject *type, PyObject *name)
1964{
1965 PyTypeObject *metatype = type->ob_type;
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001966 PyObject *meta_attribute, *attribute;
1967 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001968
1969 /* Initialize this type (we'll assume the metatype is initialized) */
1970 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001971 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001972 return NULL;
1973 }
1974
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001975 /* No readable descriptor found yet */
1976 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00001977
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001978 /* Look for the attribute in the metatype */
1979 meta_attribute = _PyType_Lookup(metatype, name);
1980
1981 if (meta_attribute != NULL) {
1982 meta_get = meta_attribute->ob_type->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00001983
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001984 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
1985 /* Data descriptors implement tp_descr_set to intercept
1986 * writes. Assume the attribute is not overridden in
1987 * type's tp_dict (and bases): call the descriptor now.
1988 */
1989 return meta_get(meta_attribute, (PyObject *)type,
1990 (PyObject *)metatype);
1991 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001992 }
1993
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001994 /* No data descriptor found on metatype. Look in tp_dict of this
1995 * type and its bases */
1996 attribute = _PyType_Lookup(type, name);
1997 if (attribute != NULL) {
1998 /* Implement descriptor functionality, if any */
1999 descrgetfunc local_get = attribute->ob_type->tp_descr_get;
2000 if (local_get != NULL) {
2001 /* NULL 2nd argument indicates the descriptor was
2002 * found on the target object itself (or a base) */
2003 return local_get(attribute, (PyObject *)NULL,
2004 (PyObject *)type);
2005 }
Tim Peters34592512002-07-11 06:23:50 +00002006
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002007 Py_INCREF(attribute);
2008 return attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002009 }
2010
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002011 /* No attribute found in local __dict__ (or bases): use the
2012 * descriptor from the metatype, if any */
2013 if (meta_get != NULL)
2014 return meta_get(meta_attribute, (PyObject *)type,
2015 (PyObject *)metatype);
2016
2017 /* If an ordinary attribute was found on the metatype, return it now */
2018 if (meta_attribute != NULL) {
2019 Py_INCREF(meta_attribute);
2020 return meta_attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002021 }
2022
2023 /* Give up */
2024 PyErr_Format(PyExc_AttributeError,
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002025 "type object '%.50s' has no attribute '%.400s'",
2026 type->tp_name, PyString_AS_STRING(name));
Tim Peters6d6c1a32001-08-02 04:15:00 +00002027 return NULL;
2028}
2029
2030static int
2031type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
2032{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002033 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2034 PyErr_Format(
2035 PyExc_TypeError,
2036 "can't set attributes of built-in/extension type '%s'",
2037 type->tp_name);
2038 return -1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002039 }
Guido van Rossum8d24ee92003-03-24 23:49:49 +00002040 /* XXX Example of how I expect this to be used...
2041 if (update_subclasses(type, name, invalidate_cache, NULL) < 0)
2042 return -1;
2043 */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002044 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
2045 return -1;
2046 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002047}
2048
2049static void
2050type_dealloc(PyTypeObject *type)
2051{
Guido van Rossume5c691a2003-03-07 15:13:17 +00002052 PyHeapTypeObject *et;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002053
2054 /* Assert this is a heap-allocated type object */
2055 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002056 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00002057 PyObject_ClearWeakRefs((PyObject *)type);
Guido van Rossume5c691a2003-03-07 15:13:17 +00002058 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002059 Py_XDECREF(type->tp_base);
2060 Py_XDECREF(type->tp_dict);
2061 Py_XDECREF(type->tp_bases);
2062 Py_XDECREF(type->tp_mro);
Guido van Rossum687ae002001-10-15 22:03:32 +00002063 Py_XDECREF(type->tp_cache);
Guido van Rossum1c450732001-10-08 15:18:27 +00002064 Py_XDECREF(type->tp_subclasses);
Neal Norwitzcee5ca02002-07-30 00:42:06 +00002065 PyObject_Free(type->tp_doc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002066 Py_XDECREF(et->name);
2067 Py_XDECREF(et->slots);
2068 type->ob_type->tp_free((PyObject *)type);
2069}
2070
Guido van Rossum1c450732001-10-08 15:18:27 +00002071static PyObject *
2072type_subclasses(PyTypeObject *type, PyObject *args_ignored)
2073{
2074 PyObject *list, *raw, *ref;
2075 int i, n;
2076
2077 list = PyList_New(0);
2078 if (list == NULL)
2079 return NULL;
2080 raw = type->tp_subclasses;
2081 if (raw == NULL)
2082 return list;
2083 assert(PyList_Check(raw));
2084 n = PyList_GET_SIZE(raw);
2085 for (i = 0; i < n; i++) {
2086 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00002087 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00002088 ref = PyWeakref_GET_OBJECT(ref);
2089 if (ref != Py_None) {
2090 if (PyList_Append(list, ref) < 0) {
2091 Py_DECREF(list);
2092 return NULL;
2093 }
2094 }
2095 }
2096 return list;
2097}
2098
Tim Peters6d6c1a32001-08-02 04:15:00 +00002099static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002100 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002101 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
Guido van Rossum1c450732001-10-08 15:18:27 +00002102 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002103 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002104 {0}
2105};
2106
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002107PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002108"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002109"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002110
Guido van Rossum048eb752001-10-02 21:24:57 +00002111static int
2112type_traverse(PyTypeObject *type, visitproc visit, void *arg)
2113{
Guido van Rossum048eb752001-10-02 21:24:57 +00002114 int err;
2115
Guido van Rossuma3862092002-06-10 15:24:42 +00002116 /* Because of type_is_gc(), the collector only calls this
2117 for heaptypes. */
2118 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002119
2120#define VISIT(SLOT) \
2121 if (SLOT) { \
2122 err = visit((PyObject *)(SLOT), arg); \
2123 if (err) \
2124 return err; \
2125 }
2126
2127 VISIT(type->tp_dict);
Guido van Rossum687ae002001-10-15 22:03:32 +00002128 VISIT(type->tp_cache);
Guido van Rossum048eb752001-10-02 21:24:57 +00002129 VISIT(type->tp_mro);
2130 VISIT(type->tp_bases);
2131 VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00002132
2133 /* There's no need to visit type->tp_subclasses or
Guido van Rossume5c691a2003-03-07 15:13:17 +00002134 ((PyHeapTypeObject *)type)->slots, because they can't be involved
Guido van Rossuma3862092002-06-10 15:24:42 +00002135 in cycles; tp_subclasses is a list of weak references,
2136 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00002137
2138#undef VISIT
2139
2140 return 0;
2141}
2142
2143static int
2144type_clear(PyTypeObject *type)
2145{
Guido van Rossum048eb752001-10-02 21:24:57 +00002146 PyObject *tmp;
2147
Guido van Rossuma3862092002-06-10 15:24:42 +00002148 /* Because of type_is_gc(), the collector only calls this
2149 for heaptypes. */
2150 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002151
2152#define CLEAR(SLOT) \
2153 if (SLOT) { \
2154 tmp = (PyObject *)(SLOT); \
2155 SLOT = NULL; \
2156 Py_DECREF(tmp); \
2157 }
2158
Guido van Rossuma3862092002-06-10 15:24:42 +00002159 /* The only field we need to clear is tp_mro, which is part of a
2160 hard cycle (its first element is the class itself) that won't
2161 be broken otherwise (it's a tuple and tuples don't have a
2162 tp_clear handler). None of the other fields need to be
2163 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00002164
Guido van Rossuma3862092002-06-10 15:24:42 +00002165 tp_dict:
2166 It is a dict, so the collector will call its tp_clear.
2167
2168 tp_cache:
2169 Not used; if it were, it would be a dict.
2170
2171 tp_bases, tp_base:
2172 If these are involved in a cycle, there must be at least
2173 one other, mutable object in the cycle, e.g. a base
2174 class's dict; the cycle will be broken that way.
2175
2176 tp_subclasses:
2177 A list of weak references can't be part of a cycle; and
2178 lists have their own tp_clear.
2179
Guido van Rossume5c691a2003-03-07 15:13:17 +00002180 slots (in PyHeapTypeObject):
Guido van Rossuma3862092002-06-10 15:24:42 +00002181 A tuple of strings can't be part of a cycle.
2182 */
2183
2184 CLEAR(type->tp_mro);
Tim Peters2f93e282001-10-04 05:27:00 +00002185
Guido van Rossum048eb752001-10-02 21:24:57 +00002186#undef CLEAR
2187
2188 return 0;
2189}
2190
2191static int
2192type_is_gc(PyTypeObject *type)
2193{
2194 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
2195}
2196
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002197PyTypeObject PyType_Type = {
2198 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002199 0, /* ob_size */
2200 "type", /* tp_name */
Guido van Rossume5c691a2003-03-07 15:13:17 +00002201 sizeof(PyHeapTypeObject), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00002202 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002203 (destructor)type_dealloc, /* tp_dealloc */
2204 0, /* tp_print */
2205 0, /* tp_getattr */
2206 0, /* tp_setattr */
2207 type_compare, /* tp_compare */
2208 (reprfunc)type_repr, /* tp_repr */
2209 0, /* tp_as_number */
2210 0, /* tp_as_sequence */
2211 0, /* tp_as_mapping */
2212 (hashfunc)_Py_HashPointer, /* tp_hash */
2213 (ternaryfunc)type_call, /* tp_call */
2214 0, /* tp_str */
2215 (getattrofunc)type_getattro, /* tp_getattro */
2216 (setattrofunc)type_setattro, /* tp_setattro */
2217 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00002218 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2219 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002220 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00002221 (traverseproc)type_traverse, /* tp_traverse */
2222 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002223 0, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00002224 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002225 0, /* tp_iter */
2226 0, /* tp_iternext */
2227 type_methods, /* tp_methods */
2228 type_members, /* tp_members */
2229 type_getsets, /* tp_getset */
2230 0, /* tp_base */
2231 0, /* tp_dict */
2232 0, /* tp_descr_get */
2233 0, /* tp_descr_set */
2234 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
2235 0, /* tp_init */
2236 0, /* tp_alloc */
2237 type_new, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002238 PyObject_GC_Del, /* tp_free */
Guido van Rossum048eb752001-10-02 21:24:57 +00002239 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002240};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002241
2242
2243/* The base type of all types (eventually)... except itself. */
2244
2245static int
2246object_init(PyObject *self, PyObject *args, PyObject *kwds)
2247{
2248 return 0;
2249}
2250
Guido van Rossum298e4212003-02-13 16:30:16 +00002251/* If we don't have a tp_new for a new-style class, new will use this one.
2252 Therefore this should take no arguments/keywords. However, this new may
2253 also be inherited by objects that define a tp_init but no tp_new. These
2254 objects WILL pass argumets to tp_new, because it gets the same args as
2255 tp_init. So only allow arguments if we aren't using the default init, in
2256 which case we expect init to handle argument parsing. */
2257static PyObject *
2258object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2259{
2260 if (type->tp_init == object_init && (PyTuple_GET_SIZE(args) ||
2261 (kwds && PyDict_Check(kwds) && PyDict_Size(kwds)))) {
2262 PyErr_SetString(PyExc_TypeError,
2263 "default __new__ takes no parameters");
2264 return NULL;
2265 }
2266 return type->tp_alloc(type, 0);
2267}
2268
Tim Peters6d6c1a32001-08-02 04:15:00 +00002269static void
2270object_dealloc(PyObject *self)
2271{
2272 self->ob_type->tp_free(self);
2273}
2274
Guido van Rossum8e248182001-08-12 05:17:56 +00002275static PyObject *
2276object_repr(PyObject *self)
2277{
Guido van Rossum76e69632001-08-16 18:52:43 +00002278 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00002279 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002280
Guido van Rossum76e69632001-08-16 18:52:43 +00002281 type = self->ob_type;
2282 mod = type_module(type, NULL);
2283 if (mod == NULL)
2284 PyErr_Clear();
2285 else if (!PyString_Check(mod)) {
2286 Py_DECREF(mod);
2287 mod = NULL;
2288 }
2289 name = type_name(type, NULL);
2290 if (name == NULL)
2291 return NULL;
2292 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002293 rtn = PyString_FromFormat("<%s.%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002294 PyString_AS_STRING(mod),
2295 PyString_AS_STRING(name),
2296 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002297 else
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002298 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002299 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002300 Py_XDECREF(mod);
2301 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00002302 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002303}
2304
Guido van Rossumb8f63662001-08-15 23:57:02 +00002305static PyObject *
2306object_str(PyObject *self)
2307{
2308 unaryfunc f;
2309
2310 f = self->ob_type->tp_repr;
2311 if (f == NULL)
2312 f = object_repr;
2313 return f(self);
2314}
2315
Guido van Rossum8e248182001-08-12 05:17:56 +00002316static long
2317object_hash(PyObject *self)
2318{
2319 return _Py_HashPointer(self);
2320}
Guido van Rossum8e248182001-08-12 05:17:56 +00002321
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002322static PyObject *
2323object_get_class(PyObject *self, void *closure)
2324{
2325 Py_INCREF(self->ob_type);
2326 return (PyObject *)(self->ob_type);
2327}
2328
2329static int
2330equiv_structs(PyTypeObject *a, PyTypeObject *b)
2331{
2332 return a == b ||
2333 (a != NULL &&
2334 b != NULL &&
2335 a->tp_basicsize == b->tp_basicsize &&
2336 a->tp_itemsize == b->tp_itemsize &&
2337 a->tp_dictoffset == b->tp_dictoffset &&
2338 a->tp_weaklistoffset == b->tp_weaklistoffset &&
2339 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
2340 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
2341}
2342
2343static int
2344same_slots_added(PyTypeObject *a, PyTypeObject *b)
2345{
2346 PyTypeObject *base = a->tp_base;
2347 int size;
2348
2349 if (base != b->tp_base)
2350 return 0;
2351 if (equiv_structs(a, base) && equiv_structs(b, base))
2352 return 1;
2353 size = base->tp_basicsize;
2354 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
2355 size += sizeof(PyObject *);
2356 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
2357 size += sizeof(PyObject *);
2358 return size == a->tp_basicsize && size == b->tp_basicsize;
2359}
2360
2361static int
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002362compatible_for_assignment(PyTypeObject* old, PyTypeObject* new, char* attr)
2363{
2364 PyTypeObject *newbase, *oldbase;
2365
2366 if (new->tp_dealloc != old->tp_dealloc ||
2367 new->tp_free != old->tp_free)
2368 {
2369 PyErr_Format(PyExc_TypeError,
2370 "%s assignment: "
2371 "'%s' deallocator differs from '%s'",
2372 attr,
2373 new->tp_name,
2374 old->tp_name);
2375 return 0;
2376 }
2377 newbase = new;
2378 oldbase = old;
2379 while (equiv_structs(newbase, newbase->tp_base))
2380 newbase = newbase->tp_base;
2381 while (equiv_structs(oldbase, oldbase->tp_base))
2382 oldbase = oldbase->tp_base;
2383 if (newbase != oldbase &&
2384 (newbase->tp_base != oldbase->tp_base ||
2385 !same_slots_added(newbase, oldbase))) {
2386 PyErr_Format(PyExc_TypeError,
2387 "%s assignment: "
2388 "'%s' object layout differs from '%s'",
2389 attr,
2390 new->tp_name,
2391 old->tp_name);
2392 return 0;
2393 }
Tim Petersea7f75d2002-12-07 21:39:16 +00002394
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002395 return 1;
2396}
2397
2398static int
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002399object_set_class(PyObject *self, PyObject *value, void *closure)
2400{
2401 PyTypeObject *old = self->ob_type;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002402 PyTypeObject *new;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002403
Guido van Rossumb6b89422002-04-15 01:03:30 +00002404 if (value == NULL) {
2405 PyErr_SetString(PyExc_TypeError,
2406 "can't delete __class__ attribute");
2407 return -1;
2408 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002409 if (!PyType_Check(value)) {
2410 PyErr_Format(PyExc_TypeError,
2411 "__class__ must be set to new-style class, not '%s' object",
2412 value->ob_type->tp_name);
2413 return -1;
2414 }
2415 new = (PyTypeObject *)value;
Guido van Rossum40af8892002-08-10 05:42:07 +00002416 if (!(new->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
2417 !(old->tp_flags & Py_TPFLAGS_HEAPTYPE))
2418 {
2419 PyErr_Format(PyExc_TypeError,
2420 "__class__ assignment: only for heap types");
2421 return -1;
2422 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002423 if (compatible_for_assignment(new, old, "__class__")) {
2424 Py_INCREF(new);
2425 self->ob_type = new;
2426 Py_DECREF(old);
2427 return 0;
2428 }
2429 else {
Guido van Rossum9ee4b942002-05-24 18:47:47 +00002430 return -1;
2431 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002432}
2433
2434static PyGetSetDef object_getsets[] = {
2435 {"__class__", object_get_class, object_set_class,
Neal Norwitz858e34f2002-08-13 17:18:45 +00002436 PyDoc_STR("the object's class")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002437 {0}
2438};
2439
Guido van Rossumc53f0092003-02-18 22:05:12 +00002440
Guido van Rossum036f9992003-02-21 22:02:54 +00002441/* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
2442 We fall back to helpers in copy_reg for:
2443 - pickle protocols < 2
2444 - calculating the list of slot names (done only once per class)
2445 - the __newobj__ function (which is used as a token but never called)
2446*/
2447
2448static PyObject *
2449import_copy_reg(void)
2450{
2451 static PyObject *copy_reg_str;
Guido van Rossum3926a632001-09-25 16:25:58 +00002452
2453 if (!copy_reg_str) {
2454 copy_reg_str = PyString_InternFromString("copy_reg");
2455 if (copy_reg_str == NULL)
2456 return NULL;
2457 }
Guido van Rossum036f9992003-02-21 22:02:54 +00002458
2459 return PyImport_Import(copy_reg_str);
2460}
2461
2462static PyObject *
2463slotnames(PyObject *cls)
2464{
2465 PyObject *clsdict;
2466 PyObject *copy_reg;
2467 PyObject *slotnames;
2468
2469 if (!PyType_Check(cls)) {
2470 Py_INCREF(Py_None);
2471 return Py_None;
2472 }
2473
2474 clsdict = ((PyTypeObject *)cls)->tp_dict;
2475 slotnames = PyDict_GetItemString(clsdict, "__slotnames__");
2476 if (slotnames != NULL) {
2477 Py_INCREF(slotnames);
2478 return slotnames;
2479 }
2480
2481 copy_reg = import_copy_reg();
2482 if (copy_reg == NULL)
2483 return NULL;
2484
2485 slotnames = PyObject_CallMethod(copy_reg, "_slotnames", "O", cls);
2486 Py_DECREF(copy_reg);
2487 if (slotnames != NULL &&
2488 slotnames != Py_None &&
2489 !PyList_Check(slotnames))
2490 {
2491 PyErr_SetString(PyExc_TypeError,
2492 "copy_reg._slotnames didn't return a list or None");
2493 Py_DECREF(slotnames);
2494 slotnames = NULL;
2495 }
2496
2497 return slotnames;
2498}
2499
2500static PyObject *
2501reduce_2(PyObject *obj)
2502{
2503 PyObject *cls, *getnewargs;
2504 PyObject *args = NULL, *args2 = NULL;
2505 PyObject *getstate = NULL, *state = NULL, *names = NULL;
2506 PyObject *slots = NULL, *listitems = NULL, *dictitems = NULL;
2507 PyObject *copy_reg = NULL, *newobj = NULL, *res = NULL;
2508 int i, n;
2509
2510 cls = PyObject_GetAttrString(obj, "__class__");
2511 if (cls == NULL)
2512 return NULL;
2513
2514 getnewargs = PyObject_GetAttrString(obj, "__getnewargs__");
2515 if (getnewargs != NULL) {
2516 args = PyObject_CallObject(getnewargs, NULL);
2517 Py_DECREF(getnewargs);
2518 if (args != NULL && !PyTuple_Check(args)) {
2519 PyErr_SetString(PyExc_TypeError,
2520 "__getnewargs__ should return a tuple");
2521 goto end;
2522 }
2523 }
2524 else {
2525 PyErr_Clear();
2526 args = PyTuple_New(0);
2527 }
2528 if (args == NULL)
2529 goto end;
2530
2531 getstate = PyObject_GetAttrString(obj, "__getstate__");
2532 if (getstate != NULL) {
2533 state = PyObject_CallObject(getstate, NULL);
2534 Py_DECREF(getstate);
2535 }
2536 else {
2537 state = PyObject_GetAttrString(obj, "__dict__");
2538 if (state == NULL) {
2539 PyErr_Clear();
2540 state = Py_None;
2541 Py_INCREF(state);
2542 }
2543 names = slotnames(cls);
2544 if (names == NULL)
2545 goto end;
2546 if (names != Py_None) {
2547 assert(PyList_Check(names));
2548 slots = PyDict_New();
2549 if (slots == NULL)
2550 goto end;
2551 n = 0;
2552 /* Can't pre-compute the list size; the list
2553 is stored on the class so accessible to other
2554 threads, which may be run by DECREF */
2555 for (i = 0; i < PyList_GET_SIZE(names); i++) {
2556 PyObject *name, *value;
2557 name = PyList_GET_ITEM(names, i);
2558 value = PyObject_GetAttr(obj, name);
2559 if (value == NULL)
2560 PyErr_Clear();
2561 else {
2562 int err = PyDict_SetItem(slots, name,
2563 value);
2564 Py_DECREF(value);
2565 if (err)
2566 goto end;
2567 n++;
2568 }
2569 }
2570 if (n) {
2571 state = Py_BuildValue("(NO)", state, slots);
2572 if (state == NULL)
2573 goto end;
2574 }
2575 }
2576 }
2577
2578 if (!PyList_Check(obj)) {
2579 listitems = Py_None;
2580 Py_INCREF(listitems);
2581 }
2582 else {
2583 listitems = PyObject_GetIter(obj);
2584 if (listitems == NULL)
2585 goto end;
2586 }
2587
2588 if (!PyDict_Check(obj)) {
2589 dictitems = Py_None;
2590 Py_INCREF(dictitems);
2591 }
2592 else {
2593 dictitems = PyObject_CallMethod(obj, "iteritems", "");
2594 if (dictitems == NULL)
2595 goto end;
2596 }
2597
2598 copy_reg = import_copy_reg();
2599 if (copy_reg == NULL)
2600 goto end;
2601 newobj = PyObject_GetAttrString(copy_reg, "__newobj__");
2602 if (newobj == NULL)
2603 goto end;
2604
2605 n = PyTuple_GET_SIZE(args);
2606 args2 = PyTuple_New(n+1);
2607 if (args2 == NULL)
2608 goto end;
2609 PyTuple_SET_ITEM(args2, 0, cls);
2610 cls = NULL;
2611 for (i = 0; i < n; i++) {
2612 PyObject *v = PyTuple_GET_ITEM(args, i);
2613 Py_INCREF(v);
2614 PyTuple_SET_ITEM(args2, i+1, v);
2615 }
2616
2617 res = Py_BuildValue("(OOOOO)",
2618 newobj, args2, state, listitems, dictitems);
2619
2620 end:
2621 Py_XDECREF(cls);
2622 Py_XDECREF(args);
2623 Py_XDECREF(args2);
Jeremy Hyltond06483c2003-04-09 21:01:42 +00002624 Py_XDECREF(slots);
Guido van Rossum036f9992003-02-21 22:02:54 +00002625 Py_XDECREF(state);
2626 Py_XDECREF(names);
2627 Py_XDECREF(listitems);
2628 Py_XDECREF(dictitems);
2629 Py_XDECREF(copy_reg);
2630 Py_XDECREF(newobj);
2631 return res;
2632}
2633
2634static PyObject *
2635object_reduce_ex(PyObject *self, PyObject *args)
2636{
2637 /* Call copy_reg._reduce_ex(self, proto) */
2638 PyObject *reduce, *copy_reg, *res;
2639 int proto = 0;
2640
2641 if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
2642 return NULL;
2643
2644 reduce = PyObject_GetAttrString(self, "__reduce__");
2645 if (reduce == NULL)
2646 PyErr_Clear();
2647 else {
2648 PyObject *cls, *clsreduce, *objreduce;
2649 int override;
2650 cls = PyObject_GetAttrString(self, "__class__");
2651 if (cls == NULL) {
2652 Py_DECREF(reduce);
2653 return NULL;
2654 }
2655 clsreduce = PyObject_GetAttrString(cls, "__reduce__");
2656 Py_DECREF(cls);
2657 if (clsreduce == NULL) {
2658 Py_DECREF(reduce);
2659 return NULL;
2660 }
2661 objreduce = PyDict_GetItemString(PyBaseObject_Type.tp_dict,
2662 "__reduce__");
2663 override = (clsreduce != objreduce);
2664 Py_DECREF(clsreduce);
2665 if (override) {
2666 res = PyObject_CallObject(reduce, NULL);
2667 Py_DECREF(reduce);
2668 return res;
2669 }
2670 else
2671 Py_DECREF(reduce);
2672 }
2673
2674 if (proto >= 2)
2675 return reduce_2(self);
2676
2677 copy_reg = import_copy_reg();
Guido van Rossum3926a632001-09-25 16:25:58 +00002678 if (!copy_reg)
2679 return NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00002680
Guido van Rossumc53f0092003-02-18 22:05:12 +00002681 res = PyEval_CallMethod(copy_reg, "_reduce_ex", "(Oi)", self, proto);
Guido van Rossum3926a632001-09-25 16:25:58 +00002682 Py_DECREF(copy_reg);
Guido van Rossum036f9992003-02-21 22:02:54 +00002683
Guido van Rossum3926a632001-09-25 16:25:58 +00002684 return res;
2685}
2686
2687static PyMethodDef object_methods[] = {
Guido van Rossumc53f0092003-02-18 22:05:12 +00002688 {"__reduce_ex__", object_reduce_ex, METH_VARARGS,
2689 PyDoc_STR("helper for pickle")},
2690 {"__reduce__", object_reduce_ex, METH_VARARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002691 PyDoc_STR("helper for pickle")},
Guido van Rossum3926a632001-09-25 16:25:58 +00002692 {0}
2693};
2694
Guido van Rossum036f9992003-02-21 22:02:54 +00002695
Tim Peters6d6c1a32001-08-02 04:15:00 +00002696PyTypeObject PyBaseObject_Type = {
2697 PyObject_HEAD_INIT(&PyType_Type)
2698 0, /* ob_size */
2699 "object", /* tp_name */
2700 sizeof(PyObject), /* tp_basicsize */
2701 0, /* tp_itemsize */
2702 (destructor)object_dealloc, /* tp_dealloc */
2703 0, /* tp_print */
2704 0, /* tp_getattr */
2705 0, /* tp_setattr */
2706 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002707 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002708 0, /* tp_as_number */
2709 0, /* tp_as_sequence */
2710 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002711 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002712 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002713 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002714 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002715 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002716 0, /* tp_as_buffer */
2717 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002718 PyDoc_STR("The most base type"), /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002719 0, /* tp_traverse */
2720 0, /* tp_clear */
2721 0, /* tp_richcompare */
2722 0, /* tp_weaklistoffset */
2723 0, /* tp_iter */
2724 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00002725 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002726 0, /* tp_members */
2727 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002728 0, /* tp_base */
2729 0, /* tp_dict */
2730 0, /* tp_descr_get */
2731 0, /* tp_descr_set */
2732 0, /* tp_dictoffset */
2733 object_init, /* tp_init */
2734 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossum298e4212003-02-13 16:30:16 +00002735 object_new, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002736 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002737};
2738
2739
2740/* Initialize the __dict__ in a type object */
2741
2742static int
2743add_methods(PyTypeObject *type, PyMethodDef *meth)
2744{
Guido van Rossum687ae002001-10-15 22:03:32 +00002745 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002746
2747 for (; meth->ml_name != NULL; meth++) {
2748 PyObject *descr;
2749 if (PyDict_GetItemString(dict, meth->ml_name))
2750 continue;
Fred Drake7bf97152002-03-28 05:33:33 +00002751 if (meth->ml_flags & METH_CLASS) {
2752 if (meth->ml_flags & METH_STATIC) {
2753 PyErr_SetString(PyExc_ValueError,
2754 "method cannot be both class and static");
2755 return -1;
2756 }
Tim Petersbca1cbc2002-12-09 22:56:13 +00002757 descr = PyDescr_NewClassMethod(type, meth);
Fred Drake7bf97152002-03-28 05:33:33 +00002758 }
2759 else if (meth->ml_flags & METH_STATIC) {
Guido van Rossum9af48ff2003-02-11 17:12:46 +00002760 PyObject *cfunc = PyCFunction_New(meth, NULL);
2761 if (cfunc == NULL)
2762 return -1;
2763 descr = PyStaticMethod_New(cfunc);
2764 Py_DECREF(cfunc);
Fred Drake7bf97152002-03-28 05:33:33 +00002765 }
2766 else {
2767 descr = PyDescr_NewMethod(type, meth);
2768 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002769 if (descr == NULL)
2770 return -1;
Fred Drake7bf97152002-03-28 05:33:33 +00002771 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002772 return -1;
2773 Py_DECREF(descr);
2774 }
2775 return 0;
2776}
2777
2778static int
Guido van Rossum6f799372001-09-20 20:46:19 +00002779add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002780{
Guido van Rossum687ae002001-10-15 22:03:32 +00002781 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002782
2783 for (; memb->name != NULL; memb++) {
2784 PyObject *descr;
2785 if (PyDict_GetItemString(dict, memb->name))
2786 continue;
2787 descr = PyDescr_NewMember(type, memb);
2788 if (descr == NULL)
2789 return -1;
2790 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
2791 return -1;
2792 Py_DECREF(descr);
2793 }
2794 return 0;
2795}
2796
2797static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00002798add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002799{
Guido van Rossum687ae002001-10-15 22:03:32 +00002800 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002801
2802 for (; gsp->name != NULL; gsp++) {
2803 PyObject *descr;
2804 if (PyDict_GetItemString(dict, gsp->name))
2805 continue;
2806 descr = PyDescr_NewGetSet(type, gsp);
2807
2808 if (descr == NULL)
2809 return -1;
2810 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
2811 return -1;
2812 Py_DECREF(descr);
2813 }
2814 return 0;
2815}
2816
Guido van Rossum13d52f02001-08-10 21:24:08 +00002817static void
2818inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002819{
2820 int oldsize, newsize;
2821
Guido van Rossum13d52f02001-08-10 21:24:08 +00002822 /* Special flag magic */
2823 if (!type->tp_as_buffer && base->tp_as_buffer) {
2824 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
2825 type->tp_flags |=
2826 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
2827 }
2828 if (!type->tp_as_sequence && base->tp_as_sequence) {
2829 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
2830 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
2831 }
2832 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
2833 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
2834 if ((!type->tp_as_number && base->tp_as_number) ||
2835 (!type->tp_as_sequence && base->tp_as_sequence)) {
2836 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
2837 if (!type->tp_as_number && !type->tp_as_sequence) {
2838 type->tp_flags |= base->tp_flags &
2839 Py_TPFLAGS_HAVE_INPLACEOPS;
2840 }
2841 }
2842 /* Wow */
2843 }
2844 if (!type->tp_as_number && base->tp_as_number) {
2845 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
2846 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
2847 }
2848
2849 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00002850 oldsize = base->tp_basicsize;
2851 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
2852 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
2853 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00002854 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
2855 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00002856 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00002857 if (type->tp_traverse == NULL)
2858 type->tp_traverse = base->tp_traverse;
2859 if (type->tp_clear == NULL)
2860 type->tp_clear = base->tp_clear;
2861 }
2862 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
Guido van Rossumf884b742001-12-17 17:14:22 +00002863 /* The condition below could use some explanation.
2864 It appears that tp_new is not inherited for static types
2865 whose base class is 'object'; this seems to be a precaution
2866 so that old extension types don't suddenly become
2867 callable (object.__new__ wouldn't insure the invariants
2868 that the extension type's own factory function ensures).
2869 Heap types, of course, are under our control, so they do
2870 inherit tp_new; static extension types that specify some
2871 other built-in type as the default are considered
2872 new-style-aware so they also inherit object.__new__. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002873 if (base != &PyBaseObject_Type ||
2874 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2875 if (type->tp_new == NULL)
2876 type->tp_new = base->tp_new;
2877 }
2878 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00002879 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00002880
2881 /* Copy other non-function slots */
2882
2883#undef COPYVAL
2884#define COPYVAL(SLOT) \
2885 if (type->SLOT == 0) type->SLOT = base->SLOT
2886
2887 COPYVAL(tp_itemsize);
2888 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
2889 COPYVAL(tp_weaklistoffset);
2890 }
2891 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2892 COPYVAL(tp_dictoffset);
2893 }
Guido van Rossum13d52f02001-08-10 21:24:08 +00002894}
2895
2896static void
2897inherit_slots(PyTypeObject *type, PyTypeObject *base)
2898{
2899 PyTypeObject *basebase;
2900
2901#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00002902#undef COPYSLOT
2903#undef COPYNUM
2904#undef COPYSEQ
2905#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00002906#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00002907
2908#define SLOTDEFINED(SLOT) \
2909 (base->SLOT != 0 && \
2910 (basebase == NULL || base->SLOT != basebase->SLOT))
2911
Tim Peters6d6c1a32001-08-02 04:15:00 +00002912#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00002913 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00002914
2915#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
2916#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
2917#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00002918#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002919
Guido van Rossum13d52f02001-08-10 21:24:08 +00002920 /* This won't inherit indirect slots (from tp_as_number etc.)
2921 if type doesn't provide the space. */
2922
2923 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
2924 basebase = base->tp_base;
2925 if (basebase->tp_as_number == NULL)
2926 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002927 COPYNUM(nb_add);
2928 COPYNUM(nb_subtract);
2929 COPYNUM(nb_multiply);
2930 COPYNUM(nb_divide);
2931 COPYNUM(nb_remainder);
2932 COPYNUM(nb_divmod);
2933 COPYNUM(nb_power);
2934 COPYNUM(nb_negative);
2935 COPYNUM(nb_positive);
2936 COPYNUM(nb_absolute);
2937 COPYNUM(nb_nonzero);
2938 COPYNUM(nb_invert);
2939 COPYNUM(nb_lshift);
2940 COPYNUM(nb_rshift);
2941 COPYNUM(nb_and);
2942 COPYNUM(nb_xor);
2943 COPYNUM(nb_or);
2944 COPYNUM(nb_coerce);
2945 COPYNUM(nb_int);
2946 COPYNUM(nb_long);
2947 COPYNUM(nb_float);
2948 COPYNUM(nb_oct);
2949 COPYNUM(nb_hex);
2950 COPYNUM(nb_inplace_add);
2951 COPYNUM(nb_inplace_subtract);
2952 COPYNUM(nb_inplace_multiply);
2953 COPYNUM(nb_inplace_divide);
2954 COPYNUM(nb_inplace_remainder);
2955 COPYNUM(nb_inplace_power);
2956 COPYNUM(nb_inplace_lshift);
2957 COPYNUM(nb_inplace_rshift);
2958 COPYNUM(nb_inplace_and);
2959 COPYNUM(nb_inplace_xor);
2960 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00002961 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
2962 COPYNUM(nb_true_divide);
2963 COPYNUM(nb_floor_divide);
2964 COPYNUM(nb_inplace_true_divide);
2965 COPYNUM(nb_inplace_floor_divide);
2966 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002967 }
2968
Guido van Rossum13d52f02001-08-10 21:24:08 +00002969 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
2970 basebase = base->tp_base;
2971 if (basebase->tp_as_sequence == NULL)
2972 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002973 COPYSEQ(sq_length);
2974 COPYSEQ(sq_concat);
2975 COPYSEQ(sq_repeat);
2976 COPYSEQ(sq_item);
2977 COPYSEQ(sq_slice);
2978 COPYSEQ(sq_ass_item);
2979 COPYSEQ(sq_ass_slice);
2980 COPYSEQ(sq_contains);
2981 COPYSEQ(sq_inplace_concat);
2982 COPYSEQ(sq_inplace_repeat);
2983 }
2984
Guido van Rossum13d52f02001-08-10 21:24:08 +00002985 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
2986 basebase = base->tp_base;
2987 if (basebase->tp_as_mapping == NULL)
2988 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002989 COPYMAP(mp_length);
2990 COPYMAP(mp_subscript);
2991 COPYMAP(mp_ass_subscript);
2992 }
2993
Tim Petersfc57ccb2001-10-12 02:38:24 +00002994 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
2995 basebase = base->tp_base;
2996 if (basebase->tp_as_buffer == NULL)
2997 basebase = NULL;
2998 COPYBUF(bf_getreadbuffer);
2999 COPYBUF(bf_getwritebuffer);
3000 COPYBUF(bf_getsegcount);
3001 COPYBUF(bf_getcharbuffer);
3002 }
3003
Guido van Rossum13d52f02001-08-10 21:24:08 +00003004 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003005
Tim Peters6d6c1a32001-08-02 04:15:00 +00003006 COPYSLOT(tp_dealloc);
3007 COPYSLOT(tp_print);
3008 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
3009 type->tp_getattr = base->tp_getattr;
3010 type->tp_getattro = base->tp_getattro;
3011 }
3012 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
3013 type->tp_setattr = base->tp_setattr;
3014 type->tp_setattro = base->tp_setattro;
3015 }
3016 /* tp_compare see tp_richcompare */
3017 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003018 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003019 COPYSLOT(tp_call);
3020 COPYSLOT(tp_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003021 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003022 if (type->tp_compare == NULL &&
3023 type->tp_richcompare == NULL &&
3024 type->tp_hash == NULL)
3025 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003026 type->tp_compare = base->tp_compare;
3027 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003028 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003029 }
3030 }
3031 else {
3032 COPYSLOT(tp_compare);
3033 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003034 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
3035 COPYSLOT(tp_iter);
3036 COPYSLOT(tp_iternext);
3037 }
3038 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
3039 COPYSLOT(tp_descr_get);
3040 COPYSLOT(tp_descr_set);
3041 COPYSLOT(tp_dictoffset);
3042 COPYSLOT(tp_init);
3043 COPYSLOT(tp_alloc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003044 COPYSLOT(tp_free);
Guido van Rossumcc8fe042002-04-05 17:10:16 +00003045 COPYSLOT(tp_is_gc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003046 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003047}
3048
Jeremy Hylton938ace62002-07-17 16:30:39 +00003049static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00003050
Tim Peters6d6c1a32001-08-02 04:15:00 +00003051int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00003052PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003053{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003054 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003055 PyTypeObject *base;
3056 int i, n;
3057
Guido van Rossumcab05802002-06-10 15:29:03 +00003058 if (type->tp_flags & Py_TPFLAGS_READY) {
3059 assert(type->tp_dict != NULL);
Guido van Rossumd614f972001-08-10 17:39:49 +00003060 return 0;
Guido van Rossumcab05802002-06-10 15:29:03 +00003061 }
Guido van Rossumd614f972001-08-10 17:39:49 +00003062 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00003063
3064 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003065
Tim Peters36eb4df2003-03-23 03:33:13 +00003066#ifdef Py_TRACE_REFS
3067 /* PyType_Ready is the closest thing we have to a choke point
3068 * for type objects, so is the best place I can think of to try
3069 * to get type objects into the doubly-linked list of all objects.
3070 * Still, not all type objects go thru PyType_Ready.
3071 */
Tim Peters7571a0f2003-03-23 17:52:28 +00003072 _Py_AddToAllObjects((PyObject *)type, 0);
Tim Peters36eb4df2003-03-23 03:33:13 +00003073#endif
3074
Tim Peters6d6c1a32001-08-02 04:15:00 +00003075 /* Initialize tp_base (defaults to BaseObject unless that's us) */
3076 base = type->tp_base;
3077 if (base == NULL && type != &PyBaseObject_Type)
3078 base = type->tp_base = &PyBaseObject_Type;
3079
Guido van Rossum323a9cf2002-08-14 17:26:30 +00003080 /* Initialize the base class */
3081 if (base && base->tp_dict == NULL) {
3082 if (PyType_Ready(base) < 0)
3083 goto error;
3084 }
3085
Guido van Rossum0986d822002-04-08 01:38:42 +00003086 /* Initialize ob_type if NULL. This means extensions that want to be
3087 compilable separately on Windows can call PyType_Ready() instead of
3088 initializing the ob_type field of their type objects. */
3089 if (type->ob_type == NULL)
3090 type->ob_type = base->ob_type;
3091
Tim Peters6d6c1a32001-08-02 04:15:00 +00003092 /* Initialize tp_bases */
3093 bases = type->tp_bases;
3094 if (bases == NULL) {
3095 if (base == NULL)
3096 bases = PyTuple_New(0);
3097 else
3098 bases = Py_BuildValue("(O)", base);
3099 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003100 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003101 type->tp_bases = bases;
3102 }
3103
Guido van Rossum687ae002001-10-15 22:03:32 +00003104 /* Initialize tp_dict */
3105 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003106 if (dict == NULL) {
3107 dict = PyDict_New();
3108 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003109 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00003110 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003111 }
3112
Guido van Rossum687ae002001-10-15 22:03:32 +00003113 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003114 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003115 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003116 if (type->tp_methods != NULL) {
3117 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003118 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003119 }
3120 if (type->tp_members != NULL) {
3121 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003122 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003123 }
3124 if (type->tp_getset != NULL) {
3125 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003126 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003127 }
3128
Tim Peters6d6c1a32001-08-02 04:15:00 +00003129 /* Calculate method resolution order */
3130 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00003131 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003132 }
3133
Guido van Rossum13d52f02001-08-10 21:24:08 +00003134 /* Inherit special flags from dominant base */
3135 if (type->tp_base != NULL)
3136 inherit_special(type, type->tp_base);
3137
Tim Peters6d6c1a32001-08-02 04:15:00 +00003138 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003139 bases = type->tp_mro;
3140 assert(bases != NULL);
3141 assert(PyTuple_Check(bases));
3142 n = PyTuple_GET_SIZE(bases);
3143 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003144 PyObject *b = PyTuple_GET_ITEM(bases, i);
3145 if (PyType_Check(b))
3146 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003147 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003148
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003149 /* if the type dictionary doesn't contain a __doc__, set it from
3150 the tp_doc slot.
3151 */
3152 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
3153 if (type->tp_doc != NULL) {
3154 PyObject *doc = PyString_FromString(type->tp_doc);
3155 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
3156 Py_DECREF(doc);
3157 } else {
Guido van Rossumd4641072002-04-03 02:13:37 +00003158 PyDict_SetItemString(type->tp_dict,
3159 "__doc__", Py_None);
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003160 }
3161 }
3162
Guido van Rossum13d52f02001-08-10 21:24:08 +00003163 /* Some more special stuff */
3164 base = type->tp_base;
3165 if (base != NULL) {
3166 if (type->tp_as_number == NULL)
3167 type->tp_as_number = base->tp_as_number;
3168 if (type->tp_as_sequence == NULL)
3169 type->tp_as_sequence = base->tp_as_sequence;
3170 if (type->tp_as_mapping == NULL)
3171 type->tp_as_mapping = base->tp_as_mapping;
Guido van Rossumeea47182003-02-11 20:39:59 +00003172 if (type->tp_as_buffer == NULL)
3173 type->tp_as_buffer = base->tp_as_buffer;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003174 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003175
Guido van Rossum1c450732001-10-08 15:18:27 +00003176 /* Link into each base class's list of subclasses */
3177 bases = type->tp_bases;
3178 n = PyTuple_GET_SIZE(bases);
3179 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003180 PyObject *b = PyTuple_GET_ITEM(bases, i);
3181 if (PyType_Check(b) &&
3182 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00003183 goto error;
3184 }
3185
Guido van Rossum13d52f02001-08-10 21:24:08 +00003186 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00003187 assert(type->tp_dict != NULL);
3188 type->tp_flags =
3189 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003190 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00003191
3192 error:
3193 type->tp_flags &= ~Py_TPFLAGS_READYING;
3194 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003195}
3196
Guido van Rossum1c450732001-10-08 15:18:27 +00003197static int
3198add_subclass(PyTypeObject *base, PyTypeObject *type)
3199{
3200 int i;
3201 PyObject *list, *ref, *new;
3202
3203 list = base->tp_subclasses;
3204 if (list == NULL) {
3205 base->tp_subclasses = list = PyList_New(0);
3206 if (list == NULL)
3207 return -1;
3208 }
3209 assert(PyList_Check(list));
3210 new = PyWeakref_NewRef((PyObject *)type, NULL);
3211 i = PyList_GET_SIZE(list);
3212 while (--i >= 0) {
3213 ref = PyList_GET_ITEM(list, i);
3214 assert(PyWeakref_CheckRef(ref));
Guido van Rossum3930bc32002-10-18 13:51:49 +00003215 if (PyWeakref_GET_OBJECT(ref) == Py_None)
3216 return PyList_SetItem(list, i, new);
Guido van Rossum1c450732001-10-08 15:18:27 +00003217 }
3218 i = PyList_Append(list, new);
3219 Py_DECREF(new);
3220 return i;
3221}
3222
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003223static void
3224remove_subclass(PyTypeObject *base, PyTypeObject *type)
3225{
3226 int i;
3227 PyObject *list, *ref;
3228
3229 list = base->tp_subclasses;
3230 if (list == NULL) {
3231 return;
3232 }
3233 assert(PyList_Check(list));
3234 i = PyList_GET_SIZE(list);
3235 while (--i >= 0) {
3236 ref = PyList_GET_ITEM(list, i);
3237 assert(PyWeakref_CheckRef(ref));
3238 if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
3239 /* this can't fail, right? */
3240 PySequence_DelItem(list, i);
3241 return;
3242 }
3243 }
3244}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003245
3246/* Generic wrappers for overloadable 'operators' such as __getitem__ */
3247
3248/* There's a wrapper *function* for each distinct function typedef used
3249 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
3250 wrapper *table* for each distinct operation (e.g. __len__, __add__).
3251 Most tables have only one entry; the tables for binary operators have two
3252 entries, one regular and one with reversed arguments. */
3253
3254static PyObject *
3255wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
3256{
3257 inquiry func = (inquiry)wrapped;
3258 int res;
3259
3260 if (!PyArg_ParseTuple(args, ""))
3261 return NULL;
3262 res = (*func)(self);
3263 if (res == -1 && PyErr_Occurred())
3264 return NULL;
3265 return PyInt_FromLong((long)res);
3266}
3267
Tim Peters6d6c1a32001-08-02 04:15:00 +00003268static PyObject *
3269wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
3270{
3271 binaryfunc func = (binaryfunc)wrapped;
3272 PyObject *other;
3273
3274 if (!PyArg_ParseTuple(args, "O", &other))
3275 return NULL;
3276 return (*func)(self, other);
3277}
3278
3279static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003280wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
3281{
3282 binaryfunc func = (binaryfunc)wrapped;
3283 PyObject *other;
3284
3285 if (!PyArg_ParseTuple(args, "O", &other))
3286 return NULL;
3287 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003288 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003289 Py_INCREF(Py_NotImplemented);
3290 return Py_NotImplemented;
3291 }
3292 return (*func)(self, other);
3293}
3294
3295static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003296wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3297{
3298 binaryfunc func = (binaryfunc)wrapped;
3299 PyObject *other;
3300
3301 if (!PyArg_ParseTuple(args, "O", &other))
3302 return NULL;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003303 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003304 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003305 Py_INCREF(Py_NotImplemented);
3306 return Py_NotImplemented;
3307 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003308 return (*func)(other, self);
3309}
3310
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003311static PyObject *
3312wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
3313{
3314 coercion func = (coercion)wrapped;
3315 PyObject *other, *res;
3316 int ok;
3317
3318 if (!PyArg_ParseTuple(args, "O", &other))
3319 return NULL;
3320 ok = func(&self, &other);
3321 if (ok < 0)
3322 return NULL;
3323 if (ok > 0) {
3324 Py_INCREF(Py_NotImplemented);
3325 return Py_NotImplemented;
3326 }
3327 res = PyTuple_New(2);
3328 if (res == NULL) {
3329 Py_DECREF(self);
3330 Py_DECREF(other);
3331 return NULL;
3332 }
3333 PyTuple_SET_ITEM(res, 0, self);
3334 PyTuple_SET_ITEM(res, 1, other);
3335 return res;
3336}
3337
Tim Peters6d6c1a32001-08-02 04:15:00 +00003338static PyObject *
3339wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
3340{
3341 ternaryfunc func = (ternaryfunc)wrapped;
3342 PyObject *other;
3343 PyObject *third = Py_None;
3344
3345 /* Note: This wrapper only works for __pow__() */
3346
3347 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
3348 return NULL;
3349 return (*func)(self, other, third);
3350}
3351
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00003352static PyObject *
3353wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3354{
3355 ternaryfunc func = (ternaryfunc)wrapped;
3356 PyObject *other;
3357 PyObject *third = Py_None;
3358
3359 /* Note: This wrapper only works for __pow__() */
3360
3361 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
3362 return NULL;
3363 return (*func)(other, self, third);
3364}
3365
Tim Peters6d6c1a32001-08-02 04:15:00 +00003366static PyObject *
3367wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
3368{
3369 unaryfunc func = (unaryfunc)wrapped;
3370
3371 if (!PyArg_ParseTuple(args, ""))
3372 return NULL;
3373 return (*func)(self);
3374}
3375
Tim Peters6d6c1a32001-08-02 04:15:00 +00003376static PyObject *
3377wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
3378{
3379 intargfunc func = (intargfunc)wrapped;
3380 int i;
3381
3382 if (!PyArg_ParseTuple(args, "i", &i))
3383 return NULL;
3384 return (*func)(self, i);
3385}
3386
Guido van Rossum5d815f32001-08-17 21:57:47 +00003387static int
3388getindex(PyObject *self, PyObject *arg)
3389{
3390 int i;
3391
3392 i = PyInt_AsLong(arg);
3393 if (i == -1 && PyErr_Occurred())
3394 return -1;
3395 if (i < 0) {
3396 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
3397 if (sq && sq->sq_length) {
3398 int n = (*sq->sq_length)(self);
3399 if (n < 0)
3400 return -1;
3401 i += n;
3402 }
3403 }
3404 return i;
3405}
3406
3407static PyObject *
3408wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
3409{
3410 intargfunc func = (intargfunc)wrapped;
3411 PyObject *arg;
3412 int i;
3413
Guido van Rossumf4593e02001-10-03 12:09:30 +00003414 if (PyTuple_GET_SIZE(args) == 1) {
3415 arg = PyTuple_GET_ITEM(args, 0);
3416 i = getindex(self, arg);
3417 if (i == -1 && PyErr_Occurred())
3418 return NULL;
3419 return (*func)(self, i);
3420 }
3421 PyArg_ParseTuple(args, "O", &arg);
3422 assert(PyErr_Occurred());
3423 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003424}
3425
Tim Peters6d6c1a32001-08-02 04:15:00 +00003426static PyObject *
3427wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
3428{
3429 intintargfunc func = (intintargfunc)wrapped;
3430 int i, j;
3431
3432 if (!PyArg_ParseTuple(args, "ii", &i, &j))
3433 return NULL;
3434 return (*func)(self, i, j);
3435}
3436
Tim Peters6d6c1a32001-08-02 04:15:00 +00003437static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003438wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003439{
3440 intobjargproc func = (intobjargproc)wrapped;
3441 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003442 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003443
Guido van Rossum5d815f32001-08-17 21:57:47 +00003444 if (!PyArg_ParseTuple(args, "OO", &arg, &value))
3445 return NULL;
3446 i = getindex(self, arg);
3447 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00003448 return NULL;
3449 res = (*func)(self, i, value);
3450 if (res == -1 && PyErr_Occurred())
3451 return NULL;
3452 Py_INCREF(Py_None);
3453 return Py_None;
3454}
3455
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003456static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003457wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003458{
3459 intobjargproc func = (intobjargproc)wrapped;
3460 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003461 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003462
Guido van Rossum5d815f32001-08-17 21:57:47 +00003463 if (!PyArg_ParseTuple(args, "O", &arg))
3464 return NULL;
3465 i = getindex(self, arg);
3466 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003467 return NULL;
3468 res = (*func)(self, i, NULL);
3469 if (res == -1 && PyErr_Occurred())
3470 return NULL;
3471 Py_INCREF(Py_None);
3472 return Py_None;
3473}
3474
Tim Peters6d6c1a32001-08-02 04:15:00 +00003475static PyObject *
3476wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
3477{
3478 intintobjargproc func = (intintobjargproc)wrapped;
3479 int i, j, res;
3480 PyObject *value;
3481
3482 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
3483 return NULL;
3484 res = (*func)(self, i, j, value);
3485 if (res == -1 && PyErr_Occurred())
3486 return NULL;
3487 Py_INCREF(Py_None);
3488 return Py_None;
3489}
3490
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003491static PyObject *
3492wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
3493{
3494 intintobjargproc func = (intintobjargproc)wrapped;
3495 int i, j, res;
3496
3497 if (!PyArg_ParseTuple(args, "ii", &i, &j))
3498 return NULL;
3499 res = (*func)(self, i, j, NULL);
3500 if (res == -1 && PyErr_Occurred())
3501 return NULL;
3502 Py_INCREF(Py_None);
3503 return Py_None;
3504}
3505
Tim Peters6d6c1a32001-08-02 04:15:00 +00003506/* XXX objobjproc is a misnomer; should be objargpred */
3507static PyObject *
3508wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
3509{
3510 objobjproc func = (objobjproc)wrapped;
3511 int res;
3512 PyObject *value;
3513
3514 if (!PyArg_ParseTuple(args, "O", &value))
3515 return NULL;
3516 res = (*func)(self, value);
3517 if (res == -1 && PyErr_Occurred())
3518 return NULL;
3519 return PyInt_FromLong((long)res);
3520}
3521
Tim Peters6d6c1a32001-08-02 04:15:00 +00003522static PyObject *
3523wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
3524{
3525 objobjargproc func = (objobjargproc)wrapped;
3526 int res;
3527 PyObject *key, *value;
3528
3529 if (!PyArg_ParseTuple(args, "OO", &key, &value))
3530 return NULL;
3531 res = (*func)(self, key, value);
3532 if (res == -1 && PyErr_Occurred())
3533 return NULL;
3534 Py_INCREF(Py_None);
3535 return Py_None;
3536}
3537
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003538static PyObject *
3539wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
3540{
3541 objobjargproc func = (objobjargproc)wrapped;
3542 int res;
3543 PyObject *key;
3544
3545 if (!PyArg_ParseTuple(args, "O", &key))
3546 return NULL;
3547 res = (*func)(self, key, NULL);
3548 if (res == -1 && PyErr_Occurred())
3549 return NULL;
3550 Py_INCREF(Py_None);
3551 return Py_None;
3552}
3553
Tim Peters6d6c1a32001-08-02 04:15:00 +00003554static PyObject *
3555wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
3556{
3557 cmpfunc func = (cmpfunc)wrapped;
3558 int res;
3559 PyObject *other;
3560
3561 if (!PyArg_ParseTuple(args, "O", &other))
3562 return NULL;
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00003563 if (other->ob_type->tp_compare != func &&
3564 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00003565 PyErr_Format(
3566 PyExc_TypeError,
3567 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
3568 self->ob_type->tp_name,
3569 self->ob_type->tp_name,
3570 other->ob_type->tp_name);
3571 return NULL;
3572 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003573 res = (*func)(self, other);
3574 if (PyErr_Occurred())
3575 return NULL;
3576 return PyInt_FromLong((long)res);
3577}
3578
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003579/* Helper to check for object.__setattr__ or __delattr__ applied to a type.
Guido van Rossum52b27052003-04-15 20:05:10 +00003580 This is called the Carlo Verre hack after its discoverer. */
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003581static int
3582hackcheck(PyObject *self, setattrofunc func, char *what)
3583{
3584 PyTypeObject *type = self->ob_type;
3585 while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE)
3586 type = type->tp_base;
3587 if (type->tp_setattro != func) {
3588 PyErr_Format(PyExc_TypeError,
3589 "can't apply this %s to %s object",
3590 what,
3591 type->tp_name);
3592 return 0;
3593 }
3594 return 1;
3595}
3596
Tim Peters6d6c1a32001-08-02 04:15:00 +00003597static PyObject *
3598wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
3599{
3600 setattrofunc func = (setattrofunc)wrapped;
3601 int res;
3602 PyObject *name, *value;
3603
3604 if (!PyArg_ParseTuple(args, "OO", &name, &value))
3605 return NULL;
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003606 if (!hackcheck(self, func, "__setattr__"))
3607 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003608 res = (*func)(self, name, value);
3609 if (res < 0)
3610 return NULL;
3611 Py_INCREF(Py_None);
3612 return Py_None;
3613}
3614
3615static PyObject *
3616wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
3617{
3618 setattrofunc func = (setattrofunc)wrapped;
3619 int res;
3620 PyObject *name;
3621
3622 if (!PyArg_ParseTuple(args, "O", &name))
3623 return NULL;
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003624 if (!hackcheck(self, func, "__delattr__"))
3625 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003626 res = (*func)(self, name, NULL);
3627 if (res < 0)
3628 return NULL;
3629 Py_INCREF(Py_None);
3630 return Py_None;
3631}
3632
Tim Peters6d6c1a32001-08-02 04:15:00 +00003633static PyObject *
3634wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
3635{
3636 hashfunc func = (hashfunc)wrapped;
3637 long res;
3638
3639 if (!PyArg_ParseTuple(args, ""))
3640 return NULL;
3641 res = (*func)(self);
3642 if (res == -1 && PyErr_Occurred())
3643 return NULL;
3644 return PyInt_FromLong(res);
3645}
3646
Tim Peters6d6c1a32001-08-02 04:15:00 +00003647static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00003648wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003649{
3650 ternaryfunc func = (ternaryfunc)wrapped;
3651
Guido van Rossumc8e56452001-10-22 00:43:43 +00003652 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003653}
3654
Tim Peters6d6c1a32001-08-02 04:15:00 +00003655static PyObject *
3656wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
3657{
3658 richcmpfunc func = (richcmpfunc)wrapped;
3659 PyObject *other;
3660
3661 if (!PyArg_ParseTuple(args, "O", &other))
3662 return NULL;
3663 return (*func)(self, other, op);
3664}
3665
3666#undef RICHCMP_WRAPPER
3667#define RICHCMP_WRAPPER(NAME, OP) \
3668static PyObject * \
3669richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
3670{ \
3671 return wrap_richcmpfunc(self, args, wrapped, OP); \
3672}
3673
Jack Jansen8e938b42001-08-08 15:29:49 +00003674RICHCMP_WRAPPER(lt, Py_LT)
3675RICHCMP_WRAPPER(le, Py_LE)
3676RICHCMP_WRAPPER(eq, Py_EQ)
3677RICHCMP_WRAPPER(ne, Py_NE)
3678RICHCMP_WRAPPER(gt, Py_GT)
3679RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003680
Tim Peters6d6c1a32001-08-02 04:15:00 +00003681static PyObject *
3682wrap_next(PyObject *self, PyObject *args, void *wrapped)
3683{
3684 unaryfunc func = (unaryfunc)wrapped;
3685 PyObject *res;
3686
3687 if (!PyArg_ParseTuple(args, ""))
3688 return NULL;
3689 res = (*func)(self);
3690 if (res == NULL && !PyErr_Occurred())
3691 PyErr_SetNone(PyExc_StopIteration);
3692 return res;
3693}
3694
Tim Peters6d6c1a32001-08-02 04:15:00 +00003695static PyObject *
3696wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
3697{
3698 descrgetfunc func = (descrgetfunc)wrapped;
3699 PyObject *obj;
3700 PyObject *type = NULL;
3701
3702 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
3703 return NULL;
Guido van Rossum82ed25c2003-02-11 16:25:43 +00003704 if (obj == Py_None)
3705 obj = NULL;
3706 if (type == Py_None)
3707 type = NULL;
3708 if (type == NULL &&obj == NULL) {
3709 PyErr_SetString(PyExc_TypeError,
3710 "__get__(None, None) is invalid");
3711 return NULL;
3712 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003713 return (*func)(self, obj, type);
3714}
3715
Tim Peters6d6c1a32001-08-02 04:15:00 +00003716static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003717wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003718{
3719 descrsetfunc func = (descrsetfunc)wrapped;
3720 PyObject *obj, *value;
3721 int ret;
3722
3723 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
3724 return NULL;
3725 ret = (*func)(self, obj, value);
3726 if (ret < 0)
3727 return NULL;
3728 Py_INCREF(Py_None);
3729 return Py_None;
3730}
Guido van Rossum22b13872002-08-06 21:41:44 +00003731
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00003732static PyObject *
3733wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
3734{
3735 descrsetfunc func = (descrsetfunc)wrapped;
3736 PyObject *obj;
3737 int ret;
3738
3739 if (!PyArg_ParseTuple(args, "O", &obj))
3740 return NULL;
3741 ret = (*func)(self, obj, NULL);
3742 if (ret < 0)
3743 return NULL;
3744 Py_INCREF(Py_None);
3745 return Py_None;
3746}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003747
Tim Peters6d6c1a32001-08-02 04:15:00 +00003748static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00003749wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003750{
3751 initproc func = (initproc)wrapped;
3752
Guido van Rossumc8e56452001-10-22 00:43:43 +00003753 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003754 return NULL;
3755 Py_INCREF(Py_None);
3756 return Py_None;
3757}
3758
Tim Peters6d6c1a32001-08-02 04:15:00 +00003759static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003760tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003761{
Barry Warsaw60f01882001-08-22 19:24:42 +00003762 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003763 PyObject *arg0, *res;
3764
3765 if (self == NULL || !PyType_Check(self))
3766 Py_FatalError("__new__() called with non-type 'self'");
3767 type = (PyTypeObject *)self;
3768 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003769 PyErr_Format(PyExc_TypeError,
3770 "%s.__new__(): not enough arguments",
3771 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003772 return NULL;
3773 }
3774 arg0 = PyTuple_GET_ITEM(args, 0);
3775 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003776 PyErr_Format(PyExc_TypeError,
3777 "%s.__new__(X): X is not a type object (%s)",
3778 type->tp_name,
3779 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003780 return NULL;
3781 }
3782 subtype = (PyTypeObject *)arg0;
3783 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003784 PyErr_Format(PyExc_TypeError,
3785 "%s.__new__(%s): %s is not a subtype of %s",
3786 type->tp_name,
3787 subtype->tp_name,
3788 subtype->tp_name,
3789 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003790 return NULL;
3791 }
Barry Warsaw60f01882001-08-22 19:24:42 +00003792
3793 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00003794 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00003795 most derived base that's not a heap type is this type. */
3796 staticbase = subtype;
3797 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
3798 staticbase = staticbase->tp_base;
Guido van Rossuma8c60f42001-09-14 19:43:36 +00003799 if (staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003800 PyErr_Format(PyExc_TypeError,
3801 "%s.__new__(%s) is not safe, use %s.__new__()",
3802 type->tp_name,
3803 subtype->tp_name,
3804 staticbase == NULL ? "?" : staticbase->tp_name);
3805 return NULL;
3806 }
3807
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003808 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
3809 if (args == NULL)
3810 return NULL;
3811 res = type->tp_new(subtype, args, kwds);
3812 Py_DECREF(args);
3813 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003814}
3815
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003816static struct PyMethodDef tp_new_methoddef[] = {
3817 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00003818 PyDoc_STR("T.__new__(S, ...) -> "
3819 "a new object with type S, a subtype of T")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00003820 {0}
3821};
3822
3823static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003824add_tp_new_wrapper(PyTypeObject *type)
3825{
Guido van Rossumf040ede2001-08-07 16:40:56 +00003826 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003827
Guido van Rossum687ae002001-10-15 22:03:32 +00003828 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00003829 return 0;
3830 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003831 if (func == NULL)
3832 return -1;
Guido van Rossum687ae002001-10-15 22:03:32 +00003833 return PyDict_SetItemString(type->tp_dict, "__new__", func);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003834}
3835
Guido van Rossumf040ede2001-08-07 16:40:56 +00003836/* Slot wrappers that call the corresponding __foo__ slot. See comments
3837 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003838
Guido van Rossumdc91b992001-08-08 22:26:22 +00003839#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003840static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003841FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003842{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00003843 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003844 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003845}
3846
Guido van Rossumdc91b992001-08-08 22:26:22 +00003847#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003848static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003849FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003850{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003851 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003852 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003853}
3854
Guido van Rossumcd118802003-01-06 22:57:47 +00003855/* Boolean helper for SLOT1BINFULL().
3856 right.__class__ is a nontrivial subclass of left.__class__. */
3857static int
3858method_is_overloaded(PyObject *left, PyObject *right, char *name)
3859{
3860 PyObject *a, *b;
3861 int ok;
3862
3863 b = PyObject_GetAttrString((PyObject *)(right->ob_type), name);
3864 if (b == NULL) {
3865 PyErr_Clear();
3866 /* If right doesn't have it, it's not overloaded */
3867 return 0;
3868 }
3869
3870 a = PyObject_GetAttrString((PyObject *)(left->ob_type), name);
3871 if (a == NULL) {
3872 PyErr_Clear();
3873 Py_DECREF(b);
3874 /* If right has it but left doesn't, it's overloaded */
3875 return 1;
3876 }
3877
3878 ok = PyObject_RichCompareBool(a, b, Py_NE);
3879 Py_DECREF(a);
3880 Py_DECREF(b);
3881 if (ok < 0) {
3882 PyErr_Clear();
3883 return 0;
3884 }
3885
3886 return ok;
3887}
3888
Guido van Rossumdc91b992001-08-08 22:26:22 +00003889
3890#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003891static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003892FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003893{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003894 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00003895 int do_other = self->ob_type != other->ob_type && \
3896 other->ob_type->tp_as_number != NULL && \
3897 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003898 if (self->ob_type->tp_as_number != NULL && \
3899 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
3900 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00003901 if (do_other && \
Guido van Rossumcd118802003-01-06 22:57:47 +00003902 PyType_IsSubtype(other->ob_type, self->ob_type) && \
3903 method_is_overloaded(self, other, ROPSTR)) { \
Guido van Rossum55f20992001-10-01 17:18:22 +00003904 r = call_maybe( \
3905 other, ROPSTR, &rcache_str, "(O)", self); \
3906 if (r != Py_NotImplemented) \
3907 return r; \
3908 Py_DECREF(r); \
3909 do_other = 0; \
3910 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00003911 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00003912 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003913 if (r != Py_NotImplemented || \
3914 other->ob_type == self->ob_type) \
3915 return r; \
3916 Py_DECREF(r); \
3917 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00003918 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00003919 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00003920 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003921 } \
3922 Py_INCREF(Py_NotImplemented); \
3923 return Py_NotImplemented; \
3924}
3925
3926#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
3927 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
3928
3929#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
3930static PyObject * \
3931FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
3932{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003933 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003934 return call_method(self, OPSTR, &cache_str, \
3935 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003936}
3937
3938static int
3939slot_sq_length(PyObject *self)
3940{
Guido van Rossum2730b132001-08-28 18:22:14 +00003941 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00003942 PyObject *res = call_method(self, "__len__", &len_str, "()");
Guido van Rossum26111622001-10-01 16:42:49 +00003943 int len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003944
3945 if (res == NULL)
3946 return -1;
Guido van Rossum26111622001-10-01 16:42:49 +00003947 len = (int)PyInt_AsLong(res);
3948 Py_DECREF(res);
Jeremy Hylton73a088e2002-07-25 16:43:29 +00003949 if (len == -1 && PyErr_Occurred())
3950 return -1;
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00003951 if (len < 0) {
Guido van Rossum22b13872002-08-06 21:41:44 +00003952 PyErr_SetString(PyExc_ValueError,
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00003953 "__len__() should return >= 0");
3954 return -1;
3955 }
Guido van Rossum26111622001-10-01 16:42:49 +00003956 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003957}
3958
Guido van Rossumdc91b992001-08-08 22:26:22 +00003959SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
3960SLOT1(slot_sq_repeat, "__mul__", int, "i")
Guido van Rossumf4593e02001-10-03 12:09:30 +00003961
3962/* Super-optimized version of slot_sq_item.
3963 Other slots could do the same... */
3964static PyObject *
3965slot_sq_item(PyObject *self, int i)
3966{
3967 static PyObject *getitem_str;
3968 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
3969 descrgetfunc f;
3970
3971 if (getitem_str == NULL) {
3972 getitem_str = PyString_InternFromString("__getitem__");
3973 if (getitem_str == NULL)
3974 return NULL;
3975 }
3976 func = _PyType_Lookup(self->ob_type, getitem_str);
3977 if (func != NULL) {
Guido van Rossumf4593e02001-10-03 12:09:30 +00003978 if ((f = func->ob_type->tp_descr_get) == NULL)
3979 Py_INCREF(func);
Neal Norwitz673cd822002-10-18 16:33:13 +00003980 else {
Guido van Rossumf4593e02001-10-03 12:09:30 +00003981 func = f(func, self, (PyObject *)(self->ob_type));
Neal Norwitz673cd822002-10-18 16:33:13 +00003982 if (func == NULL) {
3983 return NULL;
3984 }
3985 }
Guido van Rossumf4593e02001-10-03 12:09:30 +00003986 ival = PyInt_FromLong(i);
3987 if (ival != NULL) {
3988 args = PyTuple_New(1);
3989 if (args != NULL) {
3990 PyTuple_SET_ITEM(args, 0, ival);
3991 retval = PyObject_Call(func, args, NULL);
3992 Py_XDECREF(args);
3993 Py_XDECREF(func);
3994 return retval;
3995 }
3996 }
3997 }
3998 else {
3999 PyErr_SetObject(PyExc_AttributeError, getitem_str);
4000 }
4001 Py_XDECREF(args);
4002 Py_XDECREF(ival);
4003 Py_XDECREF(func);
4004 return NULL;
4005}
4006
Guido van Rossumdc91b992001-08-08 22:26:22 +00004007SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004008
4009static int
4010slot_sq_ass_item(PyObject *self, int index, PyObject *value)
4011{
4012 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004013 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004014
4015 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004016 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004017 "(i)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004018 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004019 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004020 "(iO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004021 if (res == NULL)
4022 return -1;
4023 Py_DECREF(res);
4024 return 0;
4025}
4026
4027static int
4028slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
4029{
4030 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004031 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004032
4033 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004034 res = call_method(self, "__delslice__", &delslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004035 "(ii)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004036 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004037 res = call_method(self, "__setslice__", &setslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004038 "(iiO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004039 if (res == NULL)
4040 return -1;
4041 Py_DECREF(res);
4042 return 0;
4043}
4044
4045static int
4046slot_sq_contains(PyObject *self, PyObject *value)
4047{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004048 PyObject *func, *res, *args;
Tim Petersbf9b2442003-03-23 05:35:36 +00004049 int result = -1;
4050
Guido van Rossum60718732001-08-28 17:47:51 +00004051 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004052
Guido van Rossum55f20992001-10-01 17:18:22 +00004053 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004054 if (func != NULL) {
4055 args = Py_BuildValue("(O)", value);
4056 if (args == NULL)
4057 res = NULL;
4058 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004059 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004060 Py_DECREF(args);
4061 }
4062 Py_DECREF(func);
Tim Petersbf9b2442003-03-23 05:35:36 +00004063 if (res != NULL) {
4064 result = PyObject_IsTrue(res);
4065 Py_DECREF(res);
4066 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004067 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004068 else if (! PyErr_Occurred()) {
4069 result = _PySequence_IterSearch(self, value,
4070 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004071 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004072 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004073}
4074
Guido van Rossumdc91b992001-08-08 22:26:22 +00004075SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
4076SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004077
4078#define slot_mp_length slot_sq_length
4079
Guido van Rossumdc91b992001-08-08 22:26:22 +00004080SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004081
4082static int
4083slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
4084{
4085 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004086 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004087
4088 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004089 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004090 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004091 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004092 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004093 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004094 if (res == NULL)
4095 return -1;
4096 Py_DECREF(res);
4097 return 0;
4098}
4099
Guido van Rossumdc91b992001-08-08 22:26:22 +00004100SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
4101SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
4102SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
4103SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
4104SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
4105SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
4106
Jeremy Hylton938ace62002-07-17 16:30:39 +00004107static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00004108
4109SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
4110 nb_power, "__pow__", "__rpow__")
4111
4112static PyObject *
4113slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
4114{
Guido van Rossum2730b132001-08-28 18:22:14 +00004115 static PyObject *pow_str;
4116
Guido van Rossumdc91b992001-08-08 22:26:22 +00004117 if (modulus == Py_None)
4118 return slot_nb_power_binary(self, other);
Guido van Rossum23094982002-06-10 14:30:43 +00004119 /* Three-arg power doesn't use __rpow__. But ternary_op
4120 can call this when the second argument's type uses
4121 slot_nb_power, so check before calling self.__pow__. */
4122 if (self->ob_type->tp_as_number != NULL &&
4123 self->ob_type->tp_as_number->nb_power == slot_nb_power) {
4124 return call_method(self, "__pow__", &pow_str,
4125 "(OO)", other, modulus);
4126 }
4127 Py_INCREF(Py_NotImplemented);
4128 return Py_NotImplemented;
Guido van Rossumdc91b992001-08-08 22:26:22 +00004129}
4130
4131SLOT0(slot_nb_negative, "__neg__")
4132SLOT0(slot_nb_positive, "__pos__")
4133SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004134
4135static int
4136slot_nb_nonzero(PyObject *self)
4137{
Tim Petersea7f75d2002-12-07 21:39:16 +00004138 PyObject *func, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00004139 static PyObject *nonzero_str, *len_str;
Tim Petersea7f75d2002-12-07 21:39:16 +00004140 int result = -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004141
Guido van Rossum55f20992001-10-01 17:18:22 +00004142 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004143 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00004144 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00004145 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00004146 func = lookup_maybe(self, "__len__", &len_str);
Tim Petersea7f75d2002-12-07 21:39:16 +00004147 if (func == NULL)
4148 return PyErr_Occurred() ? -1 : 1;
4149 }
4150 args = PyTuple_New(0);
4151 if (args != NULL) {
4152 PyObject *temp = PyObject_Call(func, args, NULL);
4153 Py_DECREF(args);
4154 if (temp != NULL) {
4155 result = PyObject_IsTrue(temp);
4156 Py_DECREF(temp);
Guido van Rossum55f20992001-10-01 17:18:22 +00004157 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004158 }
Guido van Rossum55f20992001-10-01 17:18:22 +00004159 Py_DECREF(func);
Tim Petersea7f75d2002-12-07 21:39:16 +00004160 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004161}
4162
Guido van Rossumdc91b992001-08-08 22:26:22 +00004163SLOT0(slot_nb_invert, "__invert__")
4164SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
4165SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
4166SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
4167SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
4168SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004169
4170static int
4171slot_nb_coerce(PyObject **a, PyObject **b)
4172{
4173 static PyObject *coerce_str;
4174 PyObject *self = *a, *other = *b;
4175
4176 if (self->ob_type->tp_as_number != NULL &&
4177 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
4178 PyObject *r;
4179 r = call_maybe(
4180 self, "__coerce__", &coerce_str, "(O)", other);
4181 if (r == NULL)
4182 return -1;
4183 if (r == Py_NotImplemented) {
4184 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004185 }
Guido van Rossum55f20992001-10-01 17:18:22 +00004186 else {
4187 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
4188 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004189 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00004190 Py_DECREF(r);
4191 return -1;
4192 }
4193 *a = PyTuple_GET_ITEM(r, 0);
4194 Py_INCREF(*a);
4195 *b = PyTuple_GET_ITEM(r, 1);
4196 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004197 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00004198 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004199 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004200 }
4201 if (other->ob_type->tp_as_number != NULL &&
4202 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
4203 PyObject *r;
4204 r = call_maybe(
4205 other, "__coerce__", &coerce_str, "(O)", self);
4206 if (r == NULL)
4207 return -1;
4208 if (r == Py_NotImplemented) {
4209 Py_DECREF(r);
4210 return 1;
4211 }
4212 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
4213 PyErr_SetString(PyExc_TypeError,
4214 "__coerce__ didn't return a 2-tuple");
4215 Py_DECREF(r);
4216 return -1;
4217 }
4218 *a = PyTuple_GET_ITEM(r, 1);
4219 Py_INCREF(*a);
4220 *b = PyTuple_GET_ITEM(r, 0);
4221 Py_INCREF(*b);
4222 Py_DECREF(r);
4223 return 0;
4224 }
4225 return 1;
4226}
4227
Guido van Rossumdc91b992001-08-08 22:26:22 +00004228SLOT0(slot_nb_int, "__int__")
4229SLOT0(slot_nb_long, "__long__")
4230SLOT0(slot_nb_float, "__float__")
4231SLOT0(slot_nb_oct, "__oct__")
4232SLOT0(slot_nb_hex, "__hex__")
4233SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
4234SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
4235SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
4236SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
4237SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Guido van Rossum6e5680f2002-10-15 01:01:53 +00004238SLOT1(slot_nb_inplace_power, "__ipow__", PyObject *, "O")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004239SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
4240SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
4241SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
4242SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
4243SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
4244SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
4245 "__floordiv__", "__rfloordiv__")
4246SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
4247SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
4248SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004249
4250static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00004251half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004252{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004253 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004254 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004255 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004256
Guido van Rossum60718732001-08-28 17:47:51 +00004257 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004258 if (func == NULL) {
4259 PyErr_Clear();
4260 }
4261 else {
4262 args = Py_BuildValue("(O)", other);
4263 if (args == NULL)
4264 res = NULL;
4265 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004266 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004267 Py_DECREF(args);
4268 }
Raymond Hettingerab5dae32002-06-24 13:08:16 +00004269 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004270 if (res != Py_NotImplemented) {
4271 if (res == NULL)
4272 return -2;
4273 c = PyInt_AsLong(res);
4274 Py_DECREF(res);
4275 if (c == -1 && PyErr_Occurred())
4276 return -2;
4277 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
4278 }
4279 Py_DECREF(res);
4280 }
4281 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004282}
4283
Guido van Rossumab3b0342001-09-18 20:38:53 +00004284/* This slot is published for the benefit of try_3way_compare in object.c */
4285int
4286_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00004287{
4288 int c;
4289
Guido van Rossumab3b0342001-09-18 20:38:53 +00004290 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004291 c = half_compare(self, other);
4292 if (c <= 1)
4293 return c;
4294 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00004295 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004296 c = half_compare(other, self);
4297 if (c < -1)
4298 return -2;
4299 if (c <= 1)
4300 return -c;
4301 }
4302 return (void *)self < (void *)other ? -1 :
4303 (void *)self > (void *)other ? 1 : 0;
4304}
4305
4306static PyObject *
4307slot_tp_repr(PyObject *self)
4308{
4309 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004310 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004311
Guido van Rossum60718732001-08-28 17:47:51 +00004312 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004313 if (func != NULL) {
4314 res = PyEval_CallObject(func, NULL);
4315 Py_DECREF(func);
4316 return res;
4317 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00004318 PyErr_Clear();
4319 return PyString_FromFormat("<%s object at %p>",
4320 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004321}
4322
4323static PyObject *
4324slot_tp_str(PyObject *self)
4325{
4326 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004327 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004328
Guido van Rossum60718732001-08-28 17:47:51 +00004329 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004330 if (func != NULL) {
4331 res = PyEval_CallObject(func, NULL);
4332 Py_DECREF(func);
4333 return res;
4334 }
4335 else {
4336 PyErr_Clear();
4337 return slot_tp_repr(self);
4338 }
4339}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004340
4341static long
4342slot_tp_hash(PyObject *self)
4343{
Tim Peters61ce0a92002-12-06 23:38:02 +00004344 PyObject *func;
Guido van Rossum60718732001-08-28 17:47:51 +00004345 static PyObject *hash_str, *eq_str, *cmp_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004346 long h;
4347
Guido van Rossum60718732001-08-28 17:47:51 +00004348 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004349
4350 if (func != NULL) {
Tim Peters61ce0a92002-12-06 23:38:02 +00004351 PyObject *res = PyEval_CallObject(func, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004352 Py_DECREF(func);
4353 if (res == NULL)
4354 return -1;
4355 h = PyInt_AsLong(res);
Tim Peters61ce0a92002-12-06 23:38:02 +00004356 Py_DECREF(res);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004357 }
4358 else {
4359 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004360 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004361 if (func == NULL) {
4362 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004363 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004364 }
4365 if (func != NULL) {
4366 Py_DECREF(func);
4367 PyErr_SetString(PyExc_TypeError, "unhashable type");
4368 return -1;
4369 }
4370 PyErr_Clear();
4371 h = _Py_HashPointer((void *)self);
4372 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004373 if (h == -1 && !PyErr_Occurred())
4374 h = -2;
4375 return h;
4376}
4377
4378static PyObject *
4379slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
4380{
Guido van Rossum60718732001-08-28 17:47:51 +00004381 static PyObject *call_str;
4382 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004383 PyObject *res;
4384
4385 if (meth == NULL)
4386 return NULL;
4387 res = PyObject_Call(meth, args, kwds);
4388 Py_DECREF(meth);
4389 return res;
4390}
4391
Guido van Rossum14a6f832001-10-17 13:59:09 +00004392/* There are two slot dispatch functions for tp_getattro.
4393
4394 - slot_tp_getattro() is used when __getattribute__ is overridden
4395 but no __getattr__ hook is present;
4396
4397 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
4398
Guido van Rossumc334df52002-04-04 23:44:47 +00004399 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
4400 detects the absence of __getattr__ and then installs the simpler slot if
4401 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00004402
Tim Peters6d6c1a32001-08-02 04:15:00 +00004403static PyObject *
4404slot_tp_getattro(PyObject *self, PyObject *name)
4405{
Guido van Rossum14a6f832001-10-17 13:59:09 +00004406 static PyObject *getattribute_str = NULL;
4407 return call_method(self, "__getattribute__", &getattribute_str,
4408 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004409}
4410
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004411static PyObject *
4412slot_tp_getattr_hook(PyObject *self, PyObject *name)
4413{
4414 PyTypeObject *tp = self->ob_type;
4415 PyObject *getattr, *getattribute, *res;
4416 static PyObject *getattribute_str = NULL;
4417 static PyObject *getattr_str = NULL;
4418
4419 if (getattr_str == NULL) {
4420 getattr_str = PyString_InternFromString("__getattr__");
4421 if (getattr_str == NULL)
4422 return NULL;
4423 }
4424 if (getattribute_str == NULL) {
4425 getattribute_str =
4426 PyString_InternFromString("__getattribute__");
4427 if (getattribute_str == NULL)
4428 return NULL;
4429 }
4430 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004431 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004432 /* No __getattr__ hook: use a simpler dispatcher */
4433 tp->tp_getattro = slot_tp_getattro;
4434 return slot_tp_getattro(self, name);
4435 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004436 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004437 if (getattribute == NULL ||
4438 (getattribute->ob_type == &PyWrapperDescr_Type &&
4439 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
4440 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004441 res = PyObject_GenericGetAttr(self, name);
4442 else
4443 res = PyObject_CallFunction(getattribute, "OO", self, name);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004444 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004445 PyErr_Clear();
4446 res = PyObject_CallFunction(getattr, "OO", self, name);
4447 }
4448 return res;
4449}
4450
Tim Peters6d6c1a32001-08-02 04:15:00 +00004451static int
4452slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
4453{
4454 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004455 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004456
4457 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004458 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004459 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004460 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004461 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004462 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004463 if (res == NULL)
4464 return -1;
4465 Py_DECREF(res);
4466 return 0;
4467}
4468
4469/* Map rich comparison operators to their __xx__ namesakes */
4470static char *name_op[] = {
4471 "__lt__",
4472 "__le__",
4473 "__eq__",
4474 "__ne__",
4475 "__gt__",
4476 "__ge__",
4477};
4478
4479static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00004480half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004481{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004482 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004483 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00004484
Guido van Rossum60718732001-08-28 17:47:51 +00004485 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004486 if (func == NULL) {
4487 PyErr_Clear();
4488 Py_INCREF(Py_NotImplemented);
4489 return Py_NotImplemented;
4490 }
4491 args = Py_BuildValue("(O)", other);
4492 if (args == NULL)
4493 res = NULL;
4494 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004495 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004496 Py_DECREF(args);
4497 }
4498 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004499 return res;
4500}
4501
Guido van Rossumb8f63662001-08-15 23:57:02 +00004502/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
4503static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
4504
4505static PyObject *
4506slot_tp_richcompare(PyObject *self, PyObject *other, int op)
4507{
4508 PyObject *res;
4509
4510 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
4511 res = half_richcompare(self, other, op);
4512 if (res != Py_NotImplemented)
4513 return res;
4514 Py_DECREF(res);
4515 }
4516 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
4517 res = half_richcompare(other, self, swapped_op[op]);
4518 if (res != Py_NotImplemented) {
4519 return res;
4520 }
4521 Py_DECREF(res);
4522 }
4523 Py_INCREF(Py_NotImplemented);
4524 return Py_NotImplemented;
4525}
4526
4527static PyObject *
4528slot_tp_iter(PyObject *self)
4529{
4530 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004531 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004532
Guido van Rossum60718732001-08-28 17:47:51 +00004533 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004534 if (func != NULL) {
Guido van Rossum84b2bed2002-08-16 17:01:09 +00004535 PyObject *args;
4536 args = res = PyTuple_New(0);
4537 if (args != NULL) {
4538 res = PyObject_Call(func, args, NULL);
4539 Py_DECREF(args);
4540 }
4541 Py_DECREF(func);
4542 return res;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004543 }
4544 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004545 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004546 if (func == NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00004547 PyErr_SetString(PyExc_TypeError,
4548 "iteration over non-sequence");
Guido van Rossumb8f63662001-08-15 23:57:02 +00004549 return NULL;
4550 }
4551 Py_DECREF(func);
4552 return PySeqIter_New(self);
4553}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004554
4555static PyObject *
4556slot_tp_iternext(PyObject *self)
4557{
Guido van Rossum2730b132001-08-28 18:22:14 +00004558 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00004559 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004560}
4561
Guido van Rossum1a493502001-08-17 16:47:50 +00004562static PyObject *
4563slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4564{
4565 PyTypeObject *tp = self->ob_type;
4566 PyObject *get;
4567 static PyObject *get_str = NULL;
4568
4569 if (get_str == NULL) {
4570 get_str = PyString_InternFromString("__get__");
4571 if (get_str == NULL)
4572 return NULL;
4573 }
4574 get = _PyType_Lookup(tp, get_str);
4575 if (get == NULL) {
4576 /* Avoid further slowdowns */
4577 if (tp->tp_descr_get == slot_tp_descr_get)
4578 tp->tp_descr_get = NULL;
4579 Py_INCREF(self);
4580 return self;
4581 }
Guido van Rossum2c252392001-08-24 10:13:31 +00004582 if (obj == NULL)
4583 obj = Py_None;
4584 if (type == NULL)
4585 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00004586 return PyObject_CallFunction(get, "OOO", self, obj, type);
4587}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004588
4589static int
4590slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
4591{
Guido van Rossum2c252392001-08-24 10:13:31 +00004592 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004593 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00004594
4595 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00004596 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004597 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00004598 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004599 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004600 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004601 if (res == NULL)
4602 return -1;
4603 Py_DECREF(res);
4604 return 0;
4605}
4606
4607static int
4608slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
4609{
Guido van Rossum60718732001-08-28 17:47:51 +00004610 static PyObject *init_str;
4611 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004612 PyObject *res;
4613
4614 if (meth == NULL)
4615 return -1;
4616 res = PyObject_Call(meth, args, kwds);
4617 Py_DECREF(meth);
4618 if (res == NULL)
4619 return -1;
4620 Py_DECREF(res);
4621 return 0;
4622}
4623
4624static PyObject *
4625slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4626{
Guido van Rossum7bed2132002-08-08 21:57:53 +00004627 static PyObject *new_str;
4628 PyObject *func;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004629 PyObject *newargs, *x;
4630 int i, n;
4631
Guido van Rossum7bed2132002-08-08 21:57:53 +00004632 if (new_str == NULL) {
4633 new_str = PyString_InternFromString("__new__");
4634 if (new_str == NULL)
4635 return NULL;
4636 }
4637 func = PyObject_GetAttr((PyObject *)type, new_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004638 if (func == NULL)
4639 return NULL;
4640 assert(PyTuple_Check(args));
4641 n = PyTuple_GET_SIZE(args);
4642 newargs = PyTuple_New(n+1);
4643 if (newargs == NULL)
4644 return NULL;
4645 Py_INCREF(type);
4646 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
4647 for (i = 0; i < n; i++) {
4648 x = PyTuple_GET_ITEM(args, i);
4649 Py_INCREF(x);
4650 PyTuple_SET_ITEM(newargs, i+1, x);
4651 }
4652 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00004653 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004654 Py_DECREF(func);
4655 return x;
4656}
4657
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004658static void
4659slot_tp_del(PyObject *self)
4660{
4661 static PyObject *del_str = NULL;
4662 PyObject *del, *res;
4663 PyObject *error_type, *error_value, *error_traceback;
4664
4665 /* Temporarily resurrect the object. */
4666 assert(self->ob_refcnt == 0);
4667 self->ob_refcnt = 1;
4668
4669 /* Save the current exception, if any. */
4670 PyErr_Fetch(&error_type, &error_value, &error_traceback);
4671
4672 /* Execute __del__ method, if any. */
4673 del = lookup_maybe(self, "__del__", &del_str);
4674 if (del != NULL) {
4675 res = PyEval_CallObject(del, NULL);
4676 if (res == NULL)
4677 PyErr_WriteUnraisable(del);
4678 else
4679 Py_DECREF(res);
4680 Py_DECREF(del);
4681 }
4682
4683 /* Restore the saved exception. */
4684 PyErr_Restore(error_type, error_value, error_traceback);
4685
4686 /* Undo the temporary resurrection; can't use DECREF here, it would
4687 * cause a recursive call.
4688 */
4689 assert(self->ob_refcnt > 0);
4690 if (--self->ob_refcnt == 0)
4691 return; /* this is the normal path out */
4692
4693 /* __del__ resurrected it! Make it look like the original Py_DECREF
4694 * never happened.
4695 */
4696 {
4697 int refcnt = self->ob_refcnt;
4698 _Py_NewReference(self);
4699 self->ob_refcnt = refcnt;
4700 }
4701 assert(!PyType_IS_GC(self->ob_type) ||
4702 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
4703 /* If Py_REF_DEBUG, the original decref dropped _Py_RefTotal, but
4704 * _Py_NewReference bumped it again, so that's a wash.
4705 * If Py_TRACE_REFS, _Py_NewReference re-added self to the object
4706 * chain, so no more to do there either.
4707 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
4708 * _Py_NewReference bumped tp_allocs: both of those need to be
4709 * undone.
4710 */
4711#ifdef COUNT_ALLOCS
4712 --self->ob_type->tp_frees;
4713 --self->ob_type->tp_allocs;
4714#endif
4715}
4716
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004717
4718/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
Tim Petersbf9b2442003-03-23 05:35:36 +00004719 functions. The offsets here are relative to the 'PyHeapTypeObject'
Guido van Rossume5c691a2003-03-07 15:13:17 +00004720 structure, which incorporates the additional structures used for numbers,
4721 sequences and mappings.
4722 Note that multiple names may map to the same slot (e.g. __eq__,
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004723 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00004724 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
4725 terminated with an all-zero entry. (This table is further initialized and
4726 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004727
Guido van Rossum6d204072001-10-21 00:44:31 +00004728typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004729
4730#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00004731#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004732#undef ETSLOT
4733#undef SQSLOT
4734#undef MPSLOT
4735#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00004736#undef UNSLOT
4737#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004738#undef BINSLOT
4739#undef RBINSLOT
4740
Guido van Rossum6d204072001-10-21 00:44:31 +00004741#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004742 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
4743 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00004744#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
4745 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004746 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00004747#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Guido van Rossume5c691a2003-03-07 15:13:17 +00004748 {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004749 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00004750#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4751 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
4752#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4753 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
4754#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4755 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
4756#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4757 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
4758 "x." NAME "() <==> " DOC)
4759#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4760 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
4761 "x." NAME "(y) <==> x" DOC "y")
4762#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
4763 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
4764 "x." NAME "(y) <==> x" DOC "y")
4765#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
4766 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
4767 "x." NAME "(y) <==> y" DOC "x")
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004768
4769static slotdef slotdefs[] = {
Guido van Rossum6d204072001-10-21 00:44:31 +00004770 SQSLOT("__len__", sq_length, slot_sq_length, wrap_inquiry,
4771 "x.__len__() <==> len(x)"),
4772 SQSLOT("__add__", sq_concat, slot_sq_concat, wrap_binaryfunc,
4773 "x.__add__(y) <==> x+y"),
4774 SQSLOT("__mul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
4775 "x.__mul__(n) <==> x*n"),
4776 SQSLOT("__rmul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
4777 "x.__rmul__(n) <==> n*x"),
4778 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
4779 "x.__getitem__(y) <==> x[y]"),
4780 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_intintargfunc,
4781 "x.__getslice__(i, j) <==> x[i:j]"),
4782 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
4783 "x.__setitem__(i, y) <==> x[i]=y"),
4784 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
4785 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004786 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Guido van Rossum6d204072001-10-21 00:44:31 +00004787 wrap_intintobjargproc,
4788 "x.__setslice__(i, j, y) <==> x[i:j]=y"),
4789 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
4790 "x.__delslice__(i, j) <==> del x[i:j]"),
4791 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
4792 "x.__contains__(y) <==> y in x"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004793 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat,
Guido van Rossum6d204072001-10-21 00:44:31 +00004794 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004795 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat,
Guido van Rossum6d204072001-10-21 00:44:31 +00004796 wrap_intargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004797
Guido van Rossum6d204072001-10-21 00:44:31 +00004798 MPSLOT("__len__", mp_length, slot_mp_length, wrap_inquiry,
4799 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00004800 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004801 wrap_binaryfunc,
4802 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004803 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004804 wrap_objobjargproc,
4805 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004806 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004807 wrap_delitem,
4808 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004809
Guido van Rossum6d204072001-10-21 00:44:31 +00004810 BINSLOT("__add__", nb_add, slot_nb_add,
4811 "+"),
4812 RBINSLOT("__radd__", nb_add, slot_nb_add,
4813 "+"),
4814 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
4815 "-"),
4816 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
4817 "-"),
4818 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
4819 "*"),
4820 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
4821 "*"),
4822 BINSLOT("__div__", nb_divide, slot_nb_divide,
4823 "/"),
4824 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
4825 "/"),
4826 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
4827 "%"),
4828 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
4829 "%"),
4830 BINSLOT("__divmod__", nb_divmod, slot_nb_divmod,
4831 "divmod(x, y)"),
4832 RBINSLOT("__rdivmod__", nb_divmod, slot_nb_divmod,
4833 "divmod(y, x)"),
4834 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
4835 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
4836 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
4837 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
4838 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
4839 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
4840 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
4841 "abs(x)"),
Guido van Rossumdfce3bf2002-03-10 14:11:16 +00004842 UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquiry,
Guido van Rossum6d204072001-10-21 00:44:31 +00004843 "x != 0"),
4844 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
4845 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
4846 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
4847 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
4848 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
4849 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
4850 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
4851 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
4852 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
4853 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
4854 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
4855 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
4856 "x.__coerce__(y) <==> coerce(x, y)"),
4857 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
4858 "int(x)"),
4859 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
4860 "long(x)"),
4861 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
4862 "float(x)"),
4863 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
4864 "oct(x)"),
4865 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
4866 "hex(x)"),
4867 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
4868 wrap_binaryfunc, "+"),
4869 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
4870 wrap_binaryfunc, "-"),
4871 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
4872 wrap_binaryfunc, "*"),
4873 IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
4874 wrap_binaryfunc, "/"),
4875 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
4876 wrap_binaryfunc, "%"),
4877 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
Guido van Rossum6e5680f2002-10-15 01:01:53 +00004878 wrap_binaryfunc, "**"),
Guido van Rossum6d204072001-10-21 00:44:31 +00004879 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
4880 wrap_binaryfunc, "<<"),
4881 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
4882 wrap_binaryfunc, ">>"),
4883 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
4884 wrap_binaryfunc, "&"),
4885 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
4886 wrap_binaryfunc, "^"),
4887 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
4888 wrap_binaryfunc, "|"),
4889 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
4890 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
4891 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
4892 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
4893 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
4894 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
4895 IBSLOT("__itruediv__", nb_inplace_true_divide,
4896 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004897
Guido van Rossum6d204072001-10-21 00:44:31 +00004898 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
4899 "x.__str__() <==> str(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00004900 TPSLOT("__str__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00004901 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
4902 "x.__repr__() <==> repr(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00004903 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00004904 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
4905 "x.__cmp__(y) <==> cmp(x,y)"),
4906 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
4907 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00004908 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
4909 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004910 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00004911 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
4912 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
4913 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
4914 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
4915 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
4916 "x.__setattr__('name', value) <==> x.name = value"),
4917 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
4918 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
4919 "x.__delattr__('name') <==> del x.name"),
4920 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
4921 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
4922 "x.__lt__(y) <==> x<y"),
4923 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
4924 "x.__le__(y) <==> x<=y"),
4925 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
4926 "x.__eq__(y) <==> x==y"),
4927 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
4928 "x.__ne__(y) <==> x!=y"),
4929 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
4930 "x.__gt__(y) <==> x>y"),
4931 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
4932 "x.__ge__(y) <==> x>=y"),
4933 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
4934 "x.__iter__() <==> iter(x)"),
4935 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
4936 "x.next() -> the next value, or raise StopIteration"),
4937 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
4938 "descr.__get__(obj[, type]) -> value"),
4939 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
4940 "descr.__set__(obj, value)"),
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004941 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
4942 wrap_descr_delete, "descr.__delete__(obj)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00004943 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00004944 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00004945 "see x.__class__.__doc__ for signature",
4946 PyWrapperFlag_KEYWORDS),
4947 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004948 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004949 {NULL}
4950};
4951
Guido van Rossumc334df52002-04-04 23:44:47 +00004952/* Given a type pointer and an offset gotten from a slotdef entry, return a
4953 pointer to the actual slot. This is not quite the same as simply adding
4954 the offset to the type pointer, since it takes care to indirect through the
4955 proper indirection pointer (as_buffer, etc.); it returns NULL if the
4956 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004957static void **
4958slotptr(PyTypeObject *type, int offset)
4959{
4960 char *ptr;
4961
Guido van Rossume5c691a2003-03-07 15:13:17 +00004962 /* Note: this depends on the order of the members of PyHeapTypeObject! */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004963 assert(offset >= 0);
Guido van Rossume5c691a2003-03-07 15:13:17 +00004964 assert(offset < offsetof(PyHeapTypeObject, as_buffer));
4965 if (offset >= offsetof(PyHeapTypeObject, as_sequence)) {
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004966 ptr = (void *)type->tp_as_sequence;
Guido van Rossume5c691a2003-03-07 15:13:17 +00004967 offset -= offsetof(PyHeapTypeObject, as_sequence);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004968 }
Guido van Rossume5c691a2003-03-07 15:13:17 +00004969 else if (offset >= offsetof(PyHeapTypeObject, as_mapping)) {
Guido van Rossum09638c12002-06-13 19:17:46 +00004970 ptr = (void *)type->tp_as_mapping;
Guido van Rossume5c691a2003-03-07 15:13:17 +00004971 offset -= offsetof(PyHeapTypeObject, as_mapping);
Guido van Rossum09638c12002-06-13 19:17:46 +00004972 }
Guido van Rossume5c691a2003-03-07 15:13:17 +00004973 else if (offset >= offsetof(PyHeapTypeObject, as_number)) {
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004974 ptr = (void *)type->tp_as_number;
Guido van Rossume5c691a2003-03-07 15:13:17 +00004975 offset -= offsetof(PyHeapTypeObject, as_number);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004976 }
4977 else {
4978 ptr = (void *)type;
4979 }
4980 if (ptr != NULL)
4981 ptr += offset;
4982 return (void **)ptr;
4983}
Guido van Rossumf040ede2001-08-07 16:40:56 +00004984
Guido van Rossumc334df52002-04-04 23:44:47 +00004985/* Length of array of slotdef pointers used to store slots with the
4986 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
4987 the same __name__, for any __name__. Since that's a static property, it is
4988 appropriate to declare fixed-size arrays for this. */
4989#define MAX_EQUIV 10
4990
4991/* Return a slot pointer for a given name, but ONLY if the attribute has
4992 exactly one slot function. The name must be an interned string. */
4993static void **
4994resolve_slotdups(PyTypeObject *type, PyObject *name)
4995{
4996 /* XXX Maybe this could be optimized more -- but is it worth it? */
4997
4998 /* pname and ptrs act as a little cache */
4999 static PyObject *pname;
5000 static slotdef *ptrs[MAX_EQUIV];
5001 slotdef *p, **pp;
5002 void **res, **ptr;
5003
5004 if (pname != name) {
5005 /* Collect all slotdefs that match name into ptrs. */
5006 pname = name;
5007 pp = ptrs;
5008 for (p = slotdefs; p->name_strobj; p++) {
5009 if (p->name_strobj == name)
5010 *pp++ = p;
5011 }
5012 *pp = NULL;
5013 }
5014
5015 /* Look in all matching slots of the type; if exactly one of these has
5016 a filled-in slot, return its value. Otherwise return NULL. */
5017 res = NULL;
5018 for (pp = ptrs; *pp; pp++) {
5019 ptr = slotptr(type, (*pp)->offset);
5020 if (ptr == NULL || *ptr == NULL)
5021 continue;
5022 if (res != NULL)
5023 return NULL;
5024 res = ptr;
5025 }
5026 return res;
5027}
5028
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005029/* Common code for update_slots_callback() and fixup_slot_dispatchers(). This
Guido van Rossumc334df52002-04-04 23:44:47 +00005030 does some incredibly complex thinking and then sticks something into the
5031 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
5032 interests, and then stores a generic wrapper or a specific function into
5033 the slot.) Return a pointer to the next slotdef with a different offset,
5034 because that's convenient for fixup_slot_dispatchers(). */
5035static slotdef *
5036update_one_slot(PyTypeObject *type, slotdef *p)
5037{
5038 PyObject *descr;
5039 PyWrapperDescrObject *d;
5040 void *generic = NULL, *specific = NULL;
5041 int use_generic = 0;
5042 int offset = p->offset;
5043 void **ptr = slotptr(type, offset);
5044
5045 if (ptr == NULL) {
5046 do {
5047 ++p;
5048 } while (p->offset == offset);
5049 return p;
5050 }
5051 do {
5052 descr = _PyType_Lookup(type, p->name_strobj);
5053 if (descr == NULL)
5054 continue;
5055 if (descr->ob_type == &PyWrapperDescr_Type) {
5056 void **tptr = resolve_slotdups(type, p->name_strobj);
5057 if (tptr == NULL || tptr == ptr)
5058 generic = p->function;
5059 d = (PyWrapperDescrObject *)descr;
5060 if (d->d_base->wrapper == p->wrapper &&
5061 PyType_IsSubtype(type, d->d_type))
5062 {
5063 if (specific == NULL ||
5064 specific == d->d_wrapped)
5065 specific = d->d_wrapped;
5066 else
5067 use_generic = 1;
5068 }
5069 }
Guido van Rossum721f62e2002-08-09 02:14:34 +00005070 else if (descr->ob_type == &PyCFunction_Type &&
5071 PyCFunction_GET_FUNCTION(descr) ==
5072 (PyCFunction)tp_new_wrapper &&
5073 strcmp(p->name, "__new__") == 0)
5074 {
5075 /* The __new__ wrapper is not a wrapper descriptor,
5076 so must be special-cased differently.
5077 If we don't do this, creating an instance will
5078 always use slot_tp_new which will look up
5079 __new__ in the MRO which will call tp_new_wrapper
5080 which will look through the base classes looking
5081 for a static base and call its tp_new (usually
5082 PyType_GenericNew), after performing various
5083 sanity checks and constructing a new argument
5084 list. Cut all that nonsense short -- this speeds
5085 up instance creation tremendously. */
5086 specific = type->tp_new;
5087 /* XXX I'm not 100% sure that there isn't a hole
5088 in this reasoning that requires additional
5089 sanity checks. I'll buy the first person to
5090 point out a bug in this reasoning a beer. */
5091 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005092 else {
5093 use_generic = 1;
5094 generic = p->function;
5095 }
5096 } while ((++p)->offset == offset);
5097 if (specific && !use_generic)
5098 *ptr = specific;
5099 else
5100 *ptr = generic;
5101 return p;
5102}
5103
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005104/* In the type, update the slots whose slotdefs are gathered in the pp array.
5105 This is a callback for update_subclasses(). */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005106static int
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005107update_slots_callback(PyTypeObject *type, void *data)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005108{
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005109 slotdef **pp = (slotdef **)data;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005110
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005111 for (; *pp; pp++)
Guido van Rossumc334df52002-04-04 23:44:47 +00005112 update_one_slot(type, *pp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005113 return 0;
5114}
5115
Guido van Rossumc334df52002-04-04 23:44:47 +00005116/* Comparison function for qsort() to compare slotdefs by their offset, and
5117 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005118static int
5119slotdef_cmp(const void *aa, const void *bb)
5120{
5121 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
5122 int c = a->offset - b->offset;
5123 if (c != 0)
5124 return c;
5125 else
5126 return a - b;
5127}
5128
Guido van Rossumc334df52002-04-04 23:44:47 +00005129/* Initialize the slotdefs table by adding interned string objects for the
5130 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005131static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005132init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005133{
5134 slotdef *p;
5135 static int initialized = 0;
5136
5137 if (initialized)
5138 return;
5139 for (p = slotdefs; p->name; p++) {
5140 p->name_strobj = PyString_InternFromString(p->name);
5141 if (!p->name_strobj)
Guido van Rossumc334df52002-04-04 23:44:47 +00005142 Py_FatalError("Out of memory interning slotdef names");
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005143 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005144 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
5145 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005146 initialized = 1;
5147}
5148
Guido van Rossumc334df52002-04-04 23:44:47 +00005149/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005150static int
5151update_slot(PyTypeObject *type, PyObject *name)
5152{
Guido van Rossumc334df52002-04-04 23:44:47 +00005153 slotdef *ptrs[MAX_EQUIV];
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005154 slotdef *p;
5155 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005156 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005157
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005158 init_slotdefs();
5159 pp = ptrs;
5160 for (p = slotdefs; p->name; p++) {
5161 /* XXX assume name is interned! */
5162 if (p->name_strobj == name)
5163 *pp++ = p;
5164 }
5165 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005166 for (pp = ptrs; *pp; pp++) {
5167 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005168 offset = p->offset;
5169 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005170 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005171 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005172 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005173 if (ptrs[0] == NULL)
5174 return 0; /* Not an attribute that affects any slots */
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005175 return update_subclasses(type, name,
5176 update_slots_callback, (void *)ptrs);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005177}
5178
Guido van Rossumc334df52002-04-04 23:44:47 +00005179/* Store the proper functions in the slot dispatches at class (type)
5180 definition time, based upon which operations the class overrides in its
5181 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00005182static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005183fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005184{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005185 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005186
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005187 init_slotdefs();
Guido van Rossumc334df52002-04-04 23:44:47 +00005188 for (p = slotdefs; p->name; )
5189 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005190}
Guido van Rossum705f0f52001-08-24 16:47:00 +00005191
Michael W. Hudson98bbc492002-11-26 14:47:27 +00005192static void
5193update_all_slots(PyTypeObject* type)
5194{
5195 slotdef *p;
5196
5197 init_slotdefs();
5198 for (p = slotdefs; p->name; p++) {
5199 /* update_slot returns int but can't actually fail */
5200 update_slot(type, p->name_strobj);
5201 }
5202}
5203
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005204/* recurse_down_subclasses() and update_subclasses() are mutually
5205 recursive functions to call a callback for all subclasses,
5206 but refraining from recursing into subclasses that define 'name'. */
5207
5208static int
5209update_subclasses(PyTypeObject *type, PyObject *name,
5210 update_callback callback, void *data)
5211{
5212 if (callback(type, data) < 0)
5213 return -1;
5214 return recurse_down_subclasses(type, name, callback, data);
5215}
5216
5217static int
5218recurse_down_subclasses(PyTypeObject *type, PyObject *name,
5219 update_callback callback, void *data)
5220{
5221 PyTypeObject *subclass;
5222 PyObject *ref, *subclasses, *dict;
5223 int i, n;
5224
5225 subclasses = type->tp_subclasses;
5226 if (subclasses == NULL)
5227 return 0;
5228 assert(PyList_Check(subclasses));
5229 n = PyList_GET_SIZE(subclasses);
5230 for (i = 0; i < n; i++) {
5231 ref = PyList_GET_ITEM(subclasses, i);
5232 assert(PyWeakref_CheckRef(ref));
5233 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
5234 assert(subclass != NULL);
5235 if ((PyObject *)subclass == Py_None)
5236 continue;
5237 assert(PyType_Check(subclass));
5238 /* Avoid recursing down into unaffected classes */
5239 dict = subclass->tp_dict;
5240 if (dict != NULL && PyDict_Check(dict) &&
5241 PyDict_GetItem(dict, name) != NULL)
5242 continue;
5243 if (update_subclasses(subclass, name, callback, data) < 0)
5244 return -1;
5245 }
5246 return 0;
5247}
5248
Guido van Rossum6d204072001-10-21 00:44:31 +00005249/* This function is called by PyType_Ready() to populate the type's
5250 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00005251 function slot (like tp_repr) that's defined in the type, one or more
5252 corresponding descriptors are added in the type's tp_dict dictionary
5253 under the appropriate name (like __repr__). Some function slots
5254 cause more than one descriptor to be added (for example, the nb_add
5255 slot adds both __add__ and __radd__ descriptors) and some function
5256 slots compete for the same descriptor (for example both sq_item and
5257 mp_subscript generate a __getitem__ descriptor).
5258
5259 In the latter case, the first slotdef entry encoutered wins. Since
Tim Petersbf9b2442003-03-23 05:35:36 +00005260 slotdef entries are sorted by the offset of the slot in the
Guido van Rossume5c691a2003-03-07 15:13:17 +00005261 PyHeapTypeObject, this gives us some control over disambiguating
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005262 between competing slots: the members of PyHeapTypeObject are listed
5263 from most general to least general, so the most general slot is
5264 preferred. In particular, because as_mapping comes before as_sequence,
5265 for a type that defines both mp_subscript and sq_item, mp_subscript
5266 wins.
Guido van Rossum09638c12002-06-13 19:17:46 +00005267
5268 This only adds new descriptors and doesn't overwrite entries in
5269 tp_dict that were previously defined. The descriptors contain a
5270 reference to the C function they must call, so that it's safe if they
5271 are copied into a subtype's __dict__ and the subtype has a different
5272 C function in its slot -- calling the method defined by the
5273 descriptor will call the C function that was used to create it,
5274 rather than the C function present in the slot when it is called.
5275 (This is important because a subtype may have a C function in the
5276 slot that calls the method from the dictionary, and we want to avoid
5277 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00005278
5279static int
5280add_operators(PyTypeObject *type)
5281{
5282 PyObject *dict = type->tp_dict;
5283 slotdef *p;
5284 PyObject *descr;
5285 void **ptr;
5286
5287 init_slotdefs();
5288 for (p = slotdefs; p->name; p++) {
5289 if (p->wrapper == NULL)
5290 continue;
5291 ptr = slotptr(type, p->offset);
5292 if (!ptr || !*ptr)
5293 continue;
5294 if (PyDict_GetItem(dict, p->name_strobj))
5295 continue;
5296 descr = PyDescr_NewWrapper(type, p, *ptr);
5297 if (descr == NULL)
5298 return -1;
5299 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
5300 return -1;
5301 Py_DECREF(descr);
5302 }
5303 if (type->tp_new != NULL) {
5304 if (add_tp_new_wrapper(type) < 0)
5305 return -1;
5306 }
5307 return 0;
5308}
5309
Guido van Rossum705f0f52001-08-24 16:47:00 +00005310
5311/* Cooperative 'super' */
5312
5313typedef struct {
5314 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00005315 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005316 PyObject *obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005317 PyTypeObject *obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005318} superobject;
5319
Guido van Rossum6f799372001-09-20 20:46:19 +00005320static PyMemberDef super_members[] = {
5321 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
5322 "the class invoking super()"},
5323 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
5324 "the instance invoking super(); may be None"},
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005325 {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
5326 "the type of the the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005327 {0}
5328};
5329
Guido van Rossum705f0f52001-08-24 16:47:00 +00005330static void
5331super_dealloc(PyObject *self)
5332{
5333 superobject *su = (superobject *)self;
5334
Guido van Rossum048eb752001-10-02 21:24:57 +00005335 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005336 Py_XDECREF(su->obj);
5337 Py_XDECREF(su->type);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005338 Py_XDECREF(su->obj_type);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005339 self->ob_type->tp_free(self);
5340}
5341
5342static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005343super_repr(PyObject *self)
5344{
5345 superobject *su = (superobject *)self;
5346
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005347 if (su->obj_type)
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005348 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005349 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005350 su->type ? su->type->tp_name : "NULL",
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005351 su->obj_type->tp_name);
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005352 else
5353 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005354 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005355 su->type ? su->type->tp_name : "NULL");
5356}
5357
5358static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00005359super_getattro(PyObject *self, PyObject *name)
5360{
5361 superobject *su = (superobject *)self;
Guido van Rossum76ba09f2003-04-16 19:40:58 +00005362 int skip = su->obj_type == NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005363
Guido van Rossum76ba09f2003-04-16 19:40:58 +00005364 if (!skip) {
5365 /* We want __class__ to return the class of the super object
5366 (i.e. super, or a subclass), not the class of su->obj. */
5367 skip = (PyString_Check(name) &&
5368 PyString_GET_SIZE(name) == 9 &&
5369 strcmp(PyString_AS_STRING(name), "__class__") == 0);
5370 }
5371
5372 if (!skip) {
Tim Petersa91e9642001-11-14 23:32:33 +00005373 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005374 PyTypeObject *starttype;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005375 descrgetfunc f;
5376 int i, n;
5377
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005378 starttype = su->obj_type;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005379 mro = starttype->tp_mro;
5380
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005381 if (mro == NULL)
5382 n = 0;
5383 else {
5384 assert(PyTuple_Check(mro));
5385 n = PyTuple_GET_SIZE(mro);
5386 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005387 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00005388 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00005389 break;
5390 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005391 i++;
5392 res = NULL;
5393 for (; i < n; i++) {
5394 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00005395 if (PyType_Check(tmp))
5396 dict = ((PyTypeObject *)tmp)->tp_dict;
5397 else if (PyClass_Check(tmp))
5398 dict = ((PyClassObject *)tmp)->cl_dict;
5399 else
5400 continue;
5401 res = PyDict_GetItem(dict, name);
Guido van Rossum2fd02eb2003-04-14 21:20:26 +00005402 if (res != NULL && !PyDescr_IsData(res)) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00005403 Py_INCREF(res);
5404 f = res->ob_type->tp_descr_get;
5405 if (f != NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00005406 tmp = f(res, su->obj,
5407 (PyObject *)starttype);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005408 Py_DECREF(res);
5409 res = tmp;
5410 }
5411 return res;
5412 }
5413 }
5414 }
5415 return PyObject_GenericGetAttr(self, name);
5416}
5417
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005418static PyTypeObject *
Guido van Rossum5b443c62001-12-03 15:38:28 +00005419supercheck(PyTypeObject *type, PyObject *obj)
5420{
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005421 /* Check that a super() call makes sense. Return a type object.
5422
5423 obj can be a new-style class, or an instance of one:
5424
5425 - If it is a class, it must be a subclass of 'type'. This case is
5426 used for class methods; the return value is obj.
5427
5428 - If it is an instance, it must be an instance of 'type'. This is
5429 the normal case; the return value is obj.__class__.
5430
5431 But... when obj is an instance, we want to allow for the case where
5432 obj->ob_type is not a subclass of type, but obj.__class__ is!
5433 This will allow using super() with a proxy for obj.
5434 */
5435
Guido van Rossum8e80a722003-02-18 19:22:22 +00005436 /* Check for first bullet above (special case) */
5437 if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
5438 Py_INCREF(obj);
5439 return (PyTypeObject *)obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005440 }
Guido van Rossum8e80a722003-02-18 19:22:22 +00005441
5442 /* Normal case */
5443 if (PyType_IsSubtype(obj->ob_type, type)) {
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005444 Py_INCREF(obj->ob_type);
5445 return obj->ob_type;
5446 }
5447 else {
5448 /* Try the slow way */
5449 static PyObject *class_str = NULL;
5450 PyObject *class_attr;
5451
5452 if (class_str == NULL) {
5453 class_str = PyString_FromString("__class__");
5454 if (class_str == NULL)
5455 return NULL;
5456 }
5457
5458 class_attr = PyObject_GetAttr(obj, class_str);
5459
5460 if (class_attr != NULL &&
5461 PyType_Check(class_attr) &&
5462 (PyTypeObject *)class_attr != obj->ob_type)
5463 {
5464 int ok = PyType_IsSubtype(
5465 (PyTypeObject *)class_attr, type);
5466 if (ok)
5467 return (PyTypeObject *)class_attr;
5468 }
5469
5470 if (class_attr == NULL)
5471 PyErr_Clear();
5472 else
5473 Py_DECREF(class_attr);
5474 }
5475
Tim Peters97e5ff52003-02-18 19:32:50 +00005476 PyErr_SetString(PyExc_TypeError,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005477 "super(type, obj): "
5478 "obj must be an instance or subtype of type");
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005479 return NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005480}
5481
Guido van Rossum705f0f52001-08-24 16:47:00 +00005482static PyObject *
5483super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5484{
5485 superobject *su = (superobject *)self;
5486 superobject *new;
5487
5488 if (obj == NULL || obj == Py_None || su->obj != NULL) {
5489 /* Not binding to an object, or already bound */
5490 Py_INCREF(self);
5491 return self;
5492 }
Guido van Rossum5b443c62001-12-03 15:38:28 +00005493 if (su->ob_type != &PySuper_Type)
5494 /* If su is an instance of a subclass of super,
5495 call its type */
5496 return PyObject_CallFunction((PyObject *)su->ob_type,
5497 "OO", su->type, obj);
5498 else {
5499 /* Inline the common case */
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005500 PyTypeObject *obj_type = supercheck(su->type, obj);
5501 if (obj_type == NULL)
Guido van Rossum5b443c62001-12-03 15:38:28 +00005502 return NULL;
5503 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
5504 NULL, NULL);
5505 if (new == NULL)
5506 return NULL;
5507 Py_INCREF(su->type);
5508 Py_INCREF(obj);
5509 new->type = su->type;
5510 new->obj = obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005511 new->obj_type = obj_type;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005512 return (PyObject *)new;
5513 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005514}
5515
5516static int
5517super_init(PyObject *self, PyObject *args, PyObject *kwds)
5518{
5519 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00005520 PyTypeObject *type;
5521 PyObject *obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005522 PyTypeObject *obj_type = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005523
5524 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
5525 return -1;
5526 if (obj == Py_None)
5527 obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005528 if (obj != NULL) {
5529 obj_type = supercheck(type, obj);
5530 if (obj_type == NULL)
5531 return -1;
5532 Py_INCREF(obj);
5533 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005534 Py_INCREF(type);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005535 su->type = type;
5536 su->obj = obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005537 su->obj_type = obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005538 return 0;
5539}
5540
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005541PyDoc_STRVAR(super_doc,
Guido van Rossum705f0f52001-08-24 16:47:00 +00005542"super(type) -> unbound super object\n"
5543"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00005544"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00005545"Typical use to call a cooperative superclass method:\n"
5546"class C(B):\n"
5547" def meth(self, arg):\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005548" super(C, self).meth(arg)");
Guido van Rossum705f0f52001-08-24 16:47:00 +00005549
Guido van Rossum048eb752001-10-02 21:24:57 +00005550static int
5551super_traverse(PyObject *self, visitproc visit, void *arg)
5552{
5553 superobject *su = (superobject *)self;
5554 int err;
5555
5556#define VISIT(SLOT) \
5557 if (SLOT) { \
5558 err = visit((PyObject *)(SLOT), arg); \
5559 if (err) \
5560 return err; \
5561 }
5562
5563 VISIT(su->obj);
5564 VISIT(su->type);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005565 VISIT(su->obj_type);
Guido van Rossum048eb752001-10-02 21:24:57 +00005566
5567#undef VISIT
5568
5569 return 0;
5570}
5571
Guido van Rossum705f0f52001-08-24 16:47:00 +00005572PyTypeObject PySuper_Type = {
5573 PyObject_HEAD_INIT(&PyType_Type)
5574 0, /* ob_size */
5575 "super", /* tp_name */
5576 sizeof(superobject), /* tp_basicsize */
5577 0, /* tp_itemsize */
5578 /* methods */
5579 super_dealloc, /* tp_dealloc */
5580 0, /* tp_print */
5581 0, /* tp_getattr */
5582 0, /* tp_setattr */
5583 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005584 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005585 0, /* tp_as_number */
5586 0, /* tp_as_sequence */
5587 0, /* tp_as_mapping */
5588 0, /* tp_hash */
5589 0, /* tp_call */
5590 0, /* tp_str */
5591 super_getattro, /* tp_getattro */
5592 0, /* tp_setattro */
5593 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00005594 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
5595 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005596 super_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00005597 super_traverse, /* tp_traverse */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005598 0, /* tp_clear */
5599 0, /* tp_richcompare */
5600 0, /* tp_weaklistoffset */
5601 0, /* tp_iter */
5602 0, /* tp_iternext */
5603 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005604 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005605 0, /* tp_getset */
5606 0, /* tp_base */
5607 0, /* tp_dict */
5608 super_descr_get, /* tp_descr_get */
5609 0, /* tp_descr_set */
5610 0, /* tp_dictoffset */
5611 super_init, /* tp_init */
5612 PyType_GenericAlloc, /* tp_alloc */
5613 PyType_GenericNew, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00005614 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005615};