blob: f2511791b2ce9690e095340e68dda771f3f79732 [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* Type object implementation */
2
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003#include "Python.h"
Tim Peters6d6c1a32001-08-02 04:15:00 +00004#include "structmember.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00005
Guido van Rossum9923ffe2002-06-04 19:52:53 +00006#include <ctype.h>
7
Guido van Rossum6f799372001-09-20 20:46:19 +00008static PyMemberDef type_members[] = {
Tim Peters6d6c1a32001-08-02 04:15:00 +00009 {"__basicsize__", T_INT, offsetof(PyTypeObject,tp_basicsize),READONLY},
10 {"__itemsize__", T_INT, offsetof(PyTypeObject, tp_itemsize), READONLY},
11 {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY},
Guido van Rossum9676b222001-08-17 20:32:36 +000012 {"__weakrefoffset__", T_LONG,
Tim Peters6d6c1a32001-08-02 04:15:00 +000013 offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
14 {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY},
15 {"__dictoffset__", T_LONG,
16 offsetof(PyTypeObject, tp_dictoffset), READONLY},
Tim Peters6d6c1a32001-08-02 04:15:00 +000017 {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY},
18 {0}
19};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000020
Guido van Rossumc0b618a1997-05-02 03:12:38 +000021static PyObject *
Guido van Rossumc3542212001-08-16 09:18:56 +000022type_name(PyTypeObject *type, void *context)
23{
24 char *s;
25
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +000026 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
Guido van Rossume5c691a2003-03-07 15:13:17 +000027 PyHeapTypeObject* et = (PyHeapTypeObject*)type;
Tim Petersea7f75d2002-12-07 21:39:16 +000028
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +000029 Py_INCREF(et->name);
30 return et->name;
31 }
32 else {
33 s = strrchr(type->tp_name, '.');
34 if (s == NULL)
35 s = type->tp_name;
36 else
37 s++;
38 return PyString_FromString(s);
39 }
Guido van Rossumc3542212001-08-16 09:18:56 +000040}
41
Michael W. Hudson98bbc492002-11-26 14:47:27 +000042static int
43type_set_name(PyTypeObject *type, PyObject *value, void *context)
44{
Guido van Rossume5c691a2003-03-07 15:13:17 +000045 PyHeapTypeObject* et;
Michael W. Hudson98bbc492002-11-26 14:47:27 +000046
47 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
48 PyErr_Format(PyExc_TypeError,
49 "can't set %s.__name__", type->tp_name);
50 return -1;
51 }
52 if (!value) {
53 PyErr_Format(PyExc_TypeError,
54 "can't delete %s.__name__", type->tp_name);
55 return -1;
56 }
57 if (!PyString_Check(value)) {
58 PyErr_Format(PyExc_TypeError,
59 "can only assign string to %s.__name__, not '%s'",
60 type->tp_name, value->ob_type->tp_name);
61 return -1;
62 }
Tim Petersea7f75d2002-12-07 21:39:16 +000063 if (strlen(PyString_AS_STRING(value))
Michael W. Hudson98bbc492002-11-26 14:47:27 +000064 != (size_t)PyString_GET_SIZE(value)) {
65 PyErr_Format(PyExc_ValueError,
66 "__name__ must not contain null bytes");
67 return -1;
68 }
69
Guido van Rossume5c691a2003-03-07 15:13:17 +000070 et = (PyHeapTypeObject*)type;
Michael W. Hudson98bbc492002-11-26 14:47:27 +000071
72 Py_INCREF(value);
73
74 Py_DECREF(et->name);
75 et->name = value;
76
77 type->tp_name = PyString_AS_STRING(value);
78
79 return 0;
80}
81
Guido van Rossumc3542212001-08-16 09:18:56 +000082static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +000083type_module(PyTypeObject *type, void *context)
Guido van Rossum29ca26e1995-01-07 11:58:15 +000084{
Guido van Rossumc3542212001-08-16 09:18:56 +000085 PyObject *mod;
86 char *s;
87
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +000088 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
89 mod = PyDict_GetItemString(type->tp_dict, "__module__");
90 Py_XINCREF(mod);
Guido van Rossumc3542212001-08-16 09:18:56 +000091 return mod;
92 }
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +000093 else {
94 s = strrchr(type->tp_name, '.');
95 if (s != NULL)
96 return PyString_FromStringAndSize(
97 type->tp_name, (int)(s - type->tp_name));
98 return PyString_FromString("__builtin__");
99 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000100}
101
Guido van Rossum3926a632001-09-25 16:25:58 +0000102static int
103type_set_module(PyTypeObject *type, PyObject *value, void *context)
104{
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000105 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
Guido van Rossum3926a632001-09-25 16:25:58 +0000106 PyErr_Format(PyExc_TypeError,
107 "can't set %s.__module__", type->tp_name);
108 return -1;
109 }
110 if (!value) {
111 PyErr_Format(PyExc_TypeError,
112 "can't delete %s.__module__", type->tp_name);
113 return -1;
114 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000115
Guido van Rossum3926a632001-09-25 16:25:58 +0000116 return PyDict_SetItemString(type->tp_dict, "__module__", value);
117}
118
Tim Peters6d6c1a32001-08-02 04:15:00 +0000119static PyObject *
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000120type_get_bases(PyTypeObject *type, void *context)
121{
122 Py_INCREF(type->tp_bases);
123 return type->tp_bases;
124}
125
126static PyTypeObject *best_base(PyObject *);
127static int mro_internal(PyTypeObject *);
128static int compatible_for_assignment(PyTypeObject *, PyTypeObject *, char *);
129static int add_subclass(PyTypeObject*, PyTypeObject*);
130static void remove_subclass(PyTypeObject *, PyTypeObject *);
131static void update_all_slots(PyTypeObject *);
132
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000133typedef int (*update_callback)(PyTypeObject *, void *);
134static int update_subclasses(PyTypeObject *type, PyObject *name,
135 update_callback callback, void *data);
136static int recurse_down_subclasses(PyTypeObject *type, PyObject *name,
137 update_callback callback, void *data);
138
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000139static int
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000140mro_subclasses(PyTypeObject *type, PyObject* temp)
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000141{
142 PyTypeObject *subclass;
143 PyObject *ref, *subclasses, *old_mro;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000144 int i, n;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000145
146 subclasses = type->tp_subclasses;
147 if (subclasses == NULL)
148 return 0;
149 assert(PyList_Check(subclasses));
150 n = PyList_GET_SIZE(subclasses);
151 for (i = 0; i < n; i++) {
152 ref = PyList_GET_ITEM(subclasses, i);
153 assert(PyWeakref_CheckRef(ref));
154 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
155 assert(subclass != NULL);
156 if ((PyObject *)subclass == Py_None)
157 continue;
158 assert(PyType_Check(subclass));
159 old_mro = subclass->tp_mro;
160 if (mro_internal(subclass) < 0) {
161 subclass->tp_mro = old_mro;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000162 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000163 }
164 else {
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000165 PyObject* tuple;
166 tuple = Py_BuildValue("OO", subclass, old_mro);
Guido van Rossum19a02ba2003-04-15 22:09:45 +0000167 Py_DECREF(old_mro);
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000168 if (!tuple)
169 return -1;
170 if (PyList_Append(temp, tuple) < 0)
171 return -1;
Guido van Rossum19a02ba2003-04-15 22:09:45 +0000172 Py_DECREF(tuple);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000173 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000174 if (mro_subclasses(subclass, temp) < 0)
175 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000176 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000177 return 0;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000178}
179
180static int
181type_set_bases(PyTypeObject *type, PyObject *value, void *context)
182{
183 int i, r = 0;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000184 PyObject *ob, *temp;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000185 PyTypeObject *new_base, *old_base;
186 PyObject *old_bases, *old_mro;
187
188 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
189 PyErr_Format(PyExc_TypeError,
190 "can't set %s.__bases__", type->tp_name);
191 return -1;
192 }
193 if (!value) {
194 PyErr_Format(PyExc_TypeError,
195 "can't delete %s.__bases__", type->tp_name);
196 return -1;
197 }
198 if (!PyTuple_Check(value)) {
199 PyErr_Format(PyExc_TypeError,
200 "can only assign tuple to %s.__bases__, not %s",
201 type->tp_name, value->ob_type->tp_name);
202 return -1;
203 }
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +0000204 if (PyTuple_GET_SIZE(value) == 0) {
205 PyErr_Format(PyExc_TypeError,
206 "can only assign non-empty tuple to %s.__bases__, not ()",
207 type->tp_name);
208 return -1;
209 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000210 for (i = 0; i < PyTuple_GET_SIZE(value); i++) {
211 ob = PyTuple_GET_ITEM(value, i);
212 if (!PyClass_Check(ob) && !PyType_Check(ob)) {
213 PyErr_Format(
214 PyExc_TypeError,
215 "%s.__bases__ must be tuple of old- or new-style classes, not '%s'",
216 type->tp_name, ob->ob_type->tp_name);
217 return -1;
218 }
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +0000219 if (PyType_Check(ob)) {
220 if (PyType_IsSubtype((PyTypeObject*)ob, type)) {
221 PyErr_SetString(PyExc_TypeError,
222 "a __bases__ item causes an inheritance cycle");
223 return -1;
224 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000225 }
226 }
227
228 new_base = best_base(value);
229
230 if (!new_base) {
231 return -1;
232 }
233
234 if (!compatible_for_assignment(type->tp_base, new_base, "__bases__"))
235 return -1;
236
237 Py_INCREF(new_base);
238 Py_INCREF(value);
239
240 old_bases = type->tp_bases;
241 old_base = type->tp_base;
242 old_mro = type->tp_mro;
243
244 type->tp_bases = value;
245 type->tp_base = new_base;
246
247 if (mro_internal(type) < 0) {
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000248 goto bail;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000249 }
250
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000251 temp = PyList_New(0);
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000252 if (!temp)
253 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000254
255 r = mro_subclasses(type, temp);
256
257 if (r < 0) {
258 for (i = 0; i < PyList_Size(temp); i++) {
259 PyTypeObject* cls;
260 PyObject* mro;
Guido van Rossum19a02ba2003-04-15 22:09:45 +0000261 PyArg_ParseTuple(PyList_GET_ITEM(temp, i),
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000262 "OO", &cls, &mro);
263 Py_DECREF(cls->tp_mro);
264 cls->tp_mro = mro;
265 Py_INCREF(cls->tp_mro);
266 }
267 Py_DECREF(temp);
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000268 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000269 }
270
271 Py_DECREF(temp);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000272
273 /* any base that was in __bases__ but now isn't, we
Raymond Hettingera8285862002-12-14 17:17:56 +0000274 need to remove |type| from its tp_subclasses.
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000275 conversely, any class now in __bases__ that wasn't
Raymond Hettingera8285862002-12-14 17:17:56 +0000276 needs to have |type| added to its subclasses. */
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000277
278 /* for now, sod that: just remove from all old_bases,
279 add to all new_bases */
280
281 for (i = PyTuple_GET_SIZE(old_bases) - 1; i >= 0; i--) {
282 ob = PyTuple_GET_ITEM(old_bases, i);
283 if (PyType_Check(ob)) {
284 remove_subclass(
285 (PyTypeObject*)ob, type);
286 }
287 }
288
289 for (i = PyTuple_GET_SIZE(value) - 1; i >= 0; i--) {
290 ob = PyTuple_GET_ITEM(value, i);
291 if (PyType_Check(ob)) {
292 if (add_subclass((PyTypeObject*)ob, type) < 0)
293 r = -1;
294 }
295 }
296
297 update_all_slots(type);
298
299 Py_DECREF(old_bases);
300 Py_DECREF(old_base);
301 Py_DECREF(old_mro);
302
303 return r;
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000304
305 bail:
306 type->tp_bases = old_bases;
307 type->tp_base = old_base;
308 type->tp_mro = old_mro;
Tim Petersea7f75d2002-12-07 21:39:16 +0000309
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000310 Py_DECREF(value);
311 Py_DECREF(new_base);
Tim Petersea7f75d2002-12-07 21:39:16 +0000312
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000313 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000314}
315
316static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000317type_dict(PyTypeObject *type, void *context)
318{
319 if (type->tp_dict == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000320 Py_INCREF(Py_None);
321 return Py_None;
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000322 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000323 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000324}
325
Tim Peters24008312002-03-17 18:56:20 +0000326static PyObject *
327type_get_doc(PyTypeObject *type, void *context)
328{
329 PyObject *result;
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000330 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL)
Tim Peters24008312002-03-17 18:56:20 +0000331 return PyString_FromString(type->tp_doc);
Tim Peters24008312002-03-17 18:56:20 +0000332 result = PyDict_GetItemString(type->tp_dict, "__doc__");
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000333 if (result == NULL) {
334 result = Py_None;
335 Py_INCREF(result);
336 }
337 else if (result->ob_type->tp_descr_get) {
Tim Peters2b858972002-04-18 04:12:28 +0000338 result = result->ob_type->tp_descr_get(result, NULL,
339 (PyObject *)type);
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000340 }
341 else {
342 Py_INCREF(result);
343 }
Tim Peters24008312002-03-17 18:56:20 +0000344 return result;
345}
346
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000347static PyGetSetDef type_getsets[] = {
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000348 {"__name__", (getter)type_name, (setter)type_set_name, NULL},
349 {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL},
Guido van Rossum3926a632001-09-25 16:25:58 +0000350 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000351 {"__dict__", (getter)type_dict, NULL, NULL},
Tim Peters24008312002-03-17 18:56:20 +0000352 {"__doc__", (getter)type_get_doc, NULL, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000353 {0}
354};
355
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000356static int
357type_compare(PyObject *v, PyObject *w)
358{
359 /* This is called with type objects only. So we
360 can just compare the addresses. */
361 Py_uintptr_t vv = (Py_uintptr_t)v;
362 Py_uintptr_t ww = (Py_uintptr_t)w;
363 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
364}
365
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000366static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000367type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000368{
Barry Warsaw7ce36942001-08-24 18:34:26 +0000369 PyObject *mod, *name, *rtn;
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000370 char *kind;
Guido van Rossumc3542212001-08-16 09:18:56 +0000371
372 mod = type_module(type, NULL);
373 if (mod == NULL)
374 PyErr_Clear();
375 else if (!PyString_Check(mod)) {
376 Py_DECREF(mod);
377 mod = NULL;
378 }
379 name = type_name(type, NULL);
380 if (name == NULL)
381 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000382
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000383 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
384 kind = "class";
385 else
386 kind = "type";
387
Barry Warsaw7ce36942001-08-24 18:34:26 +0000388 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__")) {
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000389 rtn = PyString_FromFormat("<%s '%s.%s'>",
390 kind,
Barry Warsaw7ce36942001-08-24 18:34:26 +0000391 PyString_AS_STRING(mod),
392 PyString_AS_STRING(name));
393 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000394 else
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000395 rtn = PyString_FromFormat("<%s '%s'>", kind, type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000396
Guido van Rossumc3542212001-08-16 09:18:56 +0000397 Py_XDECREF(mod);
398 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000399 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000400}
401
Tim Peters6d6c1a32001-08-02 04:15:00 +0000402static PyObject *
403type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
404{
405 PyObject *obj;
406
407 if (type->tp_new == NULL) {
408 PyErr_Format(PyExc_TypeError,
409 "cannot create '%.100s' instances",
410 type->tp_name);
411 return NULL;
412 }
413
Tim Peters3f996e72001-09-13 19:18:27 +0000414 obj = type->tp_new(type, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000415 if (obj != NULL) {
Guido van Rossumf76de622001-10-18 15:49:21 +0000416 /* Ugly exception: when the call was type(something),
417 don't call tp_init on the result. */
418 if (type == &PyType_Type &&
419 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
420 (kwds == NULL ||
421 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
422 return obj;
Guido van Rossum8ace1ab2002-04-06 01:05:01 +0000423 /* If the returned object is not an instance of type,
424 it won't be initialized. */
425 if (!PyType_IsSubtype(obj->ob_type, type))
426 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000427 type = obj->ob_type;
Jeremy Hylton719841e2002-07-16 19:39:38 +0000428 if (PyType_HasFeature(type, Py_TPFLAGS_HAVE_CLASS) &&
429 type->tp_init != NULL &&
Tim Peters6d6c1a32001-08-02 04:15:00 +0000430 type->tp_init(obj, args, kwds) < 0) {
431 Py_DECREF(obj);
432 obj = NULL;
433 }
434 }
435 return obj;
436}
437
438PyObject *
439PyType_GenericAlloc(PyTypeObject *type, int nitems)
440{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000441 PyObject *obj;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000442 const size_t size = _PyObject_VAR_SIZE(type, nitems+1);
443 /* note that we need to add one, for the sentinel */
Tim Peters406fe3b2001-10-06 19:04:01 +0000444
445 if (PyType_IS_GC(type))
Neil Schemenauer09a2ae52002-04-12 03:06:53 +0000446 obj = _PyObject_GC_Malloc(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000447 else
Neil Schemenauerc806c882001-08-29 23:54:54 +0000448 obj = PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000449
Neil Schemenauerc806c882001-08-29 23:54:54 +0000450 if (obj == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000451 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000452
Neil Schemenauerc806c882001-08-29 23:54:54 +0000453 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000454
Tim Peters6d6c1a32001-08-02 04:15:00 +0000455 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
456 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000457
Tim Peters6d6c1a32001-08-02 04:15:00 +0000458 if (type->tp_itemsize == 0)
459 PyObject_INIT(obj, type);
460 else
461 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000462
Tim Peters6d6c1a32001-08-02 04:15:00 +0000463 if (PyType_IS_GC(type))
Neil Schemenauerc806c882001-08-29 23:54:54 +0000464 _PyObject_GC_TRACK(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000465 return obj;
466}
467
468PyObject *
469PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
470{
471 return type->tp_alloc(type, 0);
472}
473
Guido van Rossum9475a232001-10-05 20:51:39 +0000474/* Helpers for subtyping */
475
476static int
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000477traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
478{
479 int i, n;
480 PyMemberDef *mp;
481
482 n = type->ob_size;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000483 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000484 for (i = 0; i < n; i++, mp++) {
485 if (mp->type == T_OBJECT_EX) {
486 char *addr = (char *)self + mp->offset;
487 PyObject *obj = *(PyObject **)addr;
488 if (obj != NULL) {
489 int err = visit(obj, arg);
490 if (err)
491 return err;
492 }
493 }
494 }
495 return 0;
496}
497
498static int
Guido van Rossum9475a232001-10-05 20:51:39 +0000499subtype_traverse(PyObject *self, visitproc visit, void *arg)
500{
501 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000502 traverseproc basetraverse;
Guido van Rossum9475a232001-10-05 20:51:39 +0000503
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000504 /* Find the nearest base with a different tp_traverse,
505 and traverse slots while we're at it */
Guido van Rossum9475a232001-10-05 20:51:39 +0000506 type = self->ob_type;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000507 base = type;
508 while ((basetraverse = base->tp_traverse) == subtype_traverse) {
509 if (base->ob_size) {
510 int err = traverse_slots(base, self, visit, arg);
511 if (err)
512 return err;
513 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000514 base = base->tp_base;
515 assert(base);
516 }
517
518 if (type->tp_dictoffset != base->tp_dictoffset) {
519 PyObject **dictptr = _PyObject_GetDictPtr(self);
520 if (dictptr && *dictptr) {
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000521 int err = visit(*dictptr, arg);
Guido van Rossum9475a232001-10-05 20:51:39 +0000522 if (err)
523 return err;
524 }
525 }
526
Guido van Rossuma3862092002-06-10 15:24:42 +0000527 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
528 /* For a heaptype, the instances count as references
529 to the type. Traverse the type so the collector
530 can find cycles involving this link. */
531 int err = visit((PyObject *)type, arg);
532 if (err)
533 return err;
534 }
535
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000536 if (basetraverse)
537 return basetraverse(self, visit, arg);
538 return 0;
539}
540
541static void
542clear_slots(PyTypeObject *type, PyObject *self)
543{
544 int i, n;
545 PyMemberDef *mp;
546
547 n = type->ob_size;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000548 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000549 for (i = 0; i < n; i++, mp++) {
550 if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
551 char *addr = (char *)self + mp->offset;
552 PyObject *obj = *(PyObject **)addr;
553 if (obj != NULL) {
554 Py_DECREF(obj);
555 *(PyObject **)addr = NULL;
556 }
557 }
558 }
559}
560
561static int
562subtype_clear(PyObject *self)
563{
564 PyTypeObject *type, *base;
565 inquiry baseclear;
566
567 /* Find the nearest base with a different tp_clear
568 and clear slots while we're at it */
569 type = self->ob_type;
570 base = type;
571 while ((baseclear = base->tp_clear) == subtype_clear) {
572 if (base->ob_size)
573 clear_slots(base, self);
574 base = base->tp_base;
575 assert(base);
576 }
577
Guido van Rossuma3862092002-06-10 15:24:42 +0000578 /* There's no need to clear the instance dict (if any);
579 the collector will call its tp_clear handler. */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000580
581 if (baseclear)
582 return baseclear(self);
Guido van Rossum9475a232001-10-05 20:51:39 +0000583 return 0;
584}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000585
586static void
587subtype_dealloc(PyObject *self)
588{
Guido van Rossum14227b42001-12-06 02:35:58 +0000589 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000590 destructor basedealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000591
Guido van Rossum22b13872002-08-06 21:41:44 +0000592 /* Extract the type; we expect it to be a heap type */
593 type = self->ob_type;
594 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000595
Guido van Rossum22b13872002-08-06 21:41:44 +0000596 /* Test whether the type has GC exactly once */
597
598 if (!PyType_IS_GC(type)) {
599 /* It's really rare to find a dynamic type that doesn't have
600 GC; it can only happen when deriving from 'object' and not
601 adding any slots or instance variables. This allows
602 certain simplifications: there's no need to call
603 clear_slots(), or DECREF the dict, or clear weakrefs. */
604
605 /* Maybe call finalizer; exit early if resurrected */
Guido van Rossumfebd61d2002-08-08 20:55:20 +0000606 if (type->tp_del) {
607 type->tp_del(self);
608 if (self->ob_refcnt > 0)
609 return;
610 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000611
612 /* Find the nearest base with a different tp_dealloc */
613 base = type;
614 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
615 assert(base->ob_size == 0);
616 base = base->tp_base;
617 assert(base);
618 }
619
620 /* Call the base tp_dealloc() */
621 assert(basedealloc);
622 basedealloc(self);
623
624 /* Can't reference self beyond this point */
625 Py_DECREF(type);
626
627 /* Done */
628 return;
629 }
630
631 /* We get here only if the type has GC */
632
633 /* UnTrack and re-Track around the trashcan macro, alas */
Andrew M. Kuchlingc9172d32003-02-06 15:22:49 +0000634 /* See explanation at end of function for full disclosure */
Guido van Rossum0906e072002-08-07 20:42:09 +0000635 PyObject_GC_UnTrack(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000636 ++_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000637 Py_TRASHCAN_SAFE_BEGIN(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000638 --_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000639 _PyObject_GC_TRACK(self); /* We'll untrack for real later */
640
Guido van Rossum59195fd2003-06-13 20:54:40 +0000641 /* Find the nearest base with a different tp_dealloc */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000642 base = type;
643 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000644 base = base->tp_base;
645 assert(base);
Guido van Rossum14227b42001-12-06 02:35:58 +0000646 }
647
Guido van Rossum1987c662003-05-29 14:29:23 +0000648 /* If we added a weaklist, we clear it. Do this *before* calling
Guido van Rossum59195fd2003-06-13 20:54:40 +0000649 the finalizer (__del__), clearing slots, or clearing the instance
650 dict. */
651
Guido van Rossum1987c662003-05-29 14:29:23 +0000652 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
653 PyObject_ClearWeakRefs(self);
654
655 /* Maybe call finalizer; exit early if resurrected */
656 if (type->tp_del) {
657 type->tp_del(self);
658 if (self->ob_refcnt > 0)
659 goto endlabel;
660 }
661
Guido van Rossum59195fd2003-06-13 20:54:40 +0000662 /* Clear slots up to the nearest base with a different tp_dealloc */
663 base = type;
664 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
665 if (base->ob_size)
666 clear_slots(base, self);
667 base = base->tp_base;
668 assert(base);
669 }
670
Tim Peters6d6c1a32001-08-02 04:15:00 +0000671 /* If we added a dict, DECREF it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000672 if (type->tp_dictoffset && !base->tp_dictoffset) {
673 PyObject **dictptr = _PyObject_GetDictPtr(self);
674 if (dictptr != NULL) {
675 PyObject *dict = *dictptr;
676 if (dict != NULL) {
677 Py_DECREF(dict);
678 *dictptr = NULL;
679 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000680 }
681 }
682
683 /* Finalize GC if the base doesn't do GC and we do */
Guido van Rossum22b13872002-08-06 21:41:44 +0000684 if (!PyType_IS_GC(base))
Guido van Rossum048eb752001-10-02 21:24:57 +0000685 _PyObject_GC_UNTRACK(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000686
687 /* Call the base tp_dealloc() */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000688 assert(basedealloc);
689 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000690
691 /* Can't reference self beyond this point */
Guido van Rossum22b13872002-08-06 21:41:44 +0000692 Py_DECREF(type);
693
Guido van Rossum0906e072002-08-07 20:42:09 +0000694 endlabel:
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000695 ++_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000696 Py_TRASHCAN_SAFE_END(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000697 --_PyTrash_delete_nesting;
698
699 /* Explanation of the weirdness around the trashcan macros:
700
701 Q. What do the trashcan macros do?
702
703 A. Read the comment titled "Trashcan mechanism" in object.h.
704 For one, this explains why there must be a call to GC-untrack
705 before the trashcan begin macro. Without understanding the
706 trashcan code, the answers to the following questions don't make
707 sense.
708
709 Q. Why do we GC-untrack before the trashcan and then immediately
710 GC-track again afterward?
711
712 A. In the case that the base class is GC-aware, the base class
713 probably GC-untracks the object. If it does that using the
714 UNTRACK macro, this will crash when the object is already
715 untracked. Because we don't know what the base class does, the
716 only safe thing is to make sure the object is tracked when we
717 call the base class dealloc. But... The trashcan begin macro
718 requires that the object is *untracked* before it is called. So
719 the dance becomes:
720
721 GC untrack
722 trashcan begin
723 GC track
724
725 Q. Why the bizarre (net-zero) manipulation of
726 _PyTrash_delete_nesting around the trashcan macros?
727
728 A. Some base classes (e.g. list) also use the trashcan mechanism.
729 The following scenario used to be possible:
730
731 - suppose the trashcan level is one below the trashcan limit
732
733 - subtype_dealloc() is called
734
735 - the trashcan limit is not yet reached, so the trashcan level
736 is incremented and the code between trashcan begin and end is
737 executed
738
739 - this destroys much of the object's contents, including its
740 slots and __dict__
741
742 - basedealloc() is called; this is really list_dealloc(), or
743 some other type which also uses the trashcan macros
744
745 - the trashcan limit is now reached, so the object is put on the
746 trashcan's to-be-deleted-later list
747
748 - basedealloc() returns
749
750 - subtype_dealloc() decrefs the object's type
751
752 - subtype_dealloc() returns
753
754 - later, the trashcan code starts deleting the objects from its
755 to-be-deleted-later list
756
757 - subtype_dealloc() is called *AGAIN* for the same object
758
759 - at the very least (if the destroyed slots and __dict__ don't
760 cause problems) the object's type gets decref'ed a second
761 time, which is *BAD*!!!
762
763 The remedy is to make sure that if the code between trashcan
764 begin and end in subtype_dealloc() is called, the code between
765 trashcan begin and end in basedealloc() will also be called.
766 This is done by decrementing the level after passing into the
767 trashcan block, and incrementing it just before leaving the
768 block.
769
770 But now it's possible that a chain of objects consisting solely
771 of objects whose deallocator is subtype_dealloc() will defeat
772 the trashcan mechanism completely: the decremented level means
773 that the effective level never reaches the limit. Therefore, we
774 *increment* the level *before* entering the trashcan block, and
775 matchingly decrement it after leaving. This means the trashcan
776 code will trigger a little early, but that's no big deal.
777
778 Q. Are there any live examples of code in need of all this
779 complexity?
780
781 A. Yes. See SF bug 668433 for code that crashed (when Python was
782 compiled in debug mode) before the trashcan level manipulations
783 were added. For more discussion, see SF patches 581742, 575073
784 and bug 574207.
785 */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000786}
787
Jeremy Hylton938ace62002-07-17 16:30:39 +0000788static PyTypeObject *solid_base(PyTypeObject *type);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000789
Tim Peters6d6c1a32001-08-02 04:15:00 +0000790/* type test with subclassing support */
791
792int
793PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
794{
795 PyObject *mro;
796
Guido van Rossum9478d072001-09-07 18:52:13 +0000797 if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
798 return b == a || b == &PyBaseObject_Type;
799
Tim Peters6d6c1a32001-08-02 04:15:00 +0000800 mro = a->tp_mro;
801 if (mro != NULL) {
802 /* Deal with multiple inheritance without recursion
803 by walking the MRO tuple */
804 int i, n;
805 assert(PyTuple_Check(mro));
806 n = PyTuple_GET_SIZE(mro);
807 for (i = 0; i < n; i++) {
808 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
809 return 1;
810 }
811 return 0;
812 }
813 else {
814 /* a is not completely initilized yet; follow tp_base */
815 do {
816 if (a == b)
817 return 1;
818 a = a->tp_base;
819 } while (a != NULL);
820 return b == &PyBaseObject_Type;
821 }
822}
823
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000824/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +0000825 without looking in the instance dictionary
826 (so we can't use PyObject_GetAttr) but still binding
827 it to the instance. The arguments are the object,
828 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000829 static variable used to cache the interned Python string.
830
831 Two variants:
832
833 - lookup_maybe() returns NULL without raising an exception
834 when the _PyType_Lookup() call fails;
835
836 - lookup_method() always raises an exception upon errors.
837*/
Guido van Rossum60718732001-08-28 17:47:51 +0000838
839static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000840lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +0000841{
842 PyObject *res;
843
844 if (*attrobj == NULL) {
845 *attrobj = PyString_InternFromString(attrstr);
846 if (*attrobj == NULL)
847 return NULL;
848 }
849 res = _PyType_Lookup(self->ob_type, *attrobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000850 if (res != NULL) {
Guido van Rossum60718732001-08-28 17:47:51 +0000851 descrgetfunc f;
852 if ((f = res->ob_type->tp_descr_get) == NULL)
853 Py_INCREF(res);
854 else
855 res = f(res, self, (PyObject *)(self->ob_type));
856 }
857 return res;
858}
859
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000860static PyObject *
861lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
862{
863 PyObject *res = lookup_maybe(self, attrstr, attrobj);
864 if (res == NULL && !PyErr_Occurred())
865 PyErr_SetObject(PyExc_AttributeError, *attrobj);
866 return res;
867}
868
Guido van Rossum2730b132001-08-28 18:22:14 +0000869/* A variation of PyObject_CallMethod that uses lookup_method()
870 instead of PyObject_GetAttrString(). This uses the same convention
871 as lookup_method to cache the interned name string object. */
872
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000873static PyObject *
Guido van Rossum2730b132001-08-28 18:22:14 +0000874call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
875{
876 va_list va;
877 PyObject *args, *func = 0, *retval;
Guido van Rossum2730b132001-08-28 18:22:14 +0000878 va_start(va, format);
879
Guido van Rossumda21c012001-10-03 00:50:18 +0000880 func = lookup_maybe(o, name, nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000881 if (func == NULL) {
882 va_end(va);
883 if (!PyErr_Occurred())
Guido van Rossumda21c012001-10-03 00:50:18 +0000884 PyErr_SetObject(PyExc_AttributeError, *nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000885 return NULL;
886 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000887
888 if (format && *format)
889 args = Py_VaBuildValue(format, va);
890 else
891 args = PyTuple_New(0);
892
893 va_end(va);
894
895 if (args == NULL)
896 return NULL;
897
898 assert(PyTuple_Check(args));
899 retval = PyObject_Call(func, args, NULL);
900
901 Py_DECREF(args);
902 Py_DECREF(func);
903
904 return retval;
905}
906
907/* Clone of call_method() that returns NotImplemented when the lookup fails. */
908
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000909static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000910call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
911{
912 va_list va;
913 PyObject *args, *func = 0, *retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000914 va_start(va, format);
915
Guido van Rossumda21c012001-10-03 00:50:18 +0000916 func = lookup_maybe(o, name, nameobj);
Guido van Rossum2730b132001-08-28 18:22:14 +0000917 if (func == NULL) {
918 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000919 if (!PyErr_Occurred()) {
920 Py_INCREF(Py_NotImplemented);
921 return Py_NotImplemented;
922 }
Guido van Rossum717ce002001-09-14 16:58:08 +0000923 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +0000924 }
925
926 if (format && *format)
927 args = Py_VaBuildValue(format, va);
928 else
929 args = PyTuple_New(0);
930
931 va_end(va);
932
Guido van Rossum717ce002001-09-14 16:58:08 +0000933 if (args == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +0000934 return NULL;
935
Guido van Rossum717ce002001-09-14 16:58:08 +0000936 assert(PyTuple_Check(args));
937 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +0000938
939 Py_DECREF(args);
940 Py_DECREF(func);
941
942 return retval;
943}
944
Tim Petersa91e9642001-11-14 23:32:33 +0000945static int
946fill_classic_mro(PyObject *mro, PyObject *cls)
947{
948 PyObject *bases, *base;
949 int i, n;
950
951 assert(PyList_Check(mro));
952 assert(PyClass_Check(cls));
953 i = PySequence_Contains(mro, cls);
954 if (i < 0)
955 return -1;
956 if (!i) {
957 if (PyList_Append(mro, cls) < 0)
958 return -1;
959 }
960 bases = ((PyClassObject *)cls)->cl_bases;
961 assert(bases && PyTuple_Check(bases));
962 n = PyTuple_GET_SIZE(bases);
963 for (i = 0; i < n; i++) {
964 base = PyTuple_GET_ITEM(bases, i);
965 if (fill_classic_mro(mro, base) < 0)
966 return -1;
967 }
968 return 0;
969}
970
971static PyObject *
972classic_mro(PyObject *cls)
973{
974 PyObject *mro;
975
976 assert(PyClass_Check(cls));
977 mro = PyList_New(0);
978 if (mro != NULL) {
979 if (fill_classic_mro(mro, cls) == 0)
980 return mro;
981 Py_DECREF(mro);
982 }
983 return NULL;
984}
985
Tim Petersea7f75d2002-12-07 21:39:16 +0000986/*
Guido van Rossum1f121312002-11-14 19:49:16 +0000987 Method resolution order algorithm C3 described in
988 "A Monotonic Superclass Linearization for Dylan",
989 by Kim Barrett, Bob Cassel, Paul Haahr,
Tim Petersea7f75d2002-12-07 21:39:16 +0000990 David A. Moon, Keith Playford, and P. Tucker Withington.
Guido van Rossum1f121312002-11-14 19:49:16 +0000991 (OOPSLA 1996)
992
Guido van Rossum98f33732002-11-25 21:36:54 +0000993 Some notes about the rules implied by C3:
994
Tim Petersea7f75d2002-12-07 21:39:16 +0000995 No duplicate bases.
Guido van Rossum98f33732002-11-25 21:36:54 +0000996 It isn't legal to repeat a class in a list of base classes.
997
998 The next three properties are the 3 constraints in "C3".
999
Tim Petersea7f75d2002-12-07 21:39:16 +00001000 Local precendece order.
Guido van Rossum98f33732002-11-25 21:36:54 +00001001 If A precedes B in C's MRO, then A will precede B in the MRO of all
1002 subclasses of C.
1003
1004 Monotonicity.
1005 The MRO of a class must be an extension without reordering of the
1006 MRO of each of its superclasses.
1007
1008 Extended Precedence Graph (EPG).
1009 Linearization is consistent if there is a path in the EPG from
1010 each class to all its successors in the linearization. See
1011 the paper for definition of EPG.
Guido van Rossum1f121312002-11-14 19:49:16 +00001012 */
1013
Tim Petersea7f75d2002-12-07 21:39:16 +00001014static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001015tail_contains(PyObject *list, int whence, PyObject *o) {
1016 int j, size;
1017 size = PyList_GET_SIZE(list);
1018
1019 for (j = whence+1; j < size; j++) {
1020 if (PyList_GET_ITEM(list, j) == o)
1021 return 1;
1022 }
1023 return 0;
1024}
1025
Guido van Rossum98f33732002-11-25 21:36:54 +00001026static PyObject *
1027class_name(PyObject *cls)
1028{
1029 PyObject *name = PyObject_GetAttrString(cls, "__name__");
1030 if (name == NULL) {
1031 PyErr_Clear();
1032 Py_XDECREF(name);
1033 name = PyObject_Repr(cls);
1034 }
1035 if (name == NULL)
1036 return NULL;
1037 if (!PyString_Check(name)) {
1038 Py_DECREF(name);
1039 return NULL;
1040 }
1041 return name;
1042}
1043
1044static int
1045check_duplicates(PyObject *list)
1046{
1047 int i, j, n;
1048 /* Let's use a quadratic time algorithm,
1049 assuming that the bases lists is short.
1050 */
1051 n = PyList_GET_SIZE(list);
1052 for (i = 0; i < n; i++) {
1053 PyObject *o = PyList_GET_ITEM(list, i);
1054 for (j = i + 1; j < n; j++) {
1055 if (PyList_GET_ITEM(list, j) == o) {
1056 o = class_name(o);
1057 PyErr_Format(PyExc_TypeError,
1058 "duplicate base class %s",
1059 o ? PyString_AS_STRING(o) : "?");
1060 Py_XDECREF(o);
1061 return -1;
1062 }
1063 }
1064 }
1065 return 0;
1066}
1067
1068/* Raise a TypeError for an MRO order disagreement.
1069
1070 It's hard to produce a good error message. In the absence of better
1071 insight into error reporting, report the classes that were candidates
1072 to be put next into the MRO. There is some conflict between the
1073 order in which they should be put in the MRO, but it's hard to
1074 diagnose what constraint can't be satisfied.
1075*/
1076
1077static void
1078set_mro_error(PyObject *to_merge, int *remain)
1079{
1080 int i, n, off, to_merge_size;
1081 char buf[1000];
1082 PyObject *k, *v;
1083 PyObject *set = PyDict_New();
1084
1085 to_merge_size = PyList_GET_SIZE(to_merge);
1086 for (i = 0; i < to_merge_size; i++) {
1087 PyObject *L = PyList_GET_ITEM(to_merge, i);
1088 if (remain[i] < PyList_GET_SIZE(L)) {
1089 PyObject *c = PyList_GET_ITEM(L, remain[i]);
1090 if (PyDict_SetItem(set, c, Py_None) < 0)
1091 return;
1092 }
1093 }
1094 n = PyDict_Size(set);
1095
Raymond Hettingerf394df42003-04-06 19:13:41 +00001096 off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \
1097consistent method resolution\norder (MRO) for bases");
Guido van Rossum98f33732002-11-25 21:36:54 +00001098 i = 0;
1099 while (PyDict_Next(set, &i, &k, &v) && off < sizeof(buf)) {
1100 PyObject *name = class_name(k);
1101 off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s",
1102 name ? PyString_AS_STRING(name) : "?");
1103 Py_XDECREF(name);
1104 if (--n && off+1 < sizeof(buf)) {
1105 buf[off++] = ',';
1106 buf[off] = '\0';
1107 }
1108 }
1109 PyErr_SetString(PyExc_TypeError, buf);
1110 Py_DECREF(set);
1111}
1112
Tim Petersea7f75d2002-12-07 21:39:16 +00001113static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001114pmerge(PyObject *acc, PyObject* to_merge) {
1115 int i, j, to_merge_size;
1116 int *remain;
1117 int ok, empty_cnt;
Tim Petersea7f75d2002-12-07 21:39:16 +00001118
Guido van Rossum1f121312002-11-14 19:49:16 +00001119 to_merge_size = PyList_GET_SIZE(to_merge);
1120
Guido van Rossum98f33732002-11-25 21:36:54 +00001121 /* remain stores an index into each sublist of to_merge.
1122 remain[i] is the index of the next base in to_merge[i]
1123 that is not included in acc.
1124 */
Guido van Rossum1f121312002-11-14 19:49:16 +00001125 remain = PyMem_MALLOC(SIZEOF_INT*to_merge_size);
1126 if (remain == NULL)
1127 return -1;
1128 for (i = 0; i < to_merge_size; i++)
1129 remain[i] = 0;
1130
1131 again:
1132 empty_cnt = 0;
1133 for (i = 0; i < to_merge_size; i++) {
1134 PyObject *candidate;
Tim Petersea7f75d2002-12-07 21:39:16 +00001135
Guido van Rossum1f121312002-11-14 19:49:16 +00001136 PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
1137
1138 if (remain[i] >= PyList_GET_SIZE(cur_list)) {
1139 empty_cnt++;
1140 continue;
1141 }
1142
Guido van Rossum98f33732002-11-25 21:36:54 +00001143 /* Choose next candidate for MRO.
1144
1145 The input sequences alone can determine the choice.
1146 If not, choose the class which appears in the MRO
1147 of the earliest direct superclass of the new class.
1148 */
1149
Guido van Rossum1f121312002-11-14 19:49:16 +00001150 candidate = PyList_GET_ITEM(cur_list, remain[i]);
1151 for (j = 0; j < to_merge_size; j++) {
1152 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum98f33732002-11-25 21:36:54 +00001153 if (tail_contains(j_lst, remain[j], candidate)) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001154 goto skip; /* continue outer loop */
Guido van Rossum98f33732002-11-25 21:36:54 +00001155 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001156 }
1157 ok = PyList_Append(acc, candidate);
1158 if (ok < 0) {
1159 PyMem_Free(remain);
1160 return -1;
1161 }
1162 for (j = 0; j < to_merge_size; j++) {
1163 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum768158c2002-12-31 16:33:01 +00001164 if (remain[j] < PyList_GET_SIZE(j_lst) &&
1165 PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001166 remain[j]++;
1167 }
1168 }
1169 goto again;
Tim Peters9a6b8d82002-11-14 23:22:33 +00001170 skip: ;
Guido van Rossum1f121312002-11-14 19:49:16 +00001171 }
1172
Guido van Rossum98f33732002-11-25 21:36:54 +00001173 if (empty_cnt == to_merge_size) {
1174 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001175 return 0;
Guido van Rossum98f33732002-11-25 21:36:54 +00001176 }
1177 set_mro_error(to_merge, remain);
1178 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001179 return -1;
1180}
1181
Tim Peters6d6c1a32001-08-02 04:15:00 +00001182static PyObject *
1183mro_implementation(PyTypeObject *type)
1184{
1185 int i, n, ok;
1186 PyObject *bases, *result;
Guido van Rossum1f121312002-11-14 19:49:16 +00001187 PyObject *to_merge, *bases_aslist;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001188
Guido van Rossum63517572002-06-18 16:44:57 +00001189 if(type->tp_dict == NULL) {
1190 if(PyType_Ready(type) < 0)
1191 return NULL;
1192 }
1193
Guido van Rossum98f33732002-11-25 21:36:54 +00001194 /* Find a superclass linearization that honors the constraints
1195 of the explicit lists of bases and the constraints implied by
Tim Petersea7f75d2002-12-07 21:39:16 +00001196 each base class.
Guido van Rossum98f33732002-11-25 21:36:54 +00001197
1198 to_merge is a list of lists, where each list is a superclass
1199 linearization implied by a base class. The last element of
1200 to_merge is the declared list of bases.
1201 */
1202
Tim Peters6d6c1a32001-08-02 04:15:00 +00001203 bases = type->tp_bases;
1204 n = PyTuple_GET_SIZE(bases);
Guido van Rossum1f121312002-11-14 19:49:16 +00001205
1206 to_merge = PyList_New(n+1);
1207 if (to_merge == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001208 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001209
Tim Peters6d6c1a32001-08-02 04:15:00 +00001210 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001211 PyObject *base = PyTuple_GET_ITEM(bases, i);
1212 PyObject *parentMRO;
1213 if (PyType_Check(base))
1214 parentMRO = PySequence_List(
1215 ((PyTypeObject*)base)->tp_mro);
1216 else
1217 parentMRO = classic_mro(base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001218 if (parentMRO == NULL) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001219 Py_DECREF(to_merge);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001220 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001221 }
1222
1223 PyList_SET_ITEM(to_merge, i, parentMRO);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001224 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001225
1226 bases_aslist = PySequence_List(bases);
1227 if (bases_aslist == NULL) {
1228 Py_DECREF(to_merge);
1229 return NULL;
1230 }
Guido van Rossum98f33732002-11-25 21:36:54 +00001231 /* This is just a basic sanity check. */
1232 if (check_duplicates(bases_aslist) < 0) {
1233 Py_DECREF(to_merge);
1234 Py_DECREF(bases_aslist);
1235 return NULL;
1236 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001237 PyList_SET_ITEM(to_merge, n, bases_aslist);
1238
1239 result = Py_BuildValue("[O]", (PyObject *)type);
1240 if (result == NULL) {
1241 Py_DECREF(to_merge);
1242 return NULL;
1243 }
1244
1245 ok = pmerge(result, to_merge);
1246 Py_DECREF(to_merge);
1247 if (ok < 0) {
1248 Py_DECREF(result);
1249 return NULL;
1250 }
1251
Tim Peters6d6c1a32001-08-02 04:15:00 +00001252 return result;
1253}
1254
1255static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001256mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001257{
1258 PyTypeObject *type = (PyTypeObject *)self;
1259
Tim Peters6d6c1a32001-08-02 04:15:00 +00001260 return mro_implementation(type);
1261}
1262
1263static int
1264mro_internal(PyTypeObject *type)
1265{
1266 PyObject *mro, *result, *tuple;
1267
1268 if (type->ob_type == &PyType_Type) {
1269 result = mro_implementation(type);
1270 }
1271 else {
Guido van Rossum60718732001-08-28 17:47:51 +00001272 static PyObject *mro_str;
1273 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001274 if (mro == NULL)
1275 return -1;
1276 result = PyObject_CallObject(mro, NULL);
1277 Py_DECREF(mro);
1278 }
1279 if (result == NULL)
1280 return -1;
1281 tuple = PySequence_Tuple(result);
1282 Py_DECREF(result);
1283 type->tp_mro = tuple;
1284 return 0;
1285}
1286
1287
1288/* Calculate the best base amongst multiple base classes.
1289 This is the first one that's on the path to the "solid base". */
1290
1291static PyTypeObject *
1292best_base(PyObject *bases)
1293{
1294 int i, n;
1295 PyTypeObject *base, *winner, *candidate, *base_i;
Tim Petersa91e9642001-11-14 23:32:33 +00001296 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001297
1298 assert(PyTuple_Check(bases));
1299 n = PyTuple_GET_SIZE(bases);
1300 assert(n > 0);
Tim Petersa91e9642001-11-14 23:32:33 +00001301 base = NULL;
1302 winner = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001303 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001304 base_proto = PyTuple_GET_ITEM(bases, i);
1305 if (PyClass_Check(base_proto))
1306 continue;
1307 if (!PyType_Check(base_proto)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001308 PyErr_SetString(
1309 PyExc_TypeError,
1310 "bases must be types");
1311 return NULL;
1312 }
Tim Petersa91e9642001-11-14 23:32:33 +00001313 base_i = (PyTypeObject *)base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001314 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001315 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001316 return NULL;
1317 }
1318 candidate = solid_base(base_i);
Tim Petersa91e9642001-11-14 23:32:33 +00001319 if (winner == NULL) {
1320 winner = candidate;
1321 base = base_i;
1322 }
1323 else if (PyType_IsSubtype(winner, candidate))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001324 ;
1325 else if (PyType_IsSubtype(candidate, winner)) {
1326 winner = candidate;
1327 base = base_i;
1328 }
1329 else {
1330 PyErr_SetString(
1331 PyExc_TypeError,
1332 "multiple bases have "
1333 "instance lay-out conflict");
1334 return NULL;
1335 }
1336 }
Guido van Rossume54616c2001-12-14 04:19:56 +00001337 if (base == NULL)
1338 PyErr_SetString(PyExc_TypeError,
1339 "a new-style class can't have only classic bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001340 return base;
1341}
1342
1343static int
1344extra_ivars(PyTypeObject *type, PyTypeObject *base)
1345{
Neil Schemenauerc806c882001-08-29 23:54:54 +00001346 size_t t_size = type->tp_basicsize;
1347 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001348
Guido van Rossum9676b222001-08-17 20:32:36 +00001349 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001350 if (type->tp_itemsize || base->tp_itemsize) {
1351 /* If itemsize is involved, stricter rules */
1352 return t_size != b_size ||
1353 type->tp_itemsize != base->tp_itemsize;
1354 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001355 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
1356 type->tp_weaklistoffset + sizeof(PyObject *) == t_size)
1357 t_size -= sizeof(PyObject *);
1358 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
1359 type->tp_dictoffset + sizeof(PyObject *) == t_size)
1360 t_size -= sizeof(PyObject *);
1361
1362 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001363}
1364
1365static PyTypeObject *
1366solid_base(PyTypeObject *type)
1367{
1368 PyTypeObject *base;
1369
1370 if (type->tp_base)
1371 base = solid_base(type->tp_base);
1372 else
1373 base = &PyBaseObject_Type;
1374 if (extra_ivars(type, base))
1375 return type;
1376 else
1377 return base;
1378}
1379
Jeremy Hylton938ace62002-07-17 16:30:39 +00001380static void object_dealloc(PyObject *);
1381static int object_init(PyObject *, PyObject *, PyObject *);
1382static int update_slot(PyTypeObject *, PyObject *);
1383static void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001384
1385static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001386subtype_dict(PyObject *obj, void *context)
1387{
1388 PyObject **dictptr = _PyObject_GetDictPtr(obj);
1389 PyObject *dict;
1390
1391 if (dictptr == NULL) {
1392 PyErr_SetString(PyExc_AttributeError,
1393 "This object has no __dict__");
1394 return NULL;
1395 }
1396 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +00001397 if (dict == NULL)
1398 *dictptr = dict = PyDict_New();
1399 Py_XINCREF(dict);
1400 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001401}
1402
Guido van Rossum6661be32001-10-26 04:26:12 +00001403static int
1404subtype_setdict(PyObject *obj, PyObject *value, void *context)
1405{
1406 PyObject **dictptr = _PyObject_GetDictPtr(obj);
1407 PyObject *dict;
1408
1409 if (dictptr == NULL) {
1410 PyErr_SetString(PyExc_AttributeError,
1411 "This object has no __dict__");
1412 return -1;
1413 }
Guido van Rossumd331cb52001-12-05 19:46:42 +00001414 if (value != NULL && !PyDict_Check(value)) {
Guido van Rossum6661be32001-10-26 04:26:12 +00001415 PyErr_SetString(PyExc_TypeError,
1416 "__dict__ must be set to a dictionary");
1417 return -1;
1418 }
1419 dict = *dictptr;
Guido van Rossumd331cb52001-12-05 19:46:42 +00001420 Py_XINCREF(value);
Guido van Rossum6661be32001-10-26 04:26:12 +00001421 *dictptr = value;
1422 Py_XDECREF(dict);
1423 return 0;
1424}
1425
Guido van Rossumad47da02002-08-12 19:05:44 +00001426static PyObject *
1427subtype_getweakref(PyObject *obj, void *context)
1428{
1429 PyObject **weaklistptr;
1430 PyObject *result;
1431
1432 if (obj->ob_type->tp_weaklistoffset == 0) {
1433 PyErr_SetString(PyExc_AttributeError,
1434 "This object has no __weaklist__");
1435 return NULL;
1436 }
1437 assert(obj->ob_type->tp_weaklistoffset > 0);
1438 assert(obj->ob_type->tp_weaklistoffset + sizeof(PyObject *) <=
Guido van Rossum3747a0f2002-08-12 19:25:08 +00001439 (size_t)(obj->ob_type->tp_basicsize));
Guido van Rossumad47da02002-08-12 19:05:44 +00001440 weaklistptr = (PyObject **)
Guido van Rossum3747a0f2002-08-12 19:25:08 +00001441 ((char *)obj + obj->ob_type->tp_weaklistoffset);
Guido van Rossumad47da02002-08-12 19:05:44 +00001442 if (*weaklistptr == NULL)
1443 result = Py_None;
1444 else
1445 result = *weaklistptr;
1446 Py_INCREF(result);
1447 return result;
1448}
1449
Guido van Rossum373c7412003-01-07 13:41:37 +00001450/* Three variants on the subtype_getsets list. */
1451
1452static PyGetSetDef subtype_getsets_full[] = {
Guido van Rossumad47da02002-08-12 19:05:44 +00001453 {"__dict__", subtype_dict, subtype_setdict,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001454 PyDoc_STR("dictionary for instance variables (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001455 {"__weakref__", subtype_getweakref, NULL,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001456 PyDoc_STR("list of weak references to the object (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001457 {0}
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001458};
1459
Guido van Rossum373c7412003-01-07 13:41:37 +00001460static PyGetSetDef subtype_getsets_dict_only[] = {
1461 {"__dict__", subtype_dict, subtype_setdict,
1462 PyDoc_STR("dictionary for instance variables (if defined)")},
1463 {0}
1464};
1465
1466static PyGetSetDef subtype_getsets_weakref_only[] = {
1467 {"__weakref__", subtype_getweakref, NULL,
1468 PyDoc_STR("list of weak references to the object (if defined)")},
1469 {0}
1470};
1471
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001472static int
1473valid_identifier(PyObject *s)
1474{
Guido van Rossum03013a02002-07-16 14:30:28 +00001475 unsigned char *p;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001476 int i, n;
1477
1478 if (!PyString_Check(s)) {
1479 PyErr_SetString(PyExc_TypeError,
1480 "__slots__ must be strings");
1481 return 0;
1482 }
Guido van Rossum03013a02002-07-16 14:30:28 +00001483 p = (unsigned char *) PyString_AS_STRING(s);
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001484 n = PyString_GET_SIZE(s);
1485 /* We must reject an empty name. As a hack, we bump the
1486 length to 1 so that the loop will balk on the trailing \0. */
1487 if (n == 0)
1488 n = 1;
1489 for (i = 0; i < n; i++, p++) {
1490 if (!(i == 0 ? isalpha(*p) : isalnum(*p)) && *p != '_') {
1491 PyErr_SetString(PyExc_TypeError,
1492 "__slots__ must be identifiers");
1493 return 0;
1494 }
1495 }
1496 return 1;
1497}
1498
Martin v. Löwisd919a592002-10-14 21:07:28 +00001499#ifdef Py_USING_UNICODE
1500/* Replace Unicode objects in slots. */
1501
1502static PyObject *
1503_unicode_to_string(PyObject *slots, int nslots)
1504{
1505 PyObject *tmp = slots;
1506 PyObject *o, *o1;
1507 int i;
1508 intintargfunc copy = slots->ob_type->tp_as_sequence->sq_slice;
1509 for (i = 0; i < nslots; i++) {
1510 if (PyUnicode_Check(o = PyTuple_GET_ITEM(tmp, i))) {
1511 if (tmp == slots) {
1512 tmp = copy(slots, 0, PyTuple_GET_SIZE(slots));
1513 if (tmp == NULL)
1514 return NULL;
1515 }
1516 o1 = _PyUnicode_AsDefaultEncodedString
1517 (o, NULL);
1518 if (o1 == NULL) {
1519 Py_DECREF(tmp);
1520 return 0;
1521 }
1522 Py_INCREF(o1);
1523 Py_DECREF(o);
1524 PyTuple_SET_ITEM(tmp, i, o1);
1525 }
1526 }
1527 return tmp;
1528}
1529#endif
1530
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001531static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001532type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
1533{
1534 PyObject *name, *bases, *dict;
1535 static char *kwlist[] = {"name", "bases", "dict", 0};
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001536 PyObject *slots, *tmp, *newslots;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001537 PyTypeObject *type, *base, *tmptype, *winner;
Guido van Rossume5c691a2003-03-07 15:13:17 +00001538 PyHeapTypeObject *et;
Guido van Rossum6f799372001-09-20 20:46:19 +00001539 PyMemberDef *mp;
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001540 int i, nbases, nslots, slotoffset, add_dict, add_weak;
Guido van Rossumad47da02002-08-12 19:05:44 +00001541 int j, may_add_dict, may_add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001542
Tim Peters3abca122001-10-27 19:37:48 +00001543 assert(args != NULL && PyTuple_Check(args));
1544 assert(kwds == NULL || PyDict_Check(kwds));
1545
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001546 /* Special case: type(x) should return x->ob_type */
Tim Peters3abca122001-10-27 19:37:48 +00001547 {
1548 const int nargs = PyTuple_GET_SIZE(args);
1549 const int nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
1550
1551 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
1552 PyObject *x = PyTuple_GET_ITEM(args, 0);
1553 Py_INCREF(x->ob_type);
1554 return (PyObject *) x->ob_type;
1555 }
1556
1557 /* SF bug 475327 -- if that didn't trigger, we need 3
1558 arguments. but PyArg_ParseTupleAndKeywords below may give
1559 a msg saying type() needs exactly 3. */
1560 if (nargs + nkwds != 3) {
1561 PyErr_SetString(PyExc_TypeError,
1562 "type() takes 1 or 3 arguments");
1563 return NULL;
1564 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001565 }
1566
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001567 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001568 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
1569 &name,
1570 &PyTuple_Type, &bases,
1571 &PyDict_Type, &dict))
1572 return NULL;
1573
1574 /* Determine the proper metatype to deal with this,
1575 and check for metatype conflicts while we're at it.
1576 Note that if some other metatype wins to contract,
1577 it's possible that its instances are not types. */
1578 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001579 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001580 for (i = 0; i < nbases; i++) {
1581 tmp = PyTuple_GET_ITEM(bases, i);
1582 tmptype = tmp->ob_type;
Tim Petersa91e9642001-11-14 23:32:33 +00001583 if (tmptype == &PyClass_Type)
1584 continue; /* Special case classic classes */
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001585 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001586 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001587 if (PyType_IsSubtype(tmptype, winner)) {
1588 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001589 continue;
1590 }
1591 PyErr_SetString(PyExc_TypeError,
Guido van Rossum636688d2003-04-23 12:07:22 +00001592 "metaclass conflict: "
1593 "the metaclass of a derived class "
1594 "must be a (non-strict) subclass "
1595 "of the metaclasses of all its bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001596 return NULL;
1597 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001598 if (winner != metatype) {
1599 if (winner->tp_new != type_new) /* Pass it to the winner */
1600 return winner->tp_new(winner, args, kwds);
1601 metatype = winner;
1602 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001603
1604 /* Adjust for empty tuple bases */
1605 if (nbases == 0) {
1606 bases = Py_BuildValue("(O)", &PyBaseObject_Type);
1607 if (bases == NULL)
1608 return NULL;
1609 nbases = 1;
1610 }
1611 else
1612 Py_INCREF(bases);
1613
1614 /* XXX From here until type is allocated, "return NULL" leaks bases! */
1615
1616 /* Calculate best base, and check that all bases are type objects */
1617 base = best_base(bases);
1618 if (base == NULL)
1619 return NULL;
1620 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
1621 PyErr_Format(PyExc_TypeError,
1622 "type '%.100s' is not an acceptable base type",
1623 base->tp_name);
1624 return NULL;
1625 }
1626
Tim Peters6d6c1a32001-08-02 04:15:00 +00001627 /* Check for a __slots__ sequence variable in dict, and count it */
1628 slots = PyDict_GetItemString(dict, "__slots__");
1629 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +00001630 add_dict = 0;
1631 add_weak = 0;
Guido van Rossumad47da02002-08-12 19:05:44 +00001632 may_add_dict = base->tp_dictoffset == 0;
1633 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
1634 if (slots == NULL) {
1635 if (may_add_dict) {
1636 add_dict++;
1637 }
1638 if (may_add_weak) {
1639 add_weak++;
1640 }
1641 }
1642 else {
1643 /* Have slots */
1644
Tim Peters6d6c1a32001-08-02 04:15:00 +00001645 /* Make it into a tuple */
1646 if (PyString_Check(slots))
1647 slots = Py_BuildValue("(O)", slots);
1648 else
1649 slots = PySequence_Tuple(slots);
1650 if (slots == NULL)
1651 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00001652 assert(PyTuple_Check(slots));
1653
1654 /* Are slots allowed? */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001655 nslots = PyTuple_GET_SIZE(slots);
Jeremy Hylton1c7a0ea2003-07-16 16:08:23 +00001656 if (nslots > 0 && base->tp_itemsize != 0) {
Guido van Rossume5c691a2003-03-07 15:13:17 +00001657 /* for the special case of meta types, allow slots */
Guido van Rossumc4141872001-08-30 04:43:35 +00001658 PyErr_Format(PyExc_TypeError,
1659 "nonempty __slots__ "
1660 "not supported for subtype of '%s'",
1661 base->tp_name);
Guido van Rossumad47da02002-08-12 19:05:44 +00001662 bad_slots:
1663 Py_DECREF(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +00001664 return NULL;
1665 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001666
Martin v. Löwisd919a592002-10-14 21:07:28 +00001667#ifdef Py_USING_UNICODE
1668 tmp = _unicode_to_string(slots, nslots);
Martin v. Löwis13b1a5c2002-10-14 21:11:34 +00001669 if (tmp != slots) {
1670 Py_DECREF(slots);
1671 slots = tmp;
1672 }
Martin v. Löwisd919a592002-10-14 21:07:28 +00001673 if (!tmp)
1674 return NULL;
1675#endif
Guido van Rossumad47da02002-08-12 19:05:44 +00001676 /* Check for valid slot names and two special cases */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001677 for (i = 0; i < nslots; i++) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001678 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
1679 char *s;
1680 if (!valid_identifier(tmp))
1681 goto bad_slots;
1682 assert(PyString_Check(tmp));
1683 s = PyString_AS_STRING(tmp);
1684 if (strcmp(s, "__dict__") == 0) {
1685 if (!may_add_dict || add_dict) {
1686 PyErr_SetString(PyExc_TypeError,
1687 "__dict__ slot disallowed: "
1688 "we already got one");
1689 goto bad_slots;
1690 }
1691 add_dict++;
1692 }
1693 if (strcmp(s, "__weakref__") == 0) {
1694 if (!may_add_weak || add_weak) {
1695 PyErr_SetString(PyExc_TypeError,
1696 "__weakref__ slot disallowed: "
1697 "either we already got one, "
1698 "or __itemsize__ != 0");
1699 goto bad_slots;
1700 }
1701 add_weak++;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001702 }
1703 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001704
Guido van Rossumad47da02002-08-12 19:05:44 +00001705 /* Copy slots into yet another tuple, demangling names */
1706 newslots = PyTuple_New(nslots - add_dict - add_weak);
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001707 if (newslots == NULL)
Guido van Rossumad47da02002-08-12 19:05:44 +00001708 goto bad_slots;
1709 for (i = j = 0; i < nslots; i++) {
1710 char *s;
Guido van Rossum8e829202002-08-16 03:47:49 +00001711 char buffer[256];
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001712 tmp = PyTuple_GET_ITEM(slots, i);
Guido van Rossumad47da02002-08-12 19:05:44 +00001713 s = PyString_AS_STRING(tmp);
1714 if ((add_dict && strcmp(s, "__dict__") == 0) ||
1715 (add_weak && strcmp(s, "__weakref__") == 0))
1716 continue;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001717 if (_Py_Mangle(PyString_AS_STRING(name),
Guido van Rossumad47da02002-08-12 19:05:44 +00001718 PyString_AS_STRING(tmp),
1719 buffer, sizeof(buffer)))
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001720 {
1721 tmp = PyString_FromString(buffer);
1722 } else {
1723 Py_INCREF(tmp);
1724 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001725 PyTuple_SET_ITEM(newslots, j, tmp);
1726 j++;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001727 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001728 assert(j == nslots - add_dict - add_weak);
1729 nslots = j;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001730 Py_DECREF(slots);
1731 slots = newslots;
1732
Guido van Rossumad47da02002-08-12 19:05:44 +00001733 /* Secondary bases may provide weakrefs or dict */
1734 if (nbases > 1 &&
1735 ((may_add_dict && !add_dict) ||
1736 (may_add_weak && !add_weak))) {
1737 for (i = 0; i < nbases; i++) {
1738 tmp = PyTuple_GET_ITEM(bases, i);
1739 if (tmp == (PyObject *)base)
1740 continue; /* Skip primary base */
1741 if (PyClass_Check(tmp)) {
1742 /* Classic base class provides both */
1743 if (may_add_dict && !add_dict)
1744 add_dict++;
1745 if (may_add_weak && !add_weak)
1746 add_weak++;
1747 break;
1748 }
1749 assert(PyType_Check(tmp));
1750 tmptype = (PyTypeObject *)tmp;
1751 if (may_add_dict && !add_dict &&
1752 tmptype->tp_dictoffset != 0)
1753 add_dict++;
1754 if (may_add_weak && !add_weak &&
1755 tmptype->tp_weaklistoffset != 0)
1756 add_weak++;
1757 if (may_add_dict && !add_dict)
1758 continue;
1759 if (may_add_weak && !add_weak)
1760 continue;
1761 /* Nothing more to check */
1762 break;
1763 }
1764 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001765 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001766
1767 /* XXX From here until type is safely allocated,
1768 "return NULL" may leak slots! */
1769
1770 /* Allocate the type object */
1771 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
Guido van Rossumad47da02002-08-12 19:05:44 +00001772 if (type == NULL) {
1773 Py_XDECREF(slots);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001774 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00001775 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001776
1777 /* Keep name and slots alive in the extended type object */
Guido van Rossume5c691a2003-03-07 15:13:17 +00001778 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001779 Py_INCREF(name);
1780 et->name = name;
1781 et->slots = slots;
1782
Guido van Rossumdc91b992001-08-08 22:26:22 +00001783 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001784 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
1785 Py_TPFLAGS_BASETYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00001786 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
1787 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00001788
1789 /* It's a new-style number unless it specifically inherits any
1790 old-style numeric behavior */
1791 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
1792 (base->tp_as_number == NULL))
1793 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
1794
1795 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001796 type->tp_as_number = &et->as_number;
1797 type->tp_as_sequence = &et->as_sequence;
1798 type->tp_as_mapping = &et->as_mapping;
1799 type->tp_as_buffer = &et->as_buffer;
1800 type->tp_name = PyString_AS_STRING(name);
1801
1802 /* Set tp_base and tp_bases */
1803 type->tp_bases = bases;
1804 Py_INCREF(base);
1805 type->tp_base = base;
1806
Guido van Rossum687ae002001-10-15 22:03:32 +00001807 /* Initialize tp_dict from passed-in dict */
1808 type->tp_dict = dict = PyDict_Copy(dict);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001809 if (dict == NULL) {
1810 Py_DECREF(type);
1811 return NULL;
1812 }
1813
Guido van Rossumc3542212001-08-16 09:18:56 +00001814 /* Set __module__ in the dict */
1815 if (PyDict_GetItemString(dict, "__module__") == NULL) {
1816 tmp = PyEval_GetGlobals();
1817 if (tmp != NULL) {
1818 tmp = PyDict_GetItemString(tmp, "__name__");
1819 if (tmp != NULL) {
1820 if (PyDict_SetItemString(dict, "__module__",
1821 tmp) < 0)
1822 return NULL;
1823 }
1824 }
1825 }
1826
Tim Peters2f93e282001-10-04 05:27:00 +00001827 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
Tim Peters24008312002-03-17 18:56:20 +00001828 and is a string. The __doc__ accessor will first look for tp_doc;
1829 if that fails, it will still look into __dict__.
Tim Peters2f93e282001-10-04 05:27:00 +00001830 */
1831 {
1832 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
1833 if (doc != NULL && PyString_Check(doc)) {
1834 const size_t n = (size_t)PyString_GET_SIZE(doc);
Tim Peters59f809d2001-10-04 05:43:02 +00001835 type->tp_doc = (char *)PyObject_MALLOC(n+1);
Tim Peters2f93e282001-10-04 05:27:00 +00001836 if (type->tp_doc == NULL) {
1837 Py_DECREF(type);
1838 return NULL;
1839 }
1840 memcpy(type->tp_doc, PyString_AS_STRING(doc), n+1);
1841 }
1842 }
1843
Tim Peters6d6c1a32001-08-02 04:15:00 +00001844 /* Special-case __new__: if it's a plain function,
1845 make it a static function */
1846 tmp = PyDict_GetItemString(dict, "__new__");
1847 if (tmp != NULL && PyFunction_Check(tmp)) {
1848 tmp = PyStaticMethod_New(tmp);
1849 if (tmp == NULL) {
1850 Py_DECREF(type);
1851 return NULL;
1852 }
1853 PyDict_SetItemString(dict, "__new__", tmp);
1854 Py_DECREF(tmp);
1855 }
1856
1857 /* Add descriptors for custom slots from __slots__, or for __dict__ */
Guido van Rossume5c691a2003-03-07 15:13:17 +00001858 mp = PyHeapType_GET_MEMBERS(et);
Neil Schemenauerc806c882001-08-29 23:54:54 +00001859 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001860 if (slots != NULL) {
1861 for (i = 0; i < nslots; i++, mp++) {
1862 mp->name = PyString_AS_STRING(
1863 PyTuple_GET_ITEM(slots, i));
Guido van Rossum64b206c2001-12-04 17:13:22 +00001864 mp->type = T_OBJECT_EX;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001865 mp->offset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +00001866 if (base->tp_weaklistoffset == 0 &&
Guido van Rossum64b206c2001-12-04 17:13:22 +00001867 strcmp(mp->name, "__weakref__") == 0) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001868 add_weak++;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001869 mp->type = T_OBJECT;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001870 mp->flags = READONLY;
Guido van Rossum9676b222001-08-17 20:32:36 +00001871 type->tp_weaklistoffset = slotoffset;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001872 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001873 slotoffset += sizeof(PyObject *);
1874 }
1875 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001876 if (add_dict) {
1877 if (base->tp_itemsize)
1878 type->tp_dictoffset = -(long)sizeof(PyObject *);
1879 else
1880 type->tp_dictoffset = slotoffset;
1881 slotoffset += sizeof(PyObject *);
1882 }
1883 if (add_weak) {
1884 assert(!base->tp_itemsize);
1885 type->tp_weaklistoffset = slotoffset;
1886 slotoffset += sizeof(PyObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001887 }
1888 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001889 type->tp_itemsize = base->tp_itemsize;
Guido van Rossume5c691a2003-03-07 15:13:17 +00001890 type->tp_members = PyHeapType_GET_MEMBERS(et);
Guido van Rossum373c7412003-01-07 13:41:37 +00001891
1892 if (type->tp_weaklistoffset && type->tp_dictoffset)
1893 type->tp_getset = subtype_getsets_full;
1894 else if (type->tp_weaklistoffset && !type->tp_dictoffset)
1895 type->tp_getset = subtype_getsets_weakref_only;
1896 else if (!type->tp_weaklistoffset && type->tp_dictoffset)
1897 type->tp_getset = subtype_getsets_dict_only;
1898 else
1899 type->tp_getset = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001900
1901 /* Special case some slots */
1902 if (type->tp_dictoffset != 0 || nslots > 0) {
1903 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
1904 type->tp_getattro = PyObject_GenericGetAttr;
1905 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
1906 type->tp_setattro = PyObject_GenericSetAttr;
1907 }
1908 type->tp_dealloc = subtype_dealloc;
1909
Guido van Rossum9475a232001-10-05 20:51:39 +00001910 /* Enable GC unless there are really no instance variables possible */
1911 if (!(type->tp_basicsize == sizeof(PyObject) &&
1912 type->tp_itemsize == 0))
1913 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
1914
Tim Peters6d6c1a32001-08-02 04:15:00 +00001915 /* Always override allocation strategy to use regular heap */
1916 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00001917 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001918 type->tp_free = PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00001919 type->tp_traverse = subtype_traverse;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001920 type->tp_clear = subtype_clear;
Guido van Rossum048eb752001-10-02 21:24:57 +00001921 }
1922 else
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001923 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001924
1925 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001926 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001927 Py_DECREF(type);
1928 return NULL;
1929 }
1930
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001931 /* Put the proper slots in place */
1932 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00001933
Tim Peters6d6c1a32001-08-02 04:15:00 +00001934 return (PyObject *)type;
1935}
1936
1937/* Internal API to look for a name through the MRO.
1938 This returns a borrowed reference, and doesn't set an exception! */
1939PyObject *
1940_PyType_Lookup(PyTypeObject *type, PyObject *name)
1941{
1942 int i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00001943 PyObject *mro, *res, *base, *dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001944
Guido van Rossum687ae002001-10-15 22:03:32 +00001945 /* Look in tp_dict of types in MRO */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001946 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00001947
1948 /* If mro is NULL, the type is either not yet initialized
1949 by PyType_Ready(), or already cleared by type_clear().
1950 Either way the safest thing to do is to return NULL. */
1951 if (mro == NULL)
1952 return NULL;
1953
Tim Peters6d6c1a32001-08-02 04:15:00 +00001954 assert(PyTuple_Check(mro));
1955 n = PyTuple_GET_SIZE(mro);
1956 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001957 base = PyTuple_GET_ITEM(mro, i);
1958 if (PyClass_Check(base))
1959 dict = ((PyClassObject *)base)->cl_dict;
1960 else {
1961 assert(PyType_Check(base));
1962 dict = ((PyTypeObject *)base)->tp_dict;
1963 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001964 assert(dict && PyDict_Check(dict));
1965 res = PyDict_GetItem(dict, name);
1966 if (res != NULL)
1967 return res;
1968 }
1969 return NULL;
1970}
1971
1972/* This is similar to PyObject_GenericGetAttr(),
1973 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
1974static PyObject *
1975type_getattro(PyTypeObject *type, PyObject *name)
1976{
1977 PyTypeObject *metatype = type->ob_type;
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001978 PyObject *meta_attribute, *attribute;
1979 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001980
1981 /* Initialize this type (we'll assume the metatype is initialized) */
1982 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001983 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001984 return NULL;
1985 }
1986
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001987 /* No readable descriptor found yet */
1988 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00001989
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001990 /* Look for the attribute in the metatype */
1991 meta_attribute = _PyType_Lookup(metatype, name);
1992
1993 if (meta_attribute != NULL) {
1994 meta_get = meta_attribute->ob_type->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00001995
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001996 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
1997 /* Data descriptors implement tp_descr_set to intercept
1998 * writes. Assume the attribute is not overridden in
1999 * type's tp_dict (and bases): call the descriptor now.
2000 */
2001 return meta_get(meta_attribute, (PyObject *)type,
2002 (PyObject *)metatype);
2003 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002004 }
2005
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002006 /* No data descriptor found on metatype. Look in tp_dict of this
2007 * type and its bases */
2008 attribute = _PyType_Lookup(type, name);
2009 if (attribute != NULL) {
2010 /* Implement descriptor functionality, if any */
2011 descrgetfunc local_get = attribute->ob_type->tp_descr_get;
2012 if (local_get != NULL) {
2013 /* NULL 2nd argument indicates the descriptor was
2014 * found on the target object itself (or a base) */
2015 return local_get(attribute, (PyObject *)NULL,
2016 (PyObject *)type);
2017 }
Tim Peters34592512002-07-11 06:23:50 +00002018
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002019 Py_INCREF(attribute);
2020 return attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002021 }
2022
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002023 /* No attribute found in local __dict__ (or bases): use the
2024 * descriptor from the metatype, if any */
2025 if (meta_get != NULL)
2026 return meta_get(meta_attribute, (PyObject *)type,
2027 (PyObject *)metatype);
2028
2029 /* If an ordinary attribute was found on the metatype, return it now */
2030 if (meta_attribute != NULL) {
2031 Py_INCREF(meta_attribute);
2032 return meta_attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002033 }
2034
2035 /* Give up */
2036 PyErr_Format(PyExc_AttributeError,
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002037 "type object '%.50s' has no attribute '%.400s'",
2038 type->tp_name, PyString_AS_STRING(name));
Tim Peters6d6c1a32001-08-02 04:15:00 +00002039 return NULL;
2040}
2041
2042static int
2043type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
2044{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002045 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2046 PyErr_Format(
2047 PyExc_TypeError,
2048 "can't set attributes of built-in/extension type '%s'",
2049 type->tp_name);
2050 return -1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002051 }
Guido van Rossum8d24ee92003-03-24 23:49:49 +00002052 /* XXX Example of how I expect this to be used...
2053 if (update_subclasses(type, name, invalidate_cache, NULL) < 0)
2054 return -1;
2055 */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002056 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
2057 return -1;
2058 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002059}
2060
2061static void
2062type_dealloc(PyTypeObject *type)
2063{
Guido van Rossume5c691a2003-03-07 15:13:17 +00002064 PyHeapTypeObject *et;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002065
2066 /* Assert this is a heap-allocated type object */
2067 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002068 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00002069 PyObject_ClearWeakRefs((PyObject *)type);
Guido van Rossume5c691a2003-03-07 15:13:17 +00002070 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002071 Py_XDECREF(type->tp_base);
2072 Py_XDECREF(type->tp_dict);
2073 Py_XDECREF(type->tp_bases);
2074 Py_XDECREF(type->tp_mro);
Guido van Rossum687ae002001-10-15 22:03:32 +00002075 Py_XDECREF(type->tp_cache);
Guido van Rossum1c450732001-10-08 15:18:27 +00002076 Py_XDECREF(type->tp_subclasses);
Neal Norwitzcee5ca02002-07-30 00:42:06 +00002077 PyObject_Free(type->tp_doc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002078 Py_XDECREF(et->name);
2079 Py_XDECREF(et->slots);
2080 type->ob_type->tp_free((PyObject *)type);
2081}
2082
Guido van Rossum1c450732001-10-08 15:18:27 +00002083static PyObject *
2084type_subclasses(PyTypeObject *type, PyObject *args_ignored)
2085{
2086 PyObject *list, *raw, *ref;
2087 int i, n;
2088
2089 list = PyList_New(0);
2090 if (list == NULL)
2091 return NULL;
2092 raw = type->tp_subclasses;
2093 if (raw == NULL)
2094 return list;
2095 assert(PyList_Check(raw));
2096 n = PyList_GET_SIZE(raw);
2097 for (i = 0; i < n; i++) {
2098 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00002099 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00002100 ref = PyWeakref_GET_OBJECT(ref);
2101 if (ref != Py_None) {
2102 if (PyList_Append(list, ref) < 0) {
2103 Py_DECREF(list);
2104 return NULL;
2105 }
2106 }
2107 }
2108 return list;
2109}
2110
Tim Peters6d6c1a32001-08-02 04:15:00 +00002111static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002112 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002113 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
Guido van Rossum1c450732001-10-08 15:18:27 +00002114 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002115 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002116 {0}
2117};
2118
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002119PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002120"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002121"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002122
Guido van Rossum048eb752001-10-02 21:24:57 +00002123static int
2124type_traverse(PyTypeObject *type, visitproc visit, void *arg)
2125{
Guido van Rossum048eb752001-10-02 21:24:57 +00002126 int err;
2127
Guido van Rossuma3862092002-06-10 15:24:42 +00002128 /* Because of type_is_gc(), the collector only calls this
2129 for heaptypes. */
2130 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002131
2132#define VISIT(SLOT) \
2133 if (SLOT) { \
2134 err = visit((PyObject *)(SLOT), arg); \
2135 if (err) \
2136 return err; \
2137 }
2138
2139 VISIT(type->tp_dict);
Guido van Rossum687ae002001-10-15 22:03:32 +00002140 VISIT(type->tp_cache);
Guido van Rossum048eb752001-10-02 21:24:57 +00002141 VISIT(type->tp_mro);
2142 VISIT(type->tp_bases);
2143 VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00002144
2145 /* There's no need to visit type->tp_subclasses or
Guido van Rossume5c691a2003-03-07 15:13:17 +00002146 ((PyHeapTypeObject *)type)->slots, because they can't be involved
Guido van Rossuma3862092002-06-10 15:24:42 +00002147 in cycles; tp_subclasses is a list of weak references,
2148 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00002149
2150#undef VISIT
2151
2152 return 0;
2153}
2154
2155static int
2156type_clear(PyTypeObject *type)
2157{
Guido van Rossum048eb752001-10-02 21:24:57 +00002158 PyObject *tmp;
2159
Guido van Rossuma3862092002-06-10 15:24:42 +00002160 /* Because of type_is_gc(), the collector only calls this
2161 for heaptypes. */
2162 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002163
2164#define CLEAR(SLOT) \
2165 if (SLOT) { \
2166 tmp = (PyObject *)(SLOT); \
2167 SLOT = NULL; \
2168 Py_DECREF(tmp); \
2169 }
2170
Guido van Rossuma3862092002-06-10 15:24:42 +00002171 /* The only field we need to clear is tp_mro, which is part of a
2172 hard cycle (its first element is the class itself) that won't
2173 be broken otherwise (it's a tuple and tuples don't have a
2174 tp_clear handler). None of the other fields need to be
2175 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00002176
Guido van Rossuma3862092002-06-10 15:24:42 +00002177 tp_dict:
2178 It is a dict, so the collector will call its tp_clear.
2179
2180 tp_cache:
2181 Not used; if it were, it would be a dict.
2182
2183 tp_bases, tp_base:
2184 If these are involved in a cycle, there must be at least
2185 one other, mutable object in the cycle, e.g. a base
2186 class's dict; the cycle will be broken that way.
2187
2188 tp_subclasses:
2189 A list of weak references can't be part of a cycle; and
2190 lists have their own tp_clear.
2191
Guido van Rossume5c691a2003-03-07 15:13:17 +00002192 slots (in PyHeapTypeObject):
Guido van Rossuma3862092002-06-10 15:24:42 +00002193 A tuple of strings can't be part of a cycle.
2194 */
2195
2196 CLEAR(type->tp_mro);
Tim Peters2f93e282001-10-04 05:27:00 +00002197
Guido van Rossum048eb752001-10-02 21:24:57 +00002198#undef CLEAR
2199
2200 return 0;
2201}
2202
2203static int
2204type_is_gc(PyTypeObject *type)
2205{
2206 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
2207}
2208
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002209PyTypeObject PyType_Type = {
2210 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002211 0, /* ob_size */
2212 "type", /* tp_name */
Guido van Rossume5c691a2003-03-07 15:13:17 +00002213 sizeof(PyHeapTypeObject), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00002214 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002215 (destructor)type_dealloc, /* tp_dealloc */
2216 0, /* tp_print */
2217 0, /* tp_getattr */
2218 0, /* tp_setattr */
2219 type_compare, /* tp_compare */
2220 (reprfunc)type_repr, /* tp_repr */
2221 0, /* tp_as_number */
2222 0, /* tp_as_sequence */
2223 0, /* tp_as_mapping */
2224 (hashfunc)_Py_HashPointer, /* tp_hash */
2225 (ternaryfunc)type_call, /* tp_call */
2226 0, /* tp_str */
2227 (getattrofunc)type_getattro, /* tp_getattro */
2228 (setattrofunc)type_setattro, /* tp_setattro */
2229 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00002230 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2231 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002232 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00002233 (traverseproc)type_traverse, /* tp_traverse */
2234 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002235 0, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00002236 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002237 0, /* tp_iter */
2238 0, /* tp_iternext */
2239 type_methods, /* tp_methods */
2240 type_members, /* tp_members */
2241 type_getsets, /* tp_getset */
2242 0, /* tp_base */
2243 0, /* tp_dict */
2244 0, /* tp_descr_get */
2245 0, /* tp_descr_set */
2246 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
2247 0, /* tp_init */
2248 0, /* tp_alloc */
2249 type_new, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002250 PyObject_GC_Del, /* tp_free */
Guido van Rossum048eb752001-10-02 21:24:57 +00002251 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002252};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002253
2254
2255/* The base type of all types (eventually)... except itself. */
2256
2257static int
2258object_init(PyObject *self, PyObject *args, PyObject *kwds)
2259{
2260 return 0;
2261}
2262
Guido van Rossum298e4212003-02-13 16:30:16 +00002263/* If we don't have a tp_new for a new-style class, new will use this one.
2264 Therefore this should take no arguments/keywords. However, this new may
2265 also be inherited by objects that define a tp_init but no tp_new. These
2266 objects WILL pass argumets to tp_new, because it gets the same args as
2267 tp_init. So only allow arguments if we aren't using the default init, in
2268 which case we expect init to handle argument parsing. */
2269static PyObject *
2270object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2271{
2272 if (type->tp_init == object_init && (PyTuple_GET_SIZE(args) ||
2273 (kwds && PyDict_Check(kwds) && PyDict_Size(kwds)))) {
2274 PyErr_SetString(PyExc_TypeError,
2275 "default __new__ takes no parameters");
2276 return NULL;
2277 }
2278 return type->tp_alloc(type, 0);
2279}
2280
Tim Peters6d6c1a32001-08-02 04:15:00 +00002281static void
2282object_dealloc(PyObject *self)
2283{
2284 self->ob_type->tp_free(self);
2285}
2286
Guido van Rossum8e248182001-08-12 05:17:56 +00002287static PyObject *
2288object_repr(PyObject *self)
2289{
Guido van Rossum76e69632001-08-16 18:52:43 +00002290 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00002291 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002292
Guido van Rossum76e69632001-08-16 18:52:43 +00002293 type = self->ob_type;
2294 mod = type_module(type, NULL);
2295 if (mod == NULL)
2296 PyErr_Clear();
2297 else if (!PyString_Check(mod)) {
2298 Py_DECREF(mod);
2299 mod = NULL;
2300 }
2301 name = type_name(type, NULL);
2302 if (name == NULL)
2303 return NULL;
2304 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002305 rtn = PyString_FromFormat("<%s.%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002306 PyString_AS_STRING(mod),
2307 PyString_AS_STRING(name),
2308 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002309 else
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002310 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002311 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002312 Py_XDECREF(mod);
2313 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00002314 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002315}
2316
Guido van Rossumb8f63662001-08-15 23:57:02 +00002317static PyObject *
2318object_str(PyObject *self)
2319{
2320 unaryfunc f;
2321
2322 f = self->ob_type->tp_repr;
2323 if (f == NULL)
2324 f = object_repr;
2325 return f(self);
2326}
2327
Guido van Rossum8e248182001-08-12 05:17:56 +00002328static long
2329object_hash(PyObject *self)
2330{
2331 return _Py_HashPointer(self);
2332}
Guido van Rossum8e248182001-08-12 05:17:56 +00002333
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002334static PyObject *
2335object_get_class(PyObject *self, void *closure)
2336{
2337 Py_INCREF(self->ob_type);
2338 return (PyObject *)(self->ob_type);
2339}
2340
2341static int
2342equiv_structs(PyTypeObject *a, PyTypeObject *b)
2343{
2344 return a == b ||
2345 (a != NULL &&
2346 b != NULL &&
2347 a->tp_basicsize == b->tp_basicsize &&
2348 a->tp_itemsize == b->tp_itemsize &&
2349 a->tp_dictoffset == b->tp_dictoffset &&
2350 a->tp_weaklistoffset == b->tp_weaklistoffset &&
2351 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
2352 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
2353}
2354
2355static int
2356same_slots_added(PyTypeObject *a, PyTypeObject *b)
2357{
2358 PyTypeObject *base = a->tp_base;
2359 int size;
2360
2361 if (base != b->tp_base)
2362 return 0;
2363 if (equiv_structs(a, base) && equiv_structs(b, base))
2364 return 1;
2365 size = base->tp_basicsize;
2366 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
2367 size += sizeof(PyObject *);
2368 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
2369 size += sizeof(PyObject *);
2370 return size == a->tp_basicsize && size == b->tp_basicsize;
2371}
2372
2373static int
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002374compatible_for_assignment(PyTypeObject* old, PyTypeObject* new, char* attr)
2375{
2376 PyTypeObject *newbase, *oldbase;
2377
2378 if (new->tp_dealloc != old->tp_dealloc ||
2379 new->tp_free != old->tp_free)
2380 {
2381 PyErr_Format(PyExc_TypeError,
2382 "%s assignment: "
2383 "'%s' deallocator differs from '%s'",
2384 attr,
2385 new->tp_name,
2386 old->tp_name);
2387 return 0;
2388 }
2389 newbase = new;
2390 oldbase = old;
2391 while (equiv_structs(newbase, newbase->tp_base))
2392 newbase = newbase->tp_base;
2393 while (equiv_structs(oldbase, oldbase->tp_base))
2394 oldbase = oldbase->tp_base;
2395 if (newbase != oldbase &&
2396 (newbase->tp_base != oldbase->tp_base ||
2397 !same_slots_added(newbase, oldbase))) {
2398 PyErr_Format(PyExc_TypeError,
2399 "%s assignment: "
2400 "'%s' object layout differs from '%s'",
2401 attr,
2402 new->tp_name,
2403 old->tp_name);
2404 return 0;
2405 }
Tim Petersea7f75d2002-12-07 21:39:16 +00002406
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002407 return 1;
2408}
2409
2410static int
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002411object_set_class(PyObject *self, PyObject *value, void *closure)
2412{
2413 PyTypeObject *old = self->ob_type;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002414 PyTypeObject *new;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002415
Guido van Rossumb6b89422002-04-15 01:03:30 +00002416 if (value == NULL) {
2417 PyErr_SetString(PyExc_TypeError,
2418 "can't delete __class__ attribute");
2419 return -1;
2420 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002421 if (!PyType_Check(value)) {
2422 PyErr_Format(PyExc_TypeError,
2423 "__class__ must be set to new-style class, not '%s' object",
2424 value->ob_type->tp_name);
2425 return -1;
2426 }
2427 new = (PyTypeObject *)value;
Guido van Rossum40af8892002-08-10 05:42:07 +00002428 if (!(new->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
2429 !(old->tp_flags & Py_TPFLAGS_HEAPTYPE))
2430 {
2431 PyErr_Format(PyExc_TypeError,
2432 "__class__ assignment: only for heap types");
2433 return -1;
2434 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002435 if (compatible_for_assignment(new, old, "__class__")) {
2436 Py_INCREF(new);
2437 self->ob_type = new;
2438 Py_DECREF(old);
2439 return 0;
2440 }
2441 else {
Guido van Rossum9ee4b942002-05-24 18:47:47 +00002442 return -1;
2443 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002444}
2445
2446static PyGetSetDef object_getsets[] = {
2447 {"__class__", object_get_class, object_set_class,
Neal Norwitz858e34f2002-08-13 17:18:45 +00002448 PyDoc_STR("the object's class")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002449 {0}
2450};
2451
Guido van Rossumc53f0092003-02-18 22:05:12 +00002452
Guido van Rossum036f9992003-02-21 22:02:54 +00002453/* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
2454 We fall back to helpers in copy_reg for:
2455 - pickle protocols < 2
2456 - calculating the list of slot names (done only once per class)
2457 - the __newobj__ function (which is used as a token but never called)
2458*/
2459
2460static PyObject *
2461import_copy_reg(void)
2462{
2463 static PyObject *copy_reg_str;
Guido van Rossum3926a632001-09-25 16:25:58 +00002464
2465 if (!copy_reg_str) {
2466 copy_reg_str = PyString_InternFromString("copy_reg");
2467 if (copy_reg_str == NULL)
2468 return NULL;
2469 }
Guido van Rossum036f9992003-02-21 22:02:54 +00002470
2471 return PyImport_Import(copy_reg_str);
2472}
2473
2474static PyObject *
2475slotnames(PyObject *cls)
2476{
2477 PyObject *clsdict;
2478 PyObject *copy_reg;
2479 PyObject *slotnames;
2480
2481 if (!PyType_Check(cls)) {
2482 Py_INCREF(Py_None);
2483 return Py_None;
2484 }
2485
2486 clsdict = ((PyTypeObject *)cls)->tp_dict;
2487 slotnames = PyDict_GetItemString(clsdict, "__slotnames__");
2488 if (slotnames != NULL) {
2489 Py_INCREF(slotnames);
2490 return slotnames;
2491 }
2492
2493 copy_reg = import_copy_reg();
2494 if (copy_reg == NULL)
2495 return NULL;
2496
2497 slotnames = PyObject_CallMethod(copy_reg, "_slotnames", "O", cls);
2498 Py_DECREF(copy_reg);
2499 if (slotnames != NULL &&
2500 slotnames != Py_None &&
2501 !PyList_Check(slotnames))
2502 {
2503 PyErr_SetString(PyExc_TypeError,
2504 "copy_reg._slotnames didn't return a list or None");
2505 Py_DECREF(slotnames);
2506 slotnames = NULL;
2507 }
2508
2509 return slotnames;
2510}
2511
2512static PyObject *
2513reduce_2(PyObject *obj)
2514{
2515 PyObject *cls, *getnewargs;
2516 PyObject *args = NULL, *args2 = NULL;
2517 PyObject *getstate = NULL, *state = NULL, *names = NULL;
2518 PyObject *slots = NULL, *listitems = NULL, *dictitems = NULL;
2519 PyObject *copy_reg = NULL, *newobj = NULL, *res = NULL;
2520 int i, n;
2521
2522 cls = PyObject_GetAttrString(obj, "__class__");
2523 if (cls == NULL)
2524 return NULL;
2525
2526 getnewargs = PyObject_GetAttrString(obj, "__getnewargs__");
2527 if (getnewargs != NULL) {
2528 args = PyObject_CallObject(getnewargs, NULL);
2529 Py_DECREF(getnewargs);
2530 if (args != NULL && !PyTuple_Check(args)) {
2531 PyErr_SetString(PyExc_TypeError,
2532 "__getnewargs__ should return a tuple");
2533 goto end;
2534 }
2535 }
2536 else {
2537 PyErr_Clear();
2538 args = PyTuple_New(0);
2539 }
2540 if (args == NULL)
2541 goto end;
2542
2543 getstate = PyObject_GetAttrString(obj, "__getstate__");
2544 if (getstate != NULL) {
2545 state = PyObject_CallObject(getstate, NULL);
2546 Py_DECREF(getstate);
Neal Norwitze2fdc612003-06-08 13:19:58 +00002547 if (state == NULL)
2548 goto end;
Guido van Rossum036f9992003-02-21 22:02:54 +00002549 }
2550 else {
2551 state = PyObject_GetAttrString(obj, "__dict__");
2552 if (state == NULL) {
2553 PyErr_Clear();
2554 state = Py_None;
2555 Py_INCREF(state);
2556 }
2557 names = slotnames(cls);
2558 if (names == NULL)
2559 goto end;
2560 if (names != Py_None) {
2561 assert(PyList_Check(names));
2562 slots = PyDict_New();
2563 if (slots == NULL)
2564 goto end;
2565 n = 0;
2566 /* Can't pre-compute the list size; the list
2567 is stored on the class so accessible to other
2568 threads, which may be run by DECREF */
2569 for (i = 0; i < PyList_GET_SIZE(names); i++) {
2570 PyObject *name, *value;
2571 name = PyList_GET_ITEM(names, i);
2572 value = PyObject_GetAttr(obj, name);
2573 if (value == NULL)
2574 PyErr_Clear();
2575 else {
2576 int err = PyDict_SetItem(slots, name,
2577 value);
2578 Py_DECREF(value);
2579 if (err)
2580 goto end;
2581 n++;
2582 }
2583 }
2584 if (n) {
2585 state = Py_BuildValue("(NO)", state, slots);
2586 if (state == NULL)
2587 goto end;
2588 }
2589 }
2590 }
2591
2592 if (!PyList_Check(obj)) {
2593 listitems = Py_None;
2594 Py_INCREF(listitems);
2595 }
2596 else {
2597 listitems = PyObject_GetIter(obj);
2598 if (listitems == NULL)
2599 goto end;
2600 }
2601
2602 if (!PyDict_Check(obj)) {
2603 dictitems = Py_None;
2604 Py_INCREF(dictitems);
2605 }
2606 else {
2607 dictitems = PyObject_CallMethod(obj, "iteritems", "");
2608 if (dictitems == NULL)
2609 goto end;
2610 }
2611
2612 copy_reg = import_copy_reg();
2613 if (copy_reg == NULL)
2614 goto end;
2615 newobj = PyObject_GetAttrString(copy_reg, "__newobj__");
2616 if (newobj == NULL)
2617 goto end;
2618
2619 n = PyTuple_GET_SIZE(args);
2620 args2 = PyTuple_New(n+1);
2621 if (args2 == NULL)
2622 goto end;
2623 PyTuple_SET_ITEM(args2, 0, cls);
2624 cls = NULL;
2625 for (i = 0; i < n; i++) {
2626 PyObject *v = PyTuple_GET_ITEM(args, i);
2627 Py_INCREF(v);
2628 PyTuple_SET_ITEM(args2, i+1, v);
2629 }
2630
2631 res = Py_BuildValue("(OOOOO)",
2632 newobj, args2, state, listitems, dictitems);
2633
2634 end:
2635 Py_XDECREF(cls);
2636 Py_XDECREF(args);
2637 Py_XDECREF(args2);
Jeremy Hyltond06483c2003-04-09 21:01:42 +00002638 Py_XDECREF(slots);
Guido van Rossum036f9992003-02-21 22:02:54 +00002639 Py_XDECREF(state);
2640 Py_XDECREF(names);
2641 Py_XDECREF(listitems);
2642 Py_XDECREF(dictitems);
2643 Py_XDECREF(copy_reg);
2644 Py_XDECREF(newobj);
2645 return res;
2646}
2647
2648static PyObject *
2649object_reduce_ex(PyObject *self, PyObject *args)
2650{
2651 /* Call copy_reg._reduce_ex(self, proto) */
2652 PyObject *reduce, *copy_reg, *res;
2653 int proto = 0;
2654
2655 if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
2656 return NULL;
2657
2658 reduce = PyObject_GetAttrString(self, "__reduce__");
2659 if (reduce == NULL)
2660 PyErr_Clear();
2661 else {
2662 PyObject *cls, *clsreduce, *objreduce;
2663 int override;
2664 cls = PyObject_GetAttrString(self, "__class__");
2665 if (cls == NULL) {
2666 Py_DECREF(reduce);
2667 return NULL;
2668 }
2669 clsreduce = PyObject_GetAttrString(cls, "__reduce__");
2670 Py_DECREF(cls);
2671 if (clsreduce == NULL) {
2672 Py_DECREF(reduce);
2673 return NULL;
2674 }
2675 objreduce = PyDict_GetItemString(PyBaseObject_Type.tp_dict,
2676 "__reduce__");
2677 override = (clsreduce != objreduce);
2678 Py_DECREF(clsreduce);
2679 if (override) {
2680 res = PyObject_CallObject(reduce, NULL);
2681 Py_DECREF(reduce);
2682 return res;
2683 }
2684 else
2685 Py_DECREF(reduce);
2686 }
2687
2688 if (proto >= 2)
2689 return reduce_2(self);
2690
2691 copy_reg = import_copy_reg();
Guido van Rossum3926a632001-09-25 16:25:58 +00002692 if (!copy_reg)
2693 return NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00002694
Guido van Rossumc53f0092003-02-18 22:05:12 +00002695 res = PyEval_CallMethod(copy_reg, "_reduce_ex", "(Oi)", self, proto);
Guido van Rossum3926a632001-09-25 16:25:58 +00002696 Py_DECREF(copy_reg);
Guido van Rossum036f9992003-02-21 22:02:54 +00002697
Guido van Rossum3926a632001-09-25 16:25:58 +00002698 return res;
2699}
2700
2701static PyMethodDef object_methods[] = {
Guido van Rossumc53f0092003-02-18 22:05:12 +00002702 {"__reduce_ex__", object_reduce_ex, METH_VARARGS,
2703 PyDoc_STR("helper for pickle")},
2704 {"__reduce__", object_reduce_ex, METH_VARARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002705 PyDoc_STR("helper for pickle")},
Guido van Rossum3926a632001-09-25 16:25:58 +00002706 {0}
2707};
2708
Guido van Rossum036f9992003-02-21 22:02:54 +00002709
Tim Peters6d6c1a32001-08-02 04:15:00 +00002710PyTypeObject PyBaseObject_Type = {
2711 PyObject_HEAD_INIT(&PyType_Type)
2712 0, /* ob_size */
2713 "object", /* tp_name */
2714 sizeof(PyObject), /* tp_basicsize */
2715 0, /* tp_itemsize */
2716 (destructor)object_dealloc, /* tp_dealloc */
2717 0, /* tp_print */
2718 0, /* tp_getattr */
2719 0, /* tp_setattr */
2720 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002721 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002722 0, /* tp_as_number */
2723 0, /* tp_as_sequence */
2724 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002725 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002726 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002727 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002728 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002729 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002730 0, /* tp_as_buffer */
2731 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002732 PyDoc_STR("The most base type"), /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002733 0, /* tp_traverse */
2734 0, /* tp_clear */
2735 0, /* tp_richcompare */
2736 0, /* tp_weaklistoffset */
2737 0, /* tp_iter */
2738 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00002739 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002740 0, /* tp_members */
2741 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002742 0, /* tp_base */
2743 0, /* tp_dict */
2744 0, /* tp_descr_get */
2745 0, /* tp_descr_set */
2746 0, /* tp_dictoffset */
2747 object_init, /* tp_init */
2748 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossum298e4212003-02-13 16:30:16 +00002749 object_new, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002750 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002751};
2752
2753
2754/* Initialize the __dict__ in a type object */
2755
2756static int
2757add_methods(PyTypeObject *type, PyMethodDef *meth)
2758{
Guido van Rossum687ae002001-10-15 22:03:32 +00002759 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002760
2761 for (; meth->ml_name != NULL; meth++) {
2762 PyObject *descr;
2763 if (PyDict_GetItemString(dict, meth->ml_name))
2764 continue;
Fred Drake7bf97152002-03-28 05:33:33 +00002765 if (meth->ml_flags & METH_CLASS) {
2766 if (meth->ml_flags & METH_STATIC) {
2767 PyErr_SetString(PyExc_ValueError,
2768 "method cannot be both class and static");
2769 return -1;
2770 }
Tim Petersbca1cbc2002-12-09 22:56:13 +00002771 descr = PyDescr_NewClassMethod(type, meth);
Fred Drake7bf97152002-03-28 05:33:33 +00002772 }
2773 else if (meth->ml_flags & METH_STATIC) {
Guido van Rossum9af48ff2003-02-11 17:12:46 +00002774 PyObject *cfunc = PyCFunction_New(meth, NULL);
2775 if (cfunc == NULL)
2776 return -1;
2777 descr = PyStaticMethod_New(cfunc);
2778 Py_DECREF(cfunc);
Fred Drake7bf97152002-03-28 05:33:33 +00002779 }
2780 else {
2781 descr = PyDescr_NewMethod(type, meth);
2782 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002783 if (descr == NULL)
2784 return -1;
Fred Drake7bf97152002-03-28 05:33:33 +00002785 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002786 return -1;
2787 Py_DECREF(descr);
2788 }
2789 return 0;
2790}
2791
2792static int
Guido van Rossum6f799372001-09-20 20:46:19 +00002793add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002794{
Guido van Rossum687ae002001-10-15 22:03:32 +00002795 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002796
2797 for (; memb->name != NULL; memb++) {
2798 PyObject *descr;
2799 if (PyDict_GetItemString(dict, memb->name))
2800 continue;
2801 descr = PyDescr_NewMember(type, memb);
2802 if (descr == NULL)
2803 return -1;
2804 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
2805 return -1;
2806 Py_DECREF(descr);
2807 }
2808 return 0;
2809}
2810
2811static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00002812add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002813{
Guido van Rossum687ae002001-10-15 22:03:32 +00002814 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002815
2816 for (; gsp->name != NULL; gsp++) {
2817 PyObject *descr;
2818 if (PyDict_GetItemString(dict, gsp->name))
2819 continue;
2820 descr = PyDescr_NewGetSet(type, gsp);
2821
2822 if (descr == NULL)
2823 return -1;
2824 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
2825 return -1;
2826 Py_DECREF(descr);
2827 }
2828 return 0;
2829}
2830
Guido van Rossum13d52f02001-08-10 21:24:08 +00002831static void
2832inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002833{
2834 int oldsize, newsize;
2835
Guido van Rossum13d52f02001-08-10 21:24:08 +00002836 /* Special flag magic */
2837 if (!type->tp_as_buffer && base->tp_as_buffer) {
2838 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
2839 type->tp_flags |=
2840 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
2841 }
2842 if (!type->tp_as_sequence && base->tp_as_sequence) {
2843 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
2844 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
2845 }
2846 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
2847 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
2848 if ((!type->tp_as_number && base->tp_as_number) ||
2849 (!type->tp_as_sequence && base->tp_as_sequence)) {
2850 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
2851 if (!type->tp_as_number && !type->tp_as_sequence) {
2852 type->tp_flags |= base->tp_flags &
2853 Py_TPFLAGS_HAVE_INPLACEOPS;
2854 }
2855 }
2856 /* Wow */
2857 }
2858 if (!type->tp_as_number && base->tp_as_number) {
2859 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
2860 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
2861 }
2862
2863 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00002864 oldsize = base->tp_basicsize;
2865 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
2866 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
2867 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00002868 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
2869 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00002870 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00002871 if (type->tp_traverse == NULL)
2872 type->tp_traverse = base->tp_traverse;
2873 if (type->tp_clear == NULL)
2874 type->tp_clear = base->tp_clear;
2875 }
2876 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
Guido van Rossumf884b742001-12-17 17:14:22 +00002877 /* The condition below could use some explanation.
2878 It appears that tp_new is not inherited for static types
2879 whose base class is 'object'; this seems to be a precaution
2880 so that old extension types don't suddenly become
2881 callable (object.__new__ wouldn't insure the invariants
2882 that the extension type's own factory function ensures).
2883 Heap types, of course, are under our control, so they do
2884 inherit tp_new; static extension types that specify some
2885 other built-in type as the default are considered
2886 new-style-aware so they also inherit object.__new__. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002887 if (base != &PyBaseObject_Type ||
2888 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2889 if (type->tp_new == NULL)
2890 type->tp_new = base->tp_new;
2891 }
2892 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00002893 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00002894
2895 /* Copy other non-function slots */
2896
2897#undef COPYVAL
2898#define COPYVAL(SLOT) \
2899 if (type->SLOT == 0) type->SLOT = base->SLOT
2900
2901 COPYVAL(tp_itemsize);
2902 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
2903 COPYVAL(tp_weaklistoffset);
2904 }
2905 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2906 COPYVAL(tp_dictoffset);
2907 }
Guido van Rossum13d52f02001-08-10 21:24:08 +00002908}
2909
2910static void
2911inherit_slots(PyTypeObject *type, PyTypeObject *base)
2912{
2913 PyTypeObject *basebase;
2914
2915#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00002916#undef COPYSLOT
2917#undef COPYNUM
2918#undef COPYSEQ
2919#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00002920#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00002921
2922#define SLOTDEFINED(SLOT) \
2923 (base->SLOT != 0 && \
2924 (basebase == NULL || base->SLOT != basebase->SLOT))
2925
Tim Peters6d6c1a32001-08-02 04:15:00 +00002926#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00002927 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00002928
2929#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
2930#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
2931#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00002932#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002933
Guido van Rossum13d52f02001-08-10 21:24:08 +00002934 /* This won't inherit indirect slots (from tp_as_number etc.)
2935 if type doesn't provide the space. */
2936
2937 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
2938 basebase = base->tp_base;
2939 if (basebase->tp_as_number == NULL)
2940 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002941 COPYNUM(nb_add);
2942 COPYNUM(nb_subtract);
2943 COPYNUM(nb_multiply);
2944 COPYNUM(nb_divide);
2945 COPYNUM(nb_remainder);
2946 COPYNUM(nb_divmod);
2947 COPYNUM(nb_power);
2948 COPYNUM(nb_negative);
2949 COPYNUM(nb_positive);
2950 COPYNUM(nb_absolute);
2951 COPYNUM(nb_nonzero);
2952 COPYNUM(nb_invert);
2953 COPYNUM(nb_lshift);
2954 COPYNUM(nb_rshift);
2955 COPYNUM(nb_and);
2956 COPYNUM(nb_xor);
2957 COPYNUM(nb_or);
2958 COPYNUM(nb_coerce);
2959 COPYNUM(nb_int);
2960 COPYNUM(nb_long);
2961 COPYNUM(nb_float);
2962 COPYNUM(nb_oct);
2963 COPYNUM(nb_hex);
2964 COPYNUM(nb_inplace_add);
2965 COPYNUM(nb_inplace_subtract);
2966 COPYNUM(nb_inplace_multiply);
2967 COPYNUM(nb_inplace_divide);
2968 COPYNUM(nb_inplace_remainder);
2969 COPYNUM(nb_inplace_power);
2970 COPYNUM(nb_inplace_lshift);
2971 COPYNUM(nb_inplace_rshift);
2972 COPYNUM(nb_inplace_and);
2973 COPYNUM(nb_inplace_xor);
2974 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00002975 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
2976 COPYNUM(nb_true_divide);
2977 COPYNUM(nb_floor_divide);
2978 COPYNUM(nb_inplace_true_divide);
2979 COPYNUM(nb_inplace_floor_divide);
2980 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002981 }
2982
Guido van Rossum13d52f02001-08-10 21:24:08 +00002983 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
2984 basebase = base->tp_base;
2985 if (basebase->tp_as_sequence == NULL)
2986 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002987 COPYSEQ(sq_length);
2988 COPYSEQ(sq_concat);
2989 COPYSEQ(sq_repeat);
2990 COPYSEQ(sq_item);
2991 COPYSEQ(sq_slice);
2992 COPYSEQ(sq_ass_item);
2993 COPYSEQ(sq_ass_slice);
2994 COPYSEQ(sq_contains);
2995 COPYSEQ(sq_inplace_concat);
2996 COPYSEQ(sq_inplace_repeat);
2997 }
2998
Guido van Rossum13d52f02001-08-10 21:24:08 +00002999 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
3000 basebase = base->tp_base;
3001 if (basebase->tp_as_mapping == NULL)
3002 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003003 COPYMAP(mp_length);
3004 COPYMAP(mp_subscript);
3005 COPYMAP(mp_ass_subscript);
3006 }
3007
Tim Petersfc57ccb2001-10-12 02:38:24 +00003008 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
3009 basebase = base->tp_base;
3010 if (basebase->tp_as_buffer == NULL)
3011 basebase = NULL;
3012 COPYBUF(bf_getreadbuffer);
3013 COPYBUF(bf_getwritebuffer);
3014 COPYBUF(bf_getsegcount);
3015 COPYBUF(bf_getcharbuffer);
3016 }
3017
Guido van Rossum13d52f02001-08-10 21:24:08 +00003018 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003019
Tim Peters6d6c1a32001-08-02 04:15:00 +00003020 COPYSLOT(tp_dealloc);
3021 COPYSLOT(tp_print);
3022 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
3023 type->tp_getattr = base->tp_getattr;
3024 type->tp_getattro = base->tp_getattro;
3025 }
3026 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
3027 type->tp_setattr = base->tp_setattr;
3028 type->tp_setattro = base->tp_setattro;
3029 }
3030 /* tp_compare see tp_richcompare */
3031 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003032 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003033 COPYSLOT(tp_call);
3034 COPYSLOT(tp_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003035 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003036 if (type->tp_compare == NULL &&
3037 type->tp_richcompare == NULL &&
3038 type->tp_hash == NULL)
3039 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003040 type->tp_compare = base->tp_compare;
3041 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003042 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003043 }
3044 }
3045 else {
3046 COPYSLOT(tp_compare);
3047 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003048 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
3049 COPYSLOT(tp_iter);
3050 COPYSLOT(tp_iternext);
3051 }
3052 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
3053 COPYSLOT(tp_descr_get);
3054 COPYSLOT(tp_descr_set);
3055 COPYSLOT(tp_dictoffset);
3056 COPYSLOT(tp_init);
3057 COPYSLOT(tp_alloc);
Guido van Rossumcc8fe042002-04-05 17:10:16 +00003058 COPYSLOT(tp_is_gc);
Tim Peters3cfe7542003-05-21 21:29:48 +00003059 if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) ==
3060 (base->tp_flags & Py_TPFLAGS_HAVE_GC)) {
3061 /* They agree about gc. */
3062 COPYSLOT(tp_free);
3063 }
3064 else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3065 type->tp_free == NULL &&
3066 base->tp_free == _PyObject_Del) {
3067 /* A bit of magic to plug in the correct default
3068 * tp_free function when a derived class adds gc,
3069 * didn't define tp_free, and the base uses the
3070 * default non-gc tp_free.
3071 */
3072 type->tp_free = PyObject_GC_Del;
3073 }
3074 /* else they didn't agree about gc, and there isn't something
3075 * obvious to be done -- the type is on its own.
3076 */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003077 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003078}
3079
Jeremy Hylton938ace62002-07-17 16:30:39 +00003080static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00003081
Tim Peters6d6c1a32001-08-02 04:15:00 +00003082int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00003083PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003084{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003085 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003086 PyTypeObject *base;
3087 int i, n;
3088
Guido van Rossumcab05802002-06-10 15:29:03 +00003089 if (type->tp_flags & Py_TPFLAGS_READY) {
3090 assert(type->tp_dict != NULL);
Guido van Rossumd614f972001-08-10 17:39:49 +00003091 return 0;
Guido van Rossumcab05802002-06-10 15:29:03 +00003092 }
Guido van Rossumd614f972001-08-10 17:39:49 +00003093 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00003094
3095 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003096
Tim Peters36eb4df2003-03-23 03:33:13 +00003097#ifdef Py_TRACE_REFS
3098 /* PyType_Ready is the closest thing we have to a choke point
3099 * for type objects, so is the best place I can think of to try
3100 * to get type objects into the doubly-linked list of all objects.
3101 * Still, not all type objects go thru PyType_Ready.
3102 */
Tim Peters7571a0f2003-03-23 17:52:28 +00003103 _Py_AddToAllObjects((PyObject *)type, 0);
Tim Peters36eb4df2003-03-23 03:33:13 +00003104#endif
3105
Tim Peters6d6c1a32001-08-02 04:15:00 +00003106 /* Initialize tp_base (defaults to BaseObject unless that's us) */
3107 base = type->tp_base;
3108 if (base == NULL && type != &PyBaseObject_Type)
3109 base = type->tp_base = &PyBaseObject_Type;
3110
Guido van Rossum323a9cf2002-08-14 17:26:30 +00003111 /* Initialize the base class */
3112 if (base && base->tp_dict == NULL) {
3113 if (PyType_Ready(base) < 0)
3114 goto error;
3115 }
3116
Guido van Rossum0986d822002-04-08 01:38:42 +00003117 /* Initialize ob_type if NULL. This means extensions that want to be
3118 compilable separately on Windows can call PyType_Ready() instead of
3119 initializing the ob_type field of their type objects. */
3120 if (type->ob_type == NULL)
3121 type->ob_type = base->ob_type;
3122
Tim Peters6d6c1a32001-08-02 04:15:00 +00003123 /* Initialize tp_bases */
3124 bases = type->tp_bases;
3125 if (bases == NULL) {
3126 if (base == NULL)
3127 bases = PyTuple_New(0);
3128 else
3129 bases = Py_BuildValue("(O)", base);
3130 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003131 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003132 type->tp_bases = bases;
3133 }
3134
Guido van Rossum687ae002001-10-15 22:03:32 +00003135 /* Initialize tp_dict */
3136 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003137 if (dict == NULL) {
3138 dict = PyDict_New();
3139 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003140 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00003141 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003142 }
3143
Guido van Rossum687ae002001-10-15 22:03:32 +00003144 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003145 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003146 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003147 if (type->tp_methods != NULL) {
3148 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003149 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003150 }
3151 if (type->tp_members != NULL) {
3152 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003153 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003154 }
3155 if (type->tp_getset != NULL) {
3156 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003157 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003158 }
3159
Tim Peters6d6c1a32001-08-02 04:15:00 +00003160 /* Calculate method resolution order */
3161 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00003162 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003163 }
3164
Guido van Rossum13d52f02001-08-10 21:24:08 +00003165 /* Inherit special flags from dominant base */
3166 if (type->tp_base != NULL)
3167 inherit_special(type, type->tp_base);
3168
Tim Peters6d6c1a32001-08-02 04:15:00 +00003169 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003170 bases = type->tp_mro;
3171 assert(bases != NULL);
3172 assert(PyTuple_Check(bases));
3173 n = PyTuple_GET_SIZE(bases);
3174 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003175 PyObject *b = PyTuple_GET_ITEM(bases, i);
3176 if (PyType_Check(b))
3177 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003178 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003179
Tim Peters3cfe7542003-05-21 21:29:48 +00003180 /* Sanity check for tp_free. */
3181 if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) &&
3182 (type->tp_free == NULL || type->tp_free == PyObject_Del)) {
3183 /* This base class needs to call tp_free, but doesn't have
3184 * one, or its tp_free is for non-gc'ed objects.
3185 */
3186 PyErr_Format(PyExc_TypeError, "type '%.100s' participates in "
3187 "gc and is a base type but has inappropriate "
3188 "tp_free slot",
3189 type->tp_name);
3190 goto error;
3191 }
3192
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003193 /* if the type dictionary doesn't contain a __doc__, set it from
3194 the tp_doc slot.
3195 */
3196 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
3197 if (type->tp_doc != NULL) {
3198 PyObject *doc = PyString_FromString(type->tp_doc);
3199 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
3200 Py_DECREF(doc);
3201 } else {
Guido van Rossumd4641072002-04-03 02:13:37 +00003202 PyDict_SetItemString(type->tp_dict,
3203 "__doc__", Py_None);
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003204 }
3205 }
3206
Guido van Rossum13d52f02001-08-10 21:24:08 +00003207 /* Some more special stuff */
3208 base = type->tp_base;
3209 if (base != NULL) {
3210 if (type->tp_as_number == NULL)
3211 type->tp_as_number = base->tp_as_number;
3212 if (type->tp_as_sequence == NULL)
3213 type->tp_as_sequence = base->tp_as_sequence;
3214 if (type->tp_as_mapping == NULL)
3215 type->tp_as_mapping = base->tp_as_mapping;
Guido van Rossumeea47182003-02-11 20:39:59 +00003216 if (type->tp_as_buffer == NULL)
3217 type->tp_as_buffer = base->tp_as_buffer;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003218 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003219
Guido van Rossum1c450732001-10-08 15:18:27 +00003220 /* Link into each base class's list of subclasses */
3221 bases = type->tp_bases;
3222 n = PyTuple_GET_SIZE(bases);
3223 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003224 PyObject *b = PyTuple_GET_ITEM(bases, i);
3225 if (PyType_Check(b) &&
3226 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00003227 goto error;
3228 }
3229
Guido van Rossum13d52f02001-08-10 21:24:08 +00003230 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00003231 assert(type->tp_dict != NULL);
3232 type->tp_flags =
3233 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003234 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00003235
3236 error:
3237 type->tp_flags &= ~Py_TPFLAGS_READYING;
3238 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003239}
3240
Guido van Rossum1c450732001-10-08 15:18:27 +00003241static int
3242add_subclass(PyTypeObject *base, PyTypeObject *type)
3243{
3244 int i;
3245 PyObject *list, *ref, *new;
3246
3247 list = base->tp_subclasses;
3248 if (list == NULL) {
3249 base->tp_subclasses = list = PyList_New(0);
3250 if (list == NULL)
3251 return -1;
3252 }
3253 assert(PyList_Check(list));
3254 new = PyWeakref_NewRef((PyObject *)type, NULL);
3255 i = PyList_GET_SIZE(list);
3256 while (--i >= 0) {
3257 ref = PyList_GET_ITEM(list, i);
3258 assert(PyWeakref_CheckRef(ref));
Guido van Rossum3930bc32002-10-18 13:51:49 +00003259 if (PyWeakref_GET_OBJECT(ref) == Py_None)
3260 return PyList_SetItem(list, i, new);
Guido van Rossum1c450732001-10-08 15:18:27 +00003261 }
3262 i = PyList_Append(list, new);
3263 Py_DECREF(new);
3264 return i;
3265}
3266
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003267static void
3268remove_subclass(PyTypeObject *base, PyTypeObject *type)
3269{
3270 int i;
3271 PyObject *list, *ref;
3272
3273 list = base->tp_subclasses;
3274 if (list == NULL) {
3275 return;
3276 }
3277 assert(PyList_Check(list));
3278 i = PyList_GET_SIZE(list);
3279 while (--i >= 0) {
3280 ref = PyList_GET_ITEM(list, i);
3281 assert(PyWeakref_CheckRef(ref));
3282 if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
3283 /* this can't fail, right? */
3284 PySequence_DelItem(list, i);
3285 return;
3286 }
3287 }
3288}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003289
3290/* Generic wrappers for overloadable 'operators' such as __getitem__ */
3291
3292/* There's a wrapper *function* for each distinct function typedef used
3293 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
3294 wrapper *table* for each distinct operation (e.g. __len__, __add__).
3295 Most tables have only one entry; the tables for binary operators have two
3296 entries, one regular and one with reversed arguments. */
3297
3298static PyObject *
3299wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
3300{
3301 inquiry func = (inquiry)wrapped;
3302 int res;
3303
3304 if (!PyArg_ParseTuple(args, ""))
3305 return NULL;
3306 res = (*func)(self);
3307 if (res == -1 && PyErr_Occurred())
3308 return NULL;
3309 return PyInt_FromLong((long)res);
3310}
3311
Tim Peters6d6c1a32001-08-02 04:15:00 +00003312static PyObject *
3313wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
3314{
3315 binaryfunc func = (binaryfunc)wrapped;
3316 PyObject *other;
3317
3318 if (!PyArg_ParseTuple(args, "O", &other))
3319 return NULL;
3320 return (*func)(self, other);
3321}
3322
3323static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003324wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
3325{
3326 binaryfunc func = (binaryfunc)wrapped;
3327 PyObject *other;
3328
3329 if (!PyArg_ParseTuple(args, "O", &other))
3330 return NULL;
3331 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003332 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003333 Py_INCREF(Py_NotImplemented);
3334 return Py_NotImplemented;
3335 }
3336 return (*func)(self, other);
3337}
3338
3339static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003340wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3341{
3342 binaryfunc func = (binaryfunc)wrapped;
3343 PyObject *other;
3344
3345 if (!PyArg_ParseTuple(args, "O", &other))
3346 return NULL;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003347 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003348 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003349 Py_INCREF(Py_NotImplemented);
3350 return Py_NotImplemented;
3351 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003352 return (*func)(other, self);
3353}
3354
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003355static PyObject *
3356wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
3357{
3358 coercion func = (coercion)wrapped;
3359 PyObject *other, *res;
3360 int ok;
3361
3362 if (!PyArg_ParseTuple(args, "O", &other))
3363 return NULL;
3364 ok = func(&self, &other);
3365 if (ok < 0)
3366 return NULL;
3367 if (ok > 0) {
3368 Py_INCREF(Py_NotImplemented);
3369 return Py_NotImplemented;
3370 }
3371 res = PyTuple_New(2);
3372 if (res == NULL) {
3373 Py_DECREF(self);
3374 Py_DECREF(other);
3375 return NULL;
3376 }
3377 PyTuple_SET_ITEM(res, 0, self);
3378 PyTuple_SET_ITEM(res, 1, other);
3379 return res;
3380}
3381
Tim Peters6d6c1a32001-08-02 04:15:00 +00003382static PyObject *
3383wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
3384{
3385 ternaryfunc func = (ternaryfunc)wrapped;
3386 PyObject *other;
3387 PyObject *third = Py_None;
3388
3389 /* Note: This wrapper only works for __pow__() */
3390
3391 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
3392 return NULL;
3393 return (*func)(self, other, third);
3394}
3395
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00003396static PyObject *
3397wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3398{
3399 ternaryfunc func = (ternaryfunc)wrapped;
3400 PyObject *other;
3401 PyObject *third = Py_None;
3402
3403 /* Note: This wrapper only works for __pow__() */
3404
3405 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
3406 return NULL;
3407 return (*func)(other, self, third);
3408}
3409
Tim Peters6d6c1a32001-08-02 04:15:00 +00003410static PyObject *
3411wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
3412{
3413 unaryfunc func = (unaryfunc)wrapped;
3414
3415 if (!PyArg_ParseTuple(args, ""))
3416 return NULL;
3417 return (*func)(self);
3418}
3419
Tim Peters6d6c1a32001-08-02 04:15:00 +00003420static PyObject *
3421wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
3422{
3423 intargfunc func = (intargfunc)wrapped;
3424 int i;
3425
3426 if (!PyArg_ParseTuple(args, "i", &i))
3427 return NULL;
3428 return (*func)(self, i);
3429}
3430
Guido van Rossum5d815f32001-08-17 21:57:47 +00003431static int
3432getindex(PyObject *self, PyObject *arg)
3433{
3434 int i;
3435
3436 i = PyInt_AsLong(arg);
3437 if (i == -1 && PyErr_Occurred())
3438 return -1;
3439 if (i < 0) {
3440 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
3441 if (sq && sq->sq_length) {
3442 int n = (*sq->sq_length)(self);
3443 if (n < 0)
3444 return -1;
3445 i += n;
3446 }
3447 }
3448 return i;
3449}
3450
3451static PyObject *
3452wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
3453{
3454 intargfunc func = (intargfunc)wrapped;
3455 PyObject *arg;
3456 int i;
3457
Guido van Rossumf4593e02001-10-03 12:09:30 +00003458 if (PyTuple_GET_SIZE(args) == 1) {
3459 arg = PyTuple_GET_ITEM(args, 0);
3460 i = getindex(self, arg);
3461 if (i == -1 && PyErr_Occurred())
3462 return NULL;
3463 return (*func)(self, i);
3464 }
3465 PyArg_ParseTuple(args, "O", &arg);
3466 assert(PyErr_Occurred());
3467 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003468}
3469
Tim Peters6d6c1a32001-08-02 04:15:00 +00003470static PyObject *
3471wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
3472{
3473 intintargfunc func = (intintargfunc)wrapped;
3474 int i, j;
3475
3476 if (!PyArg_ParseTuple(args, "ii", &i, &j))
3477 return NULL;
3478 return (*func)(self, i, j);
3479}
3480
Tim Peters6d6c1a32001-08-02 04:15:00 +00003481static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003482wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003483{
3484 intobjargproc func = (intobjargproc)wrapped;
3485 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003486 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003487
Guido van Rossum5d815f32001-08-17 21:57:47 +00003488 if (!PyArg_ParseTuple(args, "OO", &arg, &value))
3489 return NULL;
3490 i = getindex(self, arg);
3491 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00003492 return NULL;
3493 res = (*func)(self, i, value);
3494 if (res == -1 && PyErr_Occurred())
3495 return NULL;
3496 Py_INCREF(Py_None);
3497 return Py_None;
3498}
3499
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003500static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003501wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003502{
3503 intobjargproc func = (intobjargproc)wrapped;
3504 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003505 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003506
Guido van Rossum5d815f32001-08-17 21:57:47 +00003507 if (!PyArg_ParseTuple(args, "O", &arg))
3508 return NULL;
3509 i = getindex(self, arg);
3510 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003511 return NULL;
3512 res = (*func)(self, i, NULL);
3513 if (res == -1 && PyErr_Occurred())
3514 return NULL;
3515 Py_INCREF(Py_None);
3516 return Py_None;
3517}
3518
Tim Peters6d6c1a32001-08-02 04:15:00 +00003519static PyObject *
3520wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
3521{
3522 intintobjargproc func = (intintobjargproc)wrapped;
3523 int i, j, res;
3524 PyObject *value;
3525
3526 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
3527 return NULL;
3528 res = (*func)(self, i, j, value);
3529 if (res == -1 && PyErr_Occurred())
3530 return NULL;
3531 Py_INCREF(Py_None);
3532 return Py_None;
3533}
3534
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003535static PyObject *
3536wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
3537{
3538 intintobjargproc func = (intintobjargproc)wrapped;
3539 int i, j, res;
3540
3541 if (!PyArg_ParseTuple(args, "ii", &i, &j))
3542 return NULL;
3543 res = (*func)(self, i, j, NULL);
3544 if (res == -1 && PyErr_Occurred())
3545 return NULL;
3546 Py_INCREF(Py_None);
3547 return Py_None;
3548}
3549
Tim Peters6d6c1a32001-08-02 04:15:00 +00003550/* XXX objobjproc is a misnomer; should be objargpred */
3551static PyObject *
3552wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
3553{
3554 objobjproc func = (objobjproc)wrapped;
3555 int res;
3556 PyObject *value;
3557
3558 if (!PyArg_ParseTuple(args, "O", &value))
3559 return NULL;
3560 res = (*func)(self, value);
3561 if (res == -1 && PyErr_Occurred())
3562 return NULL;
3563 return PyInt_FromLong((long)res);
3564}
3565
Tim Peters6d6c1a32001-08-02 04:15:00 +00003566static PyObject *
3567wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
3568{
3569 objobjargproc func = (objobjargproc)wrapped;
3570 int res;
3571 PyObject *key, *value;
3572
3573 if (!PyArg_ParseTuple(args, "OO", &key, &value))
3574 return NULL;
3575 res = (*func)(self, key, value);
3576 if (res == -1 && PyErr_Occurred())
3577 return NULL;
3578 Py_INCREF(Py_None);
3579 return Py_None;
3580}
3581
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003582static PyObject *
3583wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
3584{
3585 objobjargproc func = (objobjargproc)wrapped;
3586 int res;
3587 PyObject *key;
3588
3589 if (!PyArg_ParseTuple(args, "O", &key))
3590 return NULL;
3591 res = (*func)(self, key, NULL);
3592 if (res == -1 && PyErr_Occurred())
3593 return NULL;
3594 Py_INCREF(Py_None);
3595 return Py_None;
3596}
3597
Tim Peters6d6c1a32001-08-02 04:15:00 +00003598static PyObject *
3599wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
3600{
3601 cmpfunc func = (cmpfunc)wrapped;
3602 int res;
3603 PyObject *other;
3604
3605 if (!PyArg_ParseTuple(args, "O", &other))
3606 return NULL;
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00003607 if (other->ob_type->tp_compare != func &&
3608 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00003609 PyErr_Format(
3610 PyExc_TypeError,
3611 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
3612 self->ob_type->tp_name,
3613 self->ob_type->tp_name,
3614 other->ob_type->tp_name);
3615 return NULL;
3616 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003617 res = (*func)(self, other);
3618 if (PyErr_Occurred())
3619 return NULL;
3620 return PyInt_FromLong((long)res);
3621}
3622
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003623/* Helper to check for object.__setattr__ or __delattr__ applied to a type.
Guido van Rossum52b27052003-04-15 20:05:10 +00003624 This is called the Carlo Verre hack after its discoverer. */
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003625static int
3626hackcheck(PyObject *self, setattrofunc func, char *what)
3627{
3628 PyTypeObject *type = self->ob_type;
3629 while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE)
3630 type = type->tp_base;
3631 if (type->tp_setattro != func) {
3632 PyErr_Format(PyExc_TypeError,
3633 "can't apply this %s to %s object",
3634 what,
3635 type->tp_name);
3636 return 0;
3637 }
3638 return 1;
3639}
3640
Tim Peters6d6c1a32001-08-02 04:15:00 +00003641static PyObject *
3642wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
3643{
3644 setattrofunc func = (setattrofunc)wrapped;
3645 int res;
3646 PyObject *name, *value;
3647
3648 if (!PyArg_ParseTuple(args, "OO", &name, &value))
3649 return NULL;
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003650 if (!hackcheck(self, func, "__setattr__"))
3651 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003652 res = (*func)(self, name, value);
3653 if (res < 0)
3654 return NULL;
3655 Py_INCREF(Py_None);
3656 return Py_None;
3657}
3658
3659static PyObject *
3660wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
3661{
3662 setattrofunc func = (setattrofunc)wrapped;
3663 int res;
3664 PyObject *name;
3665
3666 if (!PyArg_ParseTuple(args, "O", &name))
3667 return NULL;
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003668 if (!hackcheck(self, func, "__delattr__"))
3669 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003670 res = (*func)(self, name, NULL);
3671 if (res < 0)
3672 return NULL;
3673 Py_INCREF(Py_None);
3674 return Py_None;
3675}
3676
Tim Peters6d6c1a32001-08-02 04:15:00 +00003677static PyObject *
3678wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
3679{
3680 hashfunc func = (hashfunc)wrapped;
3681 long res;
3682
3683 if (!PyArg_ParseTuple(args, ""))
3684 return NULL;
3685 res = (*func)(self);
3686 if (res == -1 && PyErr_Occurred())
3687 return NULL;
3688 return PyInt_FromLong(res);
3689}
3690
Tim Peters6d6c1a32001-08-02 04:15:00 +00003691static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00003692wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003693{
3694 ternaryfunc func = (ternaryfunc)wrapped;
3695
Guido van Rossumc8e56452001-10-22 00:43:43 +00003696 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003697}
3698
Tim Peters6d6c1a32001-08-02 04:15:00 +00003699static PyObject *
3700wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
3701{
3702 richcmpfunc func = (richcmpfunc)wrapped;
3703 PyObject *other;
3704
3705 if (!PyArg_ParseTuple(args, "O", &other))
3706 return NULL;
3707 return (*func)(self, other, op);
3708}
3709
3710#undef RICHCMP_WRAPPER
3711#define RICHCMP_WRAPPER(NAME, OP) \
3712static PyObject * \
3713richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
3714{ \
3715 return wrap_richcmpfunc(self, args, wrapped, OP); \
3716}
3717
Jack Jansen8e938b42001-08-08 15:29:49 +00003718RICHCMP_WRAPPER(lt, Py_LT)
3719RICHCMP_WRAPPER(le, Py_LE)
3720RICHCMP_WRAPPER(eq, Py_EQ)
3721RICHCMP_WRAPPER(ne, Py_NE)
3722RICHCMP_WRAPPER(gt, Py_GT)
3723RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003724
Tim Peters6d6c1a32001-08-02 04:15:00 +00003725static PyObject *
3726wrap_next(PyObject *self, PyObject *args, void *wrapped)
3727{
3728 unaryfunc func = (unaryfunc)wrapped;
3729 PyObject *res;
3730
3731 if (!PyArg_ParseTuple(args, ""))
3732 return NULL;
3733 res = (*func)(self);
3734 if (res == NULL && !PyErr_Occurred())
3735 PyErr_SetNone(PyExc_StopIteration);
3736 return res;
3737}
3738
Tim Peters6d6c1a32001-08-02 04:15:00 +00003739static PyObject *
3740wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
3741{
3742 descrgetfunc func = (descrgetfunc)wrapped;
3743 PyObject *obj;
3744 PyObject *type = NULL;
3745
3746 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
3747 return NULL;
Guido van Rossum82ed25c2003-02-11 16:25:43 +00003748 if (obj == Py_None)
3749 obj = NULL;
3750 if (type == Py_None)
3751 type = NULL;
3752 if (type == NULL &&obj == NULL) {
3753 PyErr_SetString(PyExc_TypeError,
3754 "__get__(None, None) is invalid");
3755 return NULL;
3756 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003757 return (*func)(self, obj, type);
3758}
3759
Tim Peters6d6c1a32001-08-02 04:15:00 +00003760static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003761wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003762{
3763 descrsetfunc func = (descrsetfunc)wrapped;
3764 PyObject *obj, *value;
3765 int ret;
3766
3767 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
3768 return NULL;
3769 ret = (*func)(self, obj, value);
3770 if (ret < 0)
3771 return NULL;
3772 Py_INCREF(Py_None);
3773 return Py_None;
3774}
Guido van Rossum22b13872002-08-06 21:41:44 +00003775
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00003776static PyObject *
3777wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
3778{
3779 descrsetfunc func = (descrsetfunc)wrapped;
3780 PyObject *obj;
3781 int ret;
3782
3783 if (!PyArg_ParseTuple(args, "O", &obj))
3784 return NULL;
3785 ret = (*func)(self, obj, NULL);
3786 if (ret < 0)
3787 return NULL;
3788 Py_INCREF(Py_None);
3789 return Py_None;
3790}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003791
Tim Peters6d6c1a32001-08-02 04:15:00 +00003792static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00003793wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003794{
3795 initproc func = (initproc)wrapped;
3796
Guido van Rossumc8e56452001-10-22 00:43:43 +00003797 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003798 return NULL;
3799 Py_INCREF(Py_None);
3800 return Py_None;
3801}
3802
Tim Peters6d6c1a32001-08-02 04:15:00 +00003803static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003804tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003805{
Barry Warsaw60f01882001-08-22 19:24:42 +00003806 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003807 PyObject *arg0, *res;
3808
3809 if (self == NULL || !PyType_Check(self))
3810 Py_FatalError("__new__() called with non-type 'self'");
3811 type = (PyTypeObject *)self;
3812 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003813 PyErr_Format(PyExc_TypeError,
3814 "%s.__new__(): not enough arguments",
3815 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003816 return NULL;
3817 }
3818 arg0 = PyTuple_GET_ITEM(args, 0);
3819 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003820 PyErr_Format(PyExc_TypeError,
3821 "%s.__new__(X): X is not a type object (%s)",
3822 type->tp_name,
3823 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003824 return NULL;
3825 }
3826 subtype = (PyTypeObject *)arg0;
3827 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003828 PyErr_Format(PyExc_TypeError,
3829 "%s.__new__(%s): %s is not a subtype of %s",
3830 type->tp_name,
3831 subtype->tp_name,
3832 subtype->tp_name,
3833 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003834 return NULL;
3835 }
Barry Warsaw60f01882001-08-22 19:24:42 +00003836
3837 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00003838 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00003839 most derived base that's not a heap type is this type. */
3840 staticbase = subtype;
3841 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
3842 staticbase = staticbase->tp_base;
Guido van Rossuma8c60f42001-09-14 19:43:36 +00003843 if (staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003844 PyErr_Format(PyExc_TypeError,
3845 "%s.__new__(%s) is not safe, use %s.__new__()",
3846 type->tp_name,
3847 subtype->tp_name,
3848 staticbase == NULL ? "?" : staticbase->tp_name);
3849 return NULL;
3850 }
3851
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003852 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
3853 if (args == NULL)
3854 return NULL;
3855 res = type->tp_new(subtype, args, kwds);
3856 Py_DECREF(args);
3857 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003858}
3859
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003860static struct PyMethodDef tp_new_methoddef[] = {
3861 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00003862 PyDoc_STR("T.__new__(S, ...) -> "
3863 "a new object with type S, a subtype of T")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00003864 {0}
3865};
3866
3867static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003868add_tp_new_wrapper(PyTypeObject *type)
3869{
Guido van Rossumf040ede2001-08-07 16:40:56 +00003870 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003871
Guido van Rossum687ae002001-10-15 22:03:32 +00003872 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00003873 return 0;
3874 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003875 if (func == NULL)
3876 return -1;
Guido van Rossum687ae002001-10-15 22:03:32 +00003877 return PyDict_SetItemString(type->tp_dict, "__new__", func);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003878}
3879
Guido van Rossumf040ede2001-08-07 16:40:56 +00003880/* Slot wrappers that call the corresponding __foo__ slot. See comments
3881 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003882
Guido van Rossumdc91b992001-08-08 22:26:22 +00003883#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003884static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003885FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003886{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00003887 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003888 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003889}
3890
Guido van Rossumdc91b992001-08-08 22:26:22 +00003891#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003892static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003893FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003894{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003895 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003896 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003897}
3898
Guido van Rossumcd118802003-01-06 22:57:47 +00003899/* Boolean helper for SLOT1BINFULL().
3900 right.__class__ is a nontrivial subclass of left.__class__. */
3901static int
3902method_is_overloaded(PyObject *left, PyObject *right, char *name)
3903{
3904 PyObject *a, *b;
3905 int ok;
3906
3907 b = PyObject_GetAttrString((PyObject *)(right->ob_type), name);
3908 if (b == NULL) {
3909 PyErr_Clear();
3910 /* If right doesn't have it, it's not overloaded */
3911 return 0;
3912 }
3913
3914 a = PyObject_GetAttrString((PyObject *)(left->ob_type), name);
3915 if (a == NULL) {
3916 PyErr_Clear();
3917 Py_DECREF(b);
3918 /* If right has it but left doesn't, it's overloaded */
3919 return 1;
3920 }
3921
3922 ok = PyObject_RichCompareBool(a, b, Py_NE);
3923 Py_DECREF(a);
3924 Py_DECREF(b);
3925 if (ok < 0) {
3926 PyErr_Clear();
3927 return 0;
3928 }
3929
3930 return ok;
3931}
3932
Guido van Rossumdc91b992001-08-08 22:26:22 +00003933
3934#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003935static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003936FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003937{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003938 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00003939 int do_other = self->ob_type != other->ob_type && \
3940 other->ob_type->tp_as_number != NULL && \
3941 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003942 if (self->ob_type->tp_as_number != NULL && \
3943 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
3944 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00003945 if (do_other && \
Guido van Rossumcd118802003-01-06 22:57:47 +00003946 PyType_IsSubtype(other->ob_type, self->ob_type) && \
3947 method_is_overloaded(self, other, ROPSTR)) { \
Guido van Rossum55f20992001-10-01 17:18:22 +00003948 r = call_maybe( \
3949 other, ROPSTR, &rcache_str, "(O)", self); \
3950 if (r != Py_NotImplemented) \
3951 return r; \
3952 Py_DECREF(r); \
3953 do_other = 0; \
3954 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00003955 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00003956 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003957 if (r != Py_NotImplemented || \
3958 other->ob_type == self->ob_type) \
3959 return r; \
3960 Py_DECREF(r); \
3961 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00003962 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00003963 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00003964 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003965 } \
3966 Py_INCREF(Py_NotImplemented); \
3967 return Py_NotImplemented; \
3968}
3969
3970#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
3971 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
3972
3973#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
3974static PyObject * \
3975FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
3976{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003977 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003978 return call_method(self, OPSTR, &cache_str, \
3979 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003980}
3981
3982static int
3983slot_sq_length(PyObject *self)
3984{
Guido van Rossum2730b132001-08-28 18:22:14 +00003985 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00003986 PyObject *res = call_method(self, "__len__", &len_str, "()");
Guido van Rossum26111622001-10-01 16:42:49 +00003987 int len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003988
3989 if (res == NULL)
3990 return -1;
Guido van Rossum26111622001-10-01 16:42:49 +00003991 len = (int)PyInt_AsLong(res);
3992 Py_DECREF(res);
Jeremy Hylton73a088e2002-07-25 16:43:29 +00003993 if (len == -1 && PyErr_Occurred())
3994 return -1;
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00003995 if (len < 0) {
Guido van Rossum22b13872002-08-06 21:41:44 +00003996 PyErr_SetString(PyExc_ValueError,
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00003997 "__len__() should return >= 0");
3998 return -1;
3999 }
Guido van Rossum26111622001-10-01 16:42:49 +00004000 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004001}
4002
Guido van Rossumdc91b992001-08-08 22:26:22 +00004003SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
4004SLOT1(slot_sq_repeat, "__mul__", int, "i")
Guido van Rossumf4593e02001-10-03 12:09:30 +00004005
4006/* Super-optimized version of slot_sq_item.
4007 Other slots could do the same... */
4008static PyObject *
4009slot_sq_item(PyObject *self, int i)
4010{
4011 static PyObject *getitem_str;
4012 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
4013 descrgetfunc f;
4014
4015 if (getitem_str == NULL) {
4016 getitem_str = PyString_InternFromString("__getitem__");
4017 if (getitem_str == NULL)
4018 return NULL;
4019 }
4020 func = _PyType_Lookup(self->ob_type, getitem_str);
4021 if (func != NULL) {
Guido van Rossumf4593e02001-10-03 12:09:30 +00004022 if ((f = func->ob_type->tp_descr_get) == NULL)
4023 Py_INCREF(func);
Neal Norwitz673cd822002-10-18 16:33:13 +00004024 else {
Guido van Rossumf4593e02001-10-03 12:09:30 +00004025 func = f(func, self, (PyObject *)(self->ob_type));
Neal Norwitz673cd822002-10-18 16:33:13 +00004026 if (func == NULL) {
4027 return NULL;
4028 }
4029 }
Guido van Rossumf4593e02001-10-03 12:09:30 +00004030 ival = PyInt_FromLong(i);
4031 if (ival != NULL) {
4032 args = PyTuple_New(1);
4033 if (args != NULL) {
4034 PyTuple_SET_ITEM(args, 0, ival);
4035 retval = PyObject_Call(func, args, NULL);
4036 Py_XDECREF(args);
4037 Py_XDECREF(func);
4038 return retval;
4039 }
4040 }
4041 }
4042 else {
4043 PyErr_SetObject(PyExc_AttributeError, getitem_str);
4044 }
4045 Py_XDECREF(args);
4046 Py_XDECREF(ival);
4047 Py_XDECREF(func);
4048 return NULL;
4049}
4050
Guido van Rossumdc91b992001-08-08 22:26:22 +00004051SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004052
4053static int
4054slot_sq_ass_item(PyObject *self, int index, PyObject *value)
4055{
4056 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004057 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004058
4059 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004060 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004061 "(i)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004062 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004063 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004064 "(iO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004065 if (res == NULL)
4066 return -1;
4067 Py_DECREF(res);
4068 return 0;
4069}
4070
4071static int
4072slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
4073{
4074 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004075 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004076
4077 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004078 res = call_method(self, "__delslice__", &delslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004079 "(ii)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004080 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004081 res = call_method(self, "__setslice__", &setslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004082 "(iiO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004083 if (res == NULL)
4084 return -1;
4085 Py_DECREF(res);
4086 return 0;
4087}
4088
4089static int
4090slot_sq_contains(PyObject *self, PyObject *value)
4091{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004092 PyObject *func, *res, *args;
Tim Petersbf9b2442003-03-23 05:35:36 +00004093 int result = -1;
4094
Guido van Rossum60718732001-08-28 17:47:51 +00004095 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004096
Guido van Rossum55f20992001-10-01 17:18:22 +00004097 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004098 if (func != NULL) {
4099 args = Py_BuildValue("(O)", value);
4100 if (args == NULL)
4101 res = NULL;
4102 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004103 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004104 Py_DECREF(args);
4105 }
4106 Py_DECREF(func);
Tim Petersbf9b2442003-03-23 05:35:36 +00004107 if (res != NULL) {
4108 result = PyObject_IsTrue(res);
4109 Py_DECREF(res);
4110 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004111 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004112 else if (! PyErr_Occurred()) {
4113 result = _PySequence_IterSearch(self, value,
4114 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004115 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004116 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004117}
4118
Guido van Rossumdc91b992001-08-08 22:26:22 +00004119SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
4120SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004121
4122#define slot_mp_length slot_sq_length
4123
Guido van Rossumdc91b992001-08-08 22:26:22 +00004124SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004125
4126static int
4127slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
4128{
4129 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004130 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004131
4132 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004133 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004134 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004135 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004136 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004137 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004138 if (res == NULL)
4139 return -1;
4140 Py_DECREF(res);
4141 return 0;
4142}
4143
Guido van Rossumdc91b992001-08-08 22:26:22 +00004144SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
4145SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
4146SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
4147SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
4148SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
4149SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
4150
Jeremy Hylton938ace62002-07-17 16:30:39 +00004151static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00004152
4153SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
4154 nb_power, "__pow__", "__rpow__")
4155
4156static PyObject *
4157slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
4158{
Guido van Rossum2730b132001-08-28 18:22:14 +00004159 static PyObject *pow_str;
4160
Guido van Rossumdc91b992001-08-08 22:26:22 +00004161 if (modulus == Py_None)
4162 return slot_nb_power_binary(self, other);
Guido van Rossum23094982002-06-10 14:30:43 +00004163 /* Three-arg power doesn't use __rpow__. But ternary_op
4164 can call this when the second argument's type uses
4165 slot_nb_power, so check before calling self.__pow__. */
4166 if (self->ob_type->tp_as_number != NULL &&
4167 self->ob_type->tp_as_number->nb_power == slot_nb_power) {
4168 return call_method(self, "__pow__", &pow_str,
4169 "(OO)", other, modulus);
4170 }
4171 Py_INCREF(Py_NotImplemented);
4172 return Py_NotImplemented;
Guido van Rossumdc91b992001-08-08 22:26:22 +00004173}
4174
4175SLOT0(slot_nb_negative, "__neg__")
4176SLOT0(slot_nb_positive, "__pos__")
4177SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004178
4179static int
4180slot_nb_nonzero(PyObject *self)
4181{
Tim Petersea7f75d2002-12-07 21:39:16 +00004182 PyObject *func, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00004183 static PyObject *nonzero_str, *len_str;
Tim Petersea7f75d2002-12-07 21:39:16 +00004184 int result = -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004185
Guido van Rossum55f20992001-10-01 17:18:22 +00004186 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004187 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00004188 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00004189 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00004190 func = lookup_maybe(self, "__len__", &len_str);
Tim Petersea7f75d2002-12-07 21:39:16 +00004191 if (func == NULL)
4192 return PyErr_Occurred() ? -1 : 1;
4193 }
4194 args = PyTuple_New(0);
4195 if (args != NULL) {
4196 PyObject *temp = PyObject_Call(func, args, NULL);
4197 Py_DECREF(args);
4198 if (temp != NULL) {
Jeremy Hylton3e3159c2003-06-27 17:38:27 +00004199 if (PyInt_CheckExact(temp) || PyBool_Check(temp))
Jeremy Hylton090a3492003-06-27 16:46:45 +00004200 result = PyObject_IsTrue(temp);
4201 else {
4202 PyErr_Format(PyExc_TypeError,
4203 "__nonzero__ should return "
4204 "bool or int, returned %s",
4205 temp->ob_type->tp_name);
Jeremy Hylton3e3159c2003-06-27 17:38:27 +00004206 result = -1;
Jeremy Hylton090a3492003-06-27 16:46:45 +00004207 }
Tim Petersea7f75d2002-12-07 21:39:16 +00004208 Py_DECREF(temp);
Guido van Rossum55f20992001-10-01 17:18:22 +00004209 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004210 }
Guido van Rossum55f20992001-10-01 17:18:22 +00004211 Py_DECREF(func);
Tim Petersea7f75d2002-12-07 21:39:16 +00004212 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004213}
4214
Guido van Rossumdc91b992001-08-08 22:26:22 +00004215SLOT0(slot_nb_invert, "__invert__")
4216SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
4217SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
4218SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
4219SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
4220SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004221
4222static int
4223slot_nb_coerce(PyObject **a, PyObject **b)
4224{
4225 static PyObject *coerce_str;
4226 PyObject *self = *a, *other = *b;
4227
4228 if (self->ob_type->tp_as_number != NULL &&
4229 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
4230 PyObject *r;
4231 r = call_maybe(
4232 self, "__coerce__", &coerce_str, "(O)", other);
4233 if (r == NULL)
4234 return -1;
4235 if (r == Py_NotImplemented) {
4236 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004237 }
Guido van Rossum55f20992001-10-01 17:18:22 +00004238 else {
4239 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
4240 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004241 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00004242 Py_DECREF(r);
4243 return -1;
4244 }
4245 *a = PyTuple_GET_ITEM(r, 0);
4246 Py_INCREF(*a);
4247 *b = PyTuple_GET_ITEM(r, 1);
4248 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004249 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00004250 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004251 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004252 }
4253 if (other->ob_type->tp_as_number != NULL &&
4254 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
4255 PyObject *r;
4256 r = call_maybe(
4257 other, "__coerce__", &coerce_str, "(O)", self);
4258 if (r == NULL)
4259 return -1;
4260 if (r == Py_NotImplemented) {
4261 Py_DECREF(r);
4262 return 1;
4263 }
4264 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
4265 PyErr_SetString(PyExc_TypeError,
4266 "__coerce__ didn't return a 2-tuple");
4267 Py_DECREF(r);
4268 return -1;
4269 }
4270 *a = PyTuple_GET_ITEM(r, 1);
4271 Py_INCREF(*a);
4272 *b = PyTuple_GET_ITEM(r, 0);
4273 Py_INCREF(*b);
4274 Py_DECREF(r);
4275 return 0;
4276 }
4277 return 1;
4278}
4279
Guido van Rossumdc91b992001-08-08 22:26:22 +00004280SLOT0(slot_nb_int, "__int__")
4281SLOT0(slot_nb_long, "__long__")
4282SLOT0(slot_nb_float, "__float__")
4283SLOT0(slot_nb_oct, "__oct__")
4284SLOT0(slot_nb_hex, "__hex__")
4285SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
4286SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
4287SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
4288SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
4289SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Guido van Rossum6e5680f2002-10-15 01:01:53 +00004290SLOT1(slot_nb_inplace_power, "__ipow__", PyObject *, "O")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004291SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
4292SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
4293SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
4294SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
4295SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
4296SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
4297 "__floordiv__", "__rfloordiv__")
4298SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
4299SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
4300SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004301
4302static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00004303half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004304{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004305 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004306 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004307 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004308
Guido van Rossum60718732001-08-28 17:47:51 +00004309 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004310 if (func == NULL) {
4311 PyErr_Clear();
4312 }
4313 else {
4314 args = Py_BuildValue("(O)", other);
4315 if (args == NULL)
4316 res = NULL;
4317 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004318 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004319 Py_DECREF(args);
4320 }
Raymond Hettingerab5dae32002-06-24 13:08:16 +00004321 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004322 if (res != Py_NotImplemented) {
4323 if (res == NULL)
4324 return -2;
4325 c = PyInt_AsLong(res);
4326 Py_DECREF(res);
4327 if (c == -1 && PyErr_Occurred())
4328 return -2;
4329 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
4330 }
4331 Py_DECREF(res);
4332 }
4333 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004334}
4335
Guido van Rossumab3b0342001-09-18 20:38:53 +00004336/* This slot is published for the benefit of try_3way_compare in object.c */
4337int
4338_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00004339{
4340 int c;
4341
Guido van Rossumab3b0342001-09-18 20:38:53 +00004342 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004343 c = half_compare(self, other);
4344 if (c <= 1)
4345 return c;
4346 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00004347 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004348 c = half_compare(other, self);
4349 if (c < -1)
4350 return -2;
4351 if (c <= 1)
4352 return -c;
4353 }
4354 return (void *)self < (void *)other ? -1 :
4355 (void *)self > (void *)other ? 1 : 0;
4356}
4357
4358static PyObject *
4359slot_tp_repr(PyObject *self)
4360{
4361 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004362 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004363
Guido van Rossum60718732001-08-28 17:47:51 +00004364 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004365 if (func != NULL) {
4366 res = PyEval_CallObject(func, NULL);
4367 Py_DECREF(func);
4368 return res;
4369 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00004370 PyErr_Clear();
4371 return PyString_FromFormat("<%s object at %p>",
4372 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004373}
4374
4375static PyObject *
4376slot_tp_str(PyObject *self)
4377{
4378 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004379 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004380
Guido van Rossum60718732001-08-28 17:47:51 +00004381 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004382 if (func != NULL) {
4383 res = PyEval_CallObject(func, NULL);
4384 Py_DECREF(func);
4385 return res;
4386 }
4387 else {
4388 PyErr_Clear();
4389 return slot_tp_repr(self);
4390 }
4391}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004392
4393static long
4394slot_tp_hash(PyObject *self)
4395{
Tim Peters61ce0a92002-12-06 23:38:02 +00004396 PyObject *func;
Guido van Rossum60718732001-08-28 17:47:51 +00004397 static PyObject *hash_str, *eq_str, *cmp_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004398 long h;
4399
Guido van Rossum60718732001-08-28 17:47:51 +00004400 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004401
4402 if (func != NULL) {
Tim Peters61ce0a92002-12-06 23:38:02 +00004403 PyObject *res = PyEval_CallObject(func, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004404 Py_DECREF(func);
4405 if (res == NULL)
4406 return -1;
4407 h = PyInt_AsLong(res);
Tim Peters61ce0a92002-12-06 23:38:02 +00004408 Py_DECREF(res);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004409 }
4410 else {
4411 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004412 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004413 if (func == NULL) {
4414 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004415 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004416 }
4417 if (func != NULL) {
4418 Py_DECREF(func);
4419 PyErr_SetString(PyExc_TypeError, "unhashable type");
4420 return -1;
4421 }
4422 PyErr_Clear();
4423 h = _Py_HashPointer((void *)self);
4424 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004425 if (h == -1 && !PyErr_Occurred())
4426 h = -2;
4427 return h;
4428}
4429
4430static PyObject *
4431slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
4432{
Guido van Rossum60718732001-08-28 17:47:51 +00004433 static PyObject *call_str;
4434 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004435 PyObject *res;
4436
4437 if (meth == NULL)
4438 return NULL;
4439 res = PyObject_Call(meth, args, kwds);
4440 Py_DECREF(meth);
4441 return res;
4442}
4443
Guido van Rossum14a6f832001-10-17 13:59:09 +00004444/* There are two slot dispatch functions for tp_getattro.
4445
4446 - slot_tp_getattro() is used when __getattribute__ is overridden
4447 but no __getattr__ hook is present;
4448
4449 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
4450
Guido van Rossumc334df52002-04-04 23:44:47 +00004451 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
4452 detects the absence of __getattr__ and then installs the simpler slot if
4453 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00004454
Tim Peters6d6c1a32001-08-02 04:15:00 +00004455static PyObject *
4456slot_tp_getattro(PyObject *self, PyObject *name)
4457{
Guido van Rossum14a6f832001-10-17 13:59:09 +00004458 static PyObject *getattribute_str = NULL;
4459 return call_method(self, "__getattribute__", &getattribute_str,
4460 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004461}
4462
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004463static PyObject *
4464slot_tp_getattr_hook(PyObject *self, PyObject *name)
4465{
4466 PyTypeObject *tp = self->ob_type;
4467 PyObject *getattr, *getattribute, *res;
4468 static PyObject *getattribute_str = NULL;
4469 static PyObject *getattr_str = NULL;
4470
4471 if (getattr_str == NULL) {
4472 getattr_str = PyString_InternFromString("__getattr__");
4473 if (getattr_str == NULL)
4474 return NULL;
4475 }
4476 if (getattribute_str == NULL) {
4477 getattribute_str =
4478 PyString_InternFromString("__getattribute__");
4479 if (getattribute_str == NULL)
4480 return NULL;
4481 }
4482 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004483 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004484 /* No __getattr__ hook: use a simpler dispatcher */
4485 tp->tp_getattro = slot_tp_getattro;
4486 return slot_tp_getattro(self, name);
4487 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004488 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004489 if (getattribute == NULL ||
4490 (getattribute->ob_type == &PyWrapperDescr_Type &&
4491 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
4492 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004493 res = PyObject_GenericGetAttr(self, name);
4494 else
4495 res = PyObject_CallFunction(getattribute, "OO", self, name);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004496 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004497 PyErr_Clear();
4498 res = PyObject_CallFunction(getattr, "OO", self, name);
4499 }
4500 return res;
4501}
4502
Tim Peters6d6c1a32001-08-02 04:15:00 +00004503static int
4504slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
4505{
4506 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004507 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004508
4509 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004510 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004511 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004512 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004513 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004514 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004515 if (res == NULL)
4516 return -1;
4517 Py_DECREF(res);
4518 return 0;
4519}
4520
4521/* Map rich comparison operators to their __xx__ namesakes */
4522static char *name_op[] = {
4523 "__lt__",
4524 "__le__",
4525 "__eq__",
4526 "__ne__",
4527 "__gt__",
4528 "__ge__",
4529};
4530
4531static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00004532half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004533{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004534 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004535 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00004536
Guido van Rossum60718732001-08-28 17:47:51 +00004537 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004538 if (func == NULL) {
4539 PyErr_Clear();
4540 Py_INCREF(Py_NotImplemented);
4541 return Py_NotImplemented;
4542 }
4543 args = Py_BuildValue("(O)", other);
4544 if (args == NULL)
4545 res = NULL;
4546 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004547 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004548 Py_DECREF(args);
4549 }
4550 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004551 return res;
4552}
4553
Guido van Rossumb8f63662001-08-15 23:57:02 +00004554/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
4555static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
4556
4557static PyObject *
4558slot_tp_richcompare(PyObject *self, PyObject *other, int op)
4559{
4560 PyObject *res;
4561
4562 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
4563 res = half_richcompare(self, other, op);
4564 if (res != Py_NotImplemented)
4565 return res;
4566 Py_DECREF(res);
4567 }
4568 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
4569 res = half_richcompare(other, self, swapped_op[op]);
4570 if (res != Py_NotImplemented) {
4571 return res;
4572 }
4573 Py_DECREF(res);
4574 }
4575 Py_INCREF(Py_NotImplemented);
4576 return Py_NotImplemented;
4577}
4578
4579static PyObject *
4580slot_tp_iter(PyObject *self)
4581{
4582 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004583 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004584
Guido van Rossum60718732001-08-28 17:47:51 +00004585 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004586 if (func != NULL) {
Guido van Rossum84b2bed2002-08-16 17:01:09 +00004587 PyObject *args;
4588 args = res = PyTuple_New(0);
4589 if (args != NULL) {
4590 res = PyObject_Call(func, args, NULL);
4591 Py_DECREF(args);
4592 }
4593 Py_DECREF(func);
4594 return res;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004595 }
4596 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004597 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004598 if (func == NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00004599 PyErr_SetString(PyExc_TypeError,
4600 "iteration over non-sequence");
Guido van Rossumb8f63662001-08-15 23:57:02 +00004601 return NULL;
4602 }
4603 Py_DECREF(func);
4604 return PySeqIter_New(self);
4605}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004606
4607static PyObject *
4608slot_tp_iternext(PyObject *self)
4609{
Guido van Rossum2730b132001-08-28 18:22:14 +00004610 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00004611 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004612}
4613
Guido van Rossum1a493502001-08-17 16:47:50 +00004614static PyObject *
4615slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4616{
4617 PyTypeObject *tp = self->ob_type;
4618 PyObject *get;
4619 static PyObject *get_str = NULL;
4620
4621 if (get_str == NULL) {
4622 get_str = PyString_InternFromString("__get__");
4623 if (get_str == NULL)
4624 return NULL;
4625 }
4626 get = _PyType_Lookup(tp, get_str);
4627 if (get == NULL) {
4628 /* Avoid further slowdowns */
4629 if (tp->tp_descr_get == slot_tp_descr_get)
4630 tp->tp_descr_get = NULL;
4631 Py_INCREF(self);
4632 return self;
4633 }
Guido van Rossum2c252392001-08-24 10:13:31 +00004634 if (obj == NULL)
4635 obj = Py_None;
4636 if (type == NULL)
4637 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00004638 return PyObject_CallFunction(get, "OOO", self, obj, type);
4639}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004640
4641static int
4642slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
4643{
Guido van Rossum2c252392001-08-24 10:13:31 +00004644 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004645 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00004646
4647 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00004648 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004649 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00004650 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004651 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004652 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004653 if (res == NULL)
4654 return -1;
4655 Py_DECREF(res);
4656 return 0;
4657}
4658
4659static int
4660slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
4661{
Guido van Rossum60718732001-08-28 17:47:51 +00004662 static PyObject *init_str;
4663 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004664 PyObject *res;
4665
4666 if (meth == NULL)
4667 return -1;
4668 res = PyObject_Call(meth, args, kwds);
4669 Py_DECREF(meth);
4670 if (res == NULL)
4671 return -1;
4672 Py_DECREF(res);
4673 return 0;
4674}
4675
4676static PyObject *
4677slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4678{
Guido van Rossum7bed2132002-08-08 21:57:53 +00004679 static PyObject *new_str;
4680 PyObject *func;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004681 PyObject *newargs, *x;
4682 int i, n;
4683
Guido van Rossum7bed2132002-08-08 21:57:53 +00004684 if (new_str == NULL) {
4685 new_str = PyString_InternFromString("__new__");
4686 if (new_str == NULL)
4687 return NULL;
4688 }
4689 func = PyObject_GetAttr((PyObject *)type, new_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004690 if (func == NULL)
4691 return NULL;
4692 assert(PyTuple_Check(args));
4693 n = PyTuple_GET_SIZE(args);
4694 newargs = PyTuple_New(n+1);
4695 if (newargs == NULL)
4696 return NULL;
4697 Py_INCREF(type);
4698 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
4699 for (i = 0; i < n; i++) {
4700 x = PyTuple_GET_ITEM(args, i);
4701 Py_INCREF(x);
4702 PyTuple_SET_ITEM(newargs, i+1, x);
4703 }
4704 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00004705 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004706 Py_DECREF(func);
4707 return x;
4708}
4709
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004710static void
4711slot_tp_del(PyObject *self)
4712{
4713 static PyObject *del_str = NULL;
4714 PyObject *del, *res;
4715 PyObject *error_type, *error_value, *error_traceback;
4716
4717 /* Temporarily resurrect the object. */
4718 assert(self->ob_refcnt == 0);
4719 self->ob_refcnt = 1;
4720
4721 /* Save the current exception, if any. */
4722 PyErr_Fetch(&error_type, &error_value, &error_traceback);
4723
4724 /* Execute __del__ method, if any. */
4725 del = lookup_maybe(self, "__del__", &del_str);
4726 if (del != NULL) {
4727 res = PyEval_CallObject(del, NULL);
4728 if (res == NULL)
4729 PyErr_WriteUnraisable(del);
4730 else
4731 Py_DECREF(res);
4732 Py_DECREF(del);
4733 }
4734
4735 /* Restore the saved exception. */
4736 PyErr_Restore(error_type, error_value, error_traceback);
4737
4738 /* Undo the temporary resurrection; can't use DECREF here, it would
4739 * cause a recursive call.
4740 */
4741 assert(self->ob_refcnt > 0);
4742 if (--self->ob_refcnt == 0)
4743 return; /* this is the normal path out */
4744
4745 /* __del__ resurrected it! Make it look like the original Py_DECREF
4746 * never happened.
4747 */
4748 {
4749 int refcnt = self->ob_refcnt;
4750 _Py_NewReference(self);
4751 self->ob_refcnt = refcnt;
4752 }
4753 assert(!PyType_IS_GC(self->ob_type) ||
4754 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
4755 /* If Py_REF_DEBUG, the original decref dropped _Py_RefTotal, but
4756 * _Py_NewReference bumped it again, so that's a wash.
4757 * If Py_TRACE_REFS, _Py_NewReference re-added self to the object
4758 * chain, so no more to do there either.
4759 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
4760 * _Py_NewReference bumped tp_allocs: both of those need to be
4761 * undone.
4762 */
4763#ifdef COUNT_ALLOCS
4764 --self->ob_type->tp_frees;
4765 --self->ob_type->tp_allocs;
4766#endif
4767}
4768
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004769
4770/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
Tim Petersbf9b2442003-03-23 05:35:36 +00004771 functions. The offsets here are relative to the 'PyHeapTypeObject'
Guido van Rossume5c691a2003-03-07 15:13:17 +00004772 structure, which incorporates the additional structures used for numbers,
4773 sequences and mappings.
4774 Note that multiple names may map to the same slot (e.g. __eq__,
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004775 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00004776 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
4777 terminated with an all-zero entry. (This table is further initialized and
4778 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004779
Guido van Rossum6d204072001-10-21 00:44:31 +00004780typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004781
4782#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00004783#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004784#undef ETSLOT
4785#undef SQSLOT
4786#undef MPSLOT
4787#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00004788#undef UNSLOT
4789#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004790#undef BINSLOT
4791#undef RBINSLOT
4792
Guido van Rossum6d204072001-10-21 00:44:31 +00004793#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004794 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
4795 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00004796#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
4797 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004798 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00004799#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Guido van Rossume5c691a2003-03-07 15:13:17 +00004800 {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004801 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00004802#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4803 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
4804#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4805 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
4806#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4807 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
4808#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4809 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
4810 "x." NAME "() <==> " DOC)
4811#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4812 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
4813 "x." NAME "(y) <==> x" DOC "y")
4814#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
4815 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
4816 "x." NAME "(y) <==> x" DOC "y")
4817#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
4818 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
4819 "x." NAME "(y) <==> y" DOC "x")
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004820
4821static slotdef slotdefs[] = {
Guido van Rossum6d204072001-10-21 00:44:31 +00004822 SQSLOT("__len__", sq_length, slot_sq_length, wrap_inquiry,
4823 "x.__len__() <==> len(x)"),
4824 SQSLOT("__add__", sq_concat, slot_sq_concat, wrap_binaryfunc,
4825 "x.__add__(y) <==> x+y"),
4826 SQSLOT("__mul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
4827 "x.__mul__(n) <==> x*n"),
4828 SQSLOT("__rmul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
4829 "x.__rmul__(n) <==> n*x"),
4830 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
4831 "x.__getitem__(y) <==> x[y]"),
4832 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_intintargfunc,
Brett Cannon154da9b2003-05-20 02:30:04 +00004833 "x.__getslice__(i, j) <==> x[i:j]\n\
4834 \n\
4835 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00004836 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
Brett Cannonbe67d872003-05-20 02:40:12 +00004837 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum6d204072001-10-21 00:44:31 +00004838 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
Brett Cannonbe67d872003-05-20 02:40:12 +00004839 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004840 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Guido van Rossum6d204072001-10-21 00:44:31 +00004841 wrap_intintobjargproc,
Brett Cannonbe67d872003-05-20 02:40:12 +00004842 "x.__setslice__(i, j, y) <==> x[i:j]=y\n\
4843 \n\
4844 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00004845 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
Brett Cannonbe67d872003-05-20 02:40:12 +00004846 "x.__delslice__(i, j) <==> del x[i:j]\n\
4847 \n\
4848 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00004849 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
4850 "x.__contains__(y) <==> y in x"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004851 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat,
Guido van Rossum6d204072001-10-21 00:44:31 +00004852 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004853 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat,
Guido van Rossum6d204072001-10-21 00:44:31 +00004854 wrap_intargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004855
Guido van Rossum6d204072001-10-21 00:44:31 +00004856 MPSLOT("__len__", mp_length, slot_mp_length, wrap_inquiry,
4857 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00004858 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004859 wrap_binaryfunc,
4860 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004861 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004862 wrap_objobjargproc,
4863 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004864 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004865 wrap_delitem,
4866 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004867
Guido van Rossum6d204072001-10-21 00:44:31 +00004868 BINSLOT("__add__", nb_add, slot_nb_add,
4869 "+"),
4870 RBINSLOT("__radd__", nb_add, slot_nb_add,
4871 "+"),
4872 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
4873 "-"),
4874 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
4875 "-"),
4876 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
4877 "*"),
4878 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
4879 "*"),
4880 BINSLOT("__div__", nb_divide, slot_nb_divide,
4881 "/"),
4882 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
4883 "/"),
4884 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
4885 "%"),
4886 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
4887 "%"),
4888 BINSLOT("__divmod__", nb_divmod, slot_nb_divmod,
4889 "divmod(x, y)"),
4890 RBINSLOT("__rdivmod__", nb_divmod, slot_nb_divmod,
4891 "divmod(y, x)"),
4892 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
4893 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
4894 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
4895 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
4896 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
4897 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
4898 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
4899 "abs(x)"),
Guido van Rossumdfce3bf2002-03-10 14:11:16 +00004900 UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquiry,
Guido van Rossum6d204072001-10-21 00:44:31 +00004901 "x != 0"),
4902 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
4903 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
4904 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
4905 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
4906 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
4907 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
4908 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
4909 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
4910 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
4911 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
4912 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
4913 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
4914 "x.__coerce__(y) <==> coerce(x, y)"),
4915 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
4916 "int(x)"),
4917 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
4918 "long(x)"),
4919 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
4920 "float(x)"),
4921 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
4922 "oct(x)"),
4923 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
4924 "hex(x)"),
4925 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
4926 wrap_binaryfunc, "+"),
4927 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
4928 wrap_binaryfunc, "-"),
4929 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
4930 wrap_binaryfunc, "*"),
4931 IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
4932 wrap_binaryfunc, "/"),
4933 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
4934 wrap_binaryfunc, "%"),
4935 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
Guido van Rossum6e5680f2002-10-15 01:01:53 +00004936 wrap_binaryfunc, "**"),
Guido van Rossum6d204072001-10-21 00:44:31 +00004937 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
4938 wrap_binaryfunc, "<<"),
4939 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
4940 wrap_binaryfunc, ">>"),
4941 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
4942 wrap_binaryfunc, "&"),
4943 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
4944 wrap_binaryfunc, "^"),
4945 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
4946 wrap_binaryfunc, "|"),
4947 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
4948 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
4949 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
4950 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
4951 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
4952 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
4953 IBSLOT("__itruediv__", nb_inplace_true_divide,
4954 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004955
Guido van Rossum6d204072001-10-21 00:44:31 +00004956 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
4957 "x.__str__() <==> str(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00004958 TPSLOT("__str__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00004959 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
4960 "x.__repr__() <==> repr(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00004961 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00004962 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
4963 "x.__cmp__(y) <==> cmp(x,y)"),
4964 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
4965 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00004966 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
4967 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004968 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00004969 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
4970 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
4971 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
4972 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
4973 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
4974 "x.__setattr__('name', value) <==> x.name = value"),
4975 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
4976 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
4977 "x.__delattr__('name') <==> del x.name"),
4978 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
4979 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
4980 "x.__lt__(y) <==> x<y"),
4981 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
4982 "x.__le__(y) <==> x<=y"),
4983 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
4984 "x.__eq__(y) <==> x==y"),
4985 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
4986 "x.__ne__(y) <==> x!=y"),
4987 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
4988 "x.__gt__(y) <==> x>y"),
4989 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
4990 "x.__ge__(y) <==> x>=y"),
4991 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
4992 "x.__iter__() <==> iter(x)"),
4993 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
4994 "x.next() -> the next value, or raise StopIteration"),
4995 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
4996 "descr.__get__(obj[, type]) -> value"),
4997 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
4998 "descr.__set__(obj, value)"),
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004999 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
5000 wrap_descr_delete, "descr.__delete__(obj)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00005001 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00005002 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00005003 "see x.__class__.__doc__ for signature",
5004 PyWrapperFlag_KEYWORDS),
5005 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005006 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005007 {NULL}
5008};
5009
Guido van Rossumc334df52002-04-04 23:44:47 +00005010/* Given a type pointer and an offset gotten from a slotdef entry, return a
5011 pointer to the actual slot. This is not quite the same as simply adding
5012 the offset to the type pointer, since it takes care to indirect through the
5013 proper indirection pointer (as_buffer, etc.); it returns NULL if the
5014 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005015static void **
5016slotptr(PyTypeObject *type, int offset)
5017{
5018 char *ptr;
5019
Guido van Rossume5c691a2003-03-07 15:13:17 +00005020 /* Note: this depends on the order of the members of PyHeapTypeObject! */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005021 assert(offset >= 0);
Guido van Rossume5c691a2003-03-07 15:13:17 +00005022 assert(offset < offsetof(PyHeapTypeObject, as_buffer));
5023 if (offset >= offsetof(PyHeapTypeObject, as_sequence)) {
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005024 ptr = (void *)type->tp_as_sequence;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005025 offset -= offsetof(PyHeapTypeObject, as_sequence);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005026 }
Guido van Rossume5c691a2003-03-07 15:13:17 +00005027 else if (offset >= offsetof(PyHeapTypeObject, as_mapping)) {
Guido van Rossum09638c12002-06-13 19:17:46 +00005028 ptr = (void *)type->tp_as_mapping;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005029 offset -= offsetof(PyHeapTypeObject, as_mapping);
Guido van Rossum09638c12002-06-13 19:17:46 +00005030 }
Guido van Rossume5c691a2003-03-07 15:13:17 +00005031 else if (offset >= offsetof(PyHeapTypeObject, as_number)) {
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005032 ptr = (void *)type->tp_as_number;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005033 offset -= offsetof(PyHeapTypeObject, as_number);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005034 }
5035 else {
5036 ptr = (void *)type;
5037 }
5038 if (ptr != NULL)
5039 ptr += offset;
5040 return (void **)ptr;
5041}
Guido van Rossumf040ede2001-08-07 16:40:56 +00005042
Guido van Rossumc334df52002-04-04 23:44:47 +00005043/* Length of array of slotdef pointers used to store slots with the
5044 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
5045 the same __name__, for any __name__. Since that's a static property, it is
5046 appropriate to declare fixed-size arrays for this. */
5047#define MAX_EQUIV 10
5048
5049/* Return a slot pointer for a given name, but ONLY if the attribute has
5050 exactly one slot function. The name must be an interned string. */
5051static void **
5052resolve_slotdups(PyTypeObject *type, PyObject *name)
5053{
5054 /* XXX Maybe this could be optimized more -- but is it worth it? */
5055
5056 /* pname and ptrs act as a little cache */
5057 static PyObject *pname;
5058 static slotdef *ptrs[MAX_EQUIV];
5059 slotdef *p, **pp;
5060 void **res, **ptr;
5061
5062 if (pname != name) {
5063 /* Collect all slotdefs that match name into ptrs. */
5064 pname = name;
5065 pp = ptrs;
5066 for (p = slotdefs; p->name_strobj; p++) {
5067 if (p->name_strobj == name)
5068 *pp++ = p;
5069 }
5070 *pp = NULL;
5071 }
5072
5073 /* Look in all matching slots of the type; if exactly one of these has
5074 a filled-in slot, return its value. Otherwise return NULL. */
5075 res = NULL;
5076 for (pp = ptrs; *pp; pp++) {
5077 ptr = slotptr(type, (*pp)->offset);
5078 if (ptr == NULL || *ptr == NULL)
5079 continue;
5080 if (res != NULL)
5081 return NULL;
5082 res = ptr;
5083 }
5084 return res;
5085}
5086
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005087/* Common code for update_slots_callback() and fixup_slot_dispatchers(). This
Guido van Rossumc334df52002-04-04 23:44:47 +00005088 does some incredibly complex thinking and then sticks something into the
5089 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
5090 interests, and then stores a generic wrapper or a specific function into
5091 the slot.) Return a pointer to the next slotdef with a different offset,
5092 because that's convenient for fixup_slot_dispatchers(). */
5093static slotdef *
5094update_one_slot(PyTypeObject *type, slotdef *p)
5095{
5096 PyObject *descr;
5097 PyWrapperDescrObject *d;
5098 void *generic = NULL, *specific = NULL;
5099 int use_generic = 0;
5100 int offset = p->offset;
5101 void **ptr = slotptr(type, offset);
5102
5103 if (ptr == NULL) {
5104 do {
5105 ++p;
5106 } while (p->offset == offset);
5107 return p;
5108 }
5109 do {
5110 descr = _PyType_Lookup(type, p->name_strobj);
5111 if (descr == NULL)
5112 continue;
5113 if (descr->ob_type == &PyWrapperDescr_Type) {
5114 void **tptr = resolve_slotdups(type, p->name_strobj);
5115 if (tptr == NULL || tptr == ptr)
5116 generic = p->function;
5117 d = (PyWrapperDescrObject *)descr;
5118 if (d->d_base->wrapper == p->wrapper &&
5119 PyType_IsSubtype(type, d->d_type))
5120 {
5121 if (specific == NULL ||
5122 specific == d->d_wrapped)
5123 specific = d->d_wrapped;
5124 else
5125 use_generic = 1;
5126 }
5127 }
Guido van Rossum721f62e2002-08-09 02:14:34 +00005128 else if (descr->ob_type == &PyCFunction_Type &&
5129 PyCFunction_GET_FUNCTION(descr) ==
5130 (PyCFunction)tp_new_wrapper &&
5131 strcmp(p->name, "__new__") == 0)
5132 {
5133 /* The __new__ wrapper is not a wrapper descriptor,
5134 so must be special-cased differently.
5135 If we don't do this, creating an instance will
5136 always use slot_tp_new which will look up
5137 __new__ in the MRO which will call tp_new_wrapper
5138 which will look through the base classes looking
5139 for a static base and call its tp_new (usually
5140 PyType_GenericNew), after performing various
5141 sanity checks and constructing a new argument
5142 list. Cut all that nonsense short -- this speeds
5143 up instance creation tremendously. */
Martin v. Löwisa94568a2003-05-10 07:36:56 +00005144 specific = (void *)type->tp_new;
Guido van Rossum721f62e2002-08-09 02:14:34 +00005145 /* XXX I'm not 100% sure that there isn't a hole
5146 in this reasoning that requires additional
5147 sanity checks. I'll buy the first person to
5148 point out a bug in this reasoning a beer. */
5149 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005150 else {
5151 use_generic = 1;
5152 generic = p->function;
5153 }
5154 } while ((++p)->offset == offset);
5155 if (specific && !use_generic)
5156 *ptr = specific;
5157 else
5158 *ptr = generic;
5159 return p;
5160}
5161
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005162/* In the type, update the slots whose slotdefs are gathered in the pp array.
5163 This is a callback for update_subclasses(). */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005164static int
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005165update_slots_callback(PyTypeObject *type, void *data)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005166{
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005167 slotdef **pp = (slotdef **)data;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005168
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005169 for (; *pp; pp++)
Guido van Rossumc334df52002-04-04 23:44:47 +00005170 update_one_slot(type, *pp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005171 return 0;
5172}
5173
Guido van Rossumc334df52002-04-04 23:44:47 +00005174/* Comparison function for qsort() to compare slotdefs by their offset, and
5175 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005176static int
5177slotdef_cmp(const void *aa, const void *bb)
5178{
5179 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
5180 int c = a->offset - b->offset;
5181 if (c != 0)
5182 return c;
5183 else
5184 return a - b;
5185}
5186
Guido van Rossumc334df52002-04-04 23:44:47 +00005187/* Initialize the slotdefs table by adding interned string objects for the
5188 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005189static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005190init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005191{
5192 slotdef *p;
5193 static int initialized = 0;
5194
5195 if (initialized)
5196 return;
5197 for (p = slotdefs; p->name; p++) {
5198 p->name_strobj = PyString_InternFromString(p->name);
5199 if (!p->name_strobj)
Guido van Rossumc334df52002-04-04 23:44:47 +00005200 Py_FatalError("Out of memory interning slotdef names");
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005201 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005202 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
5203 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005204 initialized = 1;
5205}
5206
Guido van Rossumc334df52002-04-04 23:44:47 +00005207/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005208static int
5209update_slot(PyTypeObject *type, PyObject *name)
5210{
Guido van Rossumc334df52002-04-04 23:44:47 +00005211 slotdef *ptrs[MAX_EQUIV];
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005212 slotdef *p;
5213 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005214 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005215
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005216 init_slotdefs();
5217 pp = ptrs;
5218 for (p = slotdefs; p->name; p++) {
5219 /* XXX assume name is interned! */
5220 if (p->name_strobj == name)
5221 *pp++ = p;
5222 }
5223 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005224 for (pp = ptrs; *pp; pp++) {
5225 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005226 offset = p->offset;
5227 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005228 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005229 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005230 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005231 if (ptrs[0] == NULL)
5232 return 0; /* Not an attribute that affects any slots */
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005233 return update_subclasses(type, name,
5234 update_slots_callback, (void *)ptrs);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005235}
5236
Guido van Rossumc334df52002-04-04 23:44:47 +00005237/* Store the proper functions in the slot dispatches at class (type)
5238 definition time, based upon which operations the class overrides in its
5239 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00005240static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005241fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005242{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005243 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005244
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005245 init_slotdefs();
Guido van Rossumc334df52002-04-04 23:44:47 +00005246 for (p = slotdefs; p->name; )
5247 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005248}
Guido van Rossum705f0f52001-08-24 16:47:00 +00005249
Michael W. Hudson98bbc492002-11-26 14:47:27 +00005250static void
5251update_all_slots(PyTypeObject* type)
5252{
5253 slotdef *p;
5254
5255 init_slotdefs();
5256 for (p = slotdefs; p->name; p++) {
5257 /* update_slot returns int but can't actually fail */
5258 update_slot(type, p->name_strobj);
5259 }
5260}
5261
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005262/* recurse_down_subclasses() and update_subclasses() are mutually
5263 recursive functions to call a callback for all subclasses,
5264 but refraining from recursing into subclasses that define 'name'. */
5265
5266static int
5267update_subclasses(PyTypeObject *type, PyObject *name,
5268 update_callback callback, void *data)
5269{
5270 if (callback(type, data) < 0)
5271 return -1;
5272 return recurse_down_subclasses(type, name, callback, data);
5273}
5274
5275static int
5276recurse_down_subclasses(PyTypeObject *type, PyObject *name,
5277 update_callback callback, void *data)
5278{
5279 PyTypeObject *subclass;
5280 PyObject *ref, *subclasses, *dict;
5281 int i, n;
5282
5283 subclasses = type->tp_subclasses;
5284 if (subclasses == NULL)
5285 return 0;
5286 assert(PyList_Check(subclasses));
5287 n = PyList_GET_SIZE(subclasses);
5288 for (i = 0; i < n; i++) {
5289 ref = PyList_GET_ITEM(subclasses, i);
5290 assert(PyWeakref_CheckRef(ref));
5291 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
5292 assert(subclass != NULL);
5293 if ((PyObject *)subclass == Py_None)
5294 continue;
5295 assert(PyType_Check(subclass));
5296 /* Avoid recursing down into unaffected classes */
5297 dict = subclass->tp_dict;
5298 if (dict != NULL && PyDict_Check(dict) &&
5299 PyDict_GetItem(dict, name) != NULL)
5300 continue;
5301 if (update_subclasses(subclass, name, callback, data) < 0)
5302 return -1;
5303 }
5304 return 0;
5305}
5306
Guido van Rossum6d204072001-10-21 00:44:31 +00005307/* This function is called by PyType_Ready() to populate the type's
5308 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00005309 function slot (like tp_repr) that's defined in the type, one or more
5310 corresponding descriptors are added in the type's tp_dict dictionary
5311 under the appropriate name (like __repr__). Some function slots
5312 cause more than one descriptor to be added (for example, the nb_add
5313 slot adds both __add__ and __radd__ descriptors) and some function
5314 slots compete for the same descriptor (for example both sq_item and
5315 mp_subscript generate a __getitem__ descriptor).
5316
5317 In the latter case, the first slotdef entry encoutered wins. Since
Tim Petersbf9b2442003-03-23 05:35:36 +00005318 slotdef entries are sorted by the offset of the slot in the
Guido van Rossume5c691a2003-03-07 15:13:17 +00005319 PyHeapTypeObject, this gives us some control over disambiguating
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005320 between competing slots: the members of PyHeapTypeObject are listed
5321 from most general to least general, so the most general slot is
5322 preferred. In particular, because as_mapping comes before as_sequence,
5323 for a type that defines both mp_subscript and sq_item, mp_subscript
5324 wins.
Guido van Rossum09638c12002-06-13 19:17:46 +00005325
5326 This only adds new descriptors and doesn't overwrite entries in
5327 tp_dict that were previously defined. The descriptors contain a
5328 reference to the C function they must call, so that it's safe if they
5329 are copied into a subtype's __dict__ and the subtype has a different
5330 C function in its slot -- calling the method defined by the
5331 descriptor will call the C function that was used to create it,
5332 rather than the C function present in the slot when it is called.
5333 (This is important because a subtype may have a C function in the
5334 slot that calls the method from the dictionary, and we want to avoid
5335 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00005336
5337static int
5338add_operators(PyTypeObject *type)
5339{
5340 PyObject *dict = type->tp_dict;
5341 slotdef *p;
5342 PyObject *descr;
5343 void **ptr;
5344
5345 init_slotdefs();
5346 for (p = slotdefs; p->name; p++) {
5347 if (p->wrapper == NULL)
5348 continue;
5349 ptr = slotptr(type, p->offset);
5350 if (!ptr || !*ptr)
5351 continue;
5352 if (PyDict_GetItem(dict, p->name_strobj))
5353 continue;
5354 descr = PyDescr_NewWrapper(type, p, *ptr);
5355 if (descr == NULL)
5356 return -1;
5357 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
5358 return -1;
5359 Py_DECREF(descr);
5360 }
5361 if (type->tp_new != NULL) {
5362 if (add_tp_new_wrapper(type) < 0)
5363 return -1;
5364 }
5365 return 0;
5366}
5367
Guido van Rossum705f0f52001-08-24 16:47:00 +00005368
5369/* Cooperative 'super' */
5370
5371typedef struct {
5372 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00005373 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005374 PyObject *obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005375 PyTypeObject *obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005376} superobject;
5377
Guido van Rossum6f799372001-09-20 20:46:19 +00005378static PyMemberDef super_members[] = {
5379 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
5380 "the class invoking super()"},
5381 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
5382 "the instance invoking super(); may be None"},
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005383 {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
5384 "the type of the the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005385 {0}
5386};
5387
Guido van Rossum705f0f52001-08-24 16:47:00 +00005388static void
5389super_dealloc(PyObject *self)
5390{
5391 superobject *su = (superobject *)self;
5392
Guido van Rossum048eb752001-10-02 21:24:57 +00005393 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005394 Py_XDECREF(su->obj);
5395 Py_XDECREF(su->type);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005396 Py_XDECREF(su->obj_type);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005397 self->ob_type->tp_free(self);
5398}
5399
5400static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005401super_repr(PyObject *self)
5402{
5403 superobject *su = (superobject *)self;
5404
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005405 if (su->obj_type)
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005406 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005407 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005408 su->type ? su->type->tp_name : "NULL",
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005409 su->obj_type->tp_name);
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005410 else
5411 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005412 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005413 su->type ? su->type->tp_name : "NULL");
5414}
5415
5416static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00005417super_getattro(PyObject *self, PyObject *name)
5418{
5419 superobject *su = (superobject *)self;
Guido van Rossum76ba09f2003-04-16 19:40:58 +00005420 int skip = su->obj_type == NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005421
Guido van Rossum76ba09f2003-04-16 19:40:58 +00005422 if (!skip) {
5423 /* We want __class__ to return the class of the super object
5424 (i.e. super, or a subclass), not the class of su->obj. */
5425 skip = (PyString_Check(name) &&
5426 PyString_GET_SIZE(name) == 9 &&
5427 strcmp(PyString_AS_STRING(name), "__class__") == 0);
5428 }
5429
5430 if (!skip) {
Tim Petersa91e9642001-11-14 23:32:33 +00005431 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005432 PyTypeObject *starttype;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005433 descrgetfunc f;
5434 int i, n;
5435
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005436 starttype = su->obj_type;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005437 mro = starttype->tp_mro;
5438
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005439 if (mro == NULL)
5440 n = 0;
5441 else {
5442 assert(PyTuple_Check(mro));
5443 n = PyTuple_GET_SIZE(mro);
5444 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005445 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00005446 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00005447 break;
5448 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005449 i++;
5450 res = NULL;
5451 for (; i < n; i++) {
5452 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00005453 if (PyType_Check(tmp))
5454 dict = ((PyTypeObject *)tmp)->tp_dict;
5455 else if (PyClass_Check(tmp))
5456 dict = ((PyClassObject *)tmp)->cl_dict;
5457 else
5458 continue;
5459 res = PyDict_GetItem(dict, name);
Guido van Rossum6cc5bb62003-04-16 20:01:36 +00005460 if (res != NULL) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00005461 Py_INCREF(res);
5462 f = res->ob_type->tp_descr_get;
5463 if (f != NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00005464 tmp = f(res, su->obj,
5465 (PyObject *)starttype);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005466 Py_DECREF(res);
5467 res = tmp;
5468 }
5469 return res;
5470 }
5471 }
5472 }
5473 return PyObject_GenericGetAttr(self, name);
5474}
5475
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005476static PyTypeObject *
Guido van Rossum5b443c62001-12-03 15:38:28 +00005477supercheck(PyTypeObject *type, PyObject *obj)
5478{
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005479 /* Check that a super() call makes sense. Return a type object.
5480
5481 obj can be a new-style class, or an instance of one:
5482
5483 - If it is a class, it must be a subclass of 'type'. This case is
5484 used for class methods; the return value is obj.
5485
5486 - If it is an instance, it must be an instance of 'type'. This is
5487 the normal case; the return value is obj.__class__.
5488
5489 But... when obj is an instance, we want to allow for the case where
5490 obj->ob_type is not a subclass of type, but obj.__class__ is!
5491 This will allow using super() with a proxy for obj.
5492 */
5493
Guido van Rossum8e80a722003-02-18 19:22:22 +00005494 /* Check for first bullet above (special case) */
5495 if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
5496 Py_INCREF(obj);
5497 return (PyTypeObject *)obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005498 }
Guido van Rossum8e80a722003-02-18 19:22:22 +00005499
5500 /* Normal case */
5501 if (PyType_IsSubtype(obj->ob_type, type)) {
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005502 Py_INCREF(obj->ob_type);
5503 return obj->ob_type;
5504 }
5505 else {
5506 /* Try the slow way */
5507 static PyObject *class_str = NULL;
5508 PyObject *class_attr;
5509
5510 if (class_str == NULL) {
5511 class_str = PyString_FromString("__class__");
5512 if (class_str == NULL)
5513 return NULL;
5514 }
5515
5516 class_attr = PyObject_GetAttr(obj, class_str);
5517
5518 if (class_attr != NULL &&
5519 PyType_Check(class_attr) &&
5520 (PyTypeObject *)class_attr != obj->ob_type)
5521 {
5522 int ok = PyType_IsSubtype(
5523 (PyTypeObject *)class_attr, type);
5524 if (ok)
5525 return (PyTypeObject *)class_attr;
5526 }
5527
5528 if (class_attr == NULL)
5529 PyErr_Clear();
5530 else
5531 Py_DECREF(class_attr);
5532 }
5533
Tim Peters97e5ff52003-02-18 19:32:50 +00005534 PyErr_SetString(PyExc_TypeError,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005535 "super(type, obj): "
5536 "obj must be an instance or subtype of type");
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005537 return NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005538}
5539
Guido van Rossum705f0f52001-08-24 16:47:00 +00005540static PyObject *
5541super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5542{
5543 superobject *su = (superobject *)self;
5544 superobject *new;
5545
5546 if (obj == NULL || obj == Py_None || su->obj != NULL) {
5547 /* Not binding to an object, or already bound */
5548 Py_INCREF(self);
5549 return self;
5550 }
Guido van Rossum5b443c62001-12-03 15:38:28 +00005551 if (su->ob_type != &PySuper_Type)
Brett Cannon10147f72003-06-11 20:50:33 +00005552 /* If su is not an instance of a subclass of super,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005553 call its type */
5554 return PyObject_CallFunction((PyObject *)su->ob_type,
5555 "OO", su->type, obj);
5556 else {
5557 /* Inline the common case */
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005558 PyTypeObject *obj_type = supercheck(su->type, obj);
5559 if (obj_type == NULL)
Guido van Rossum5b443c62001-12-03 15:38:28 +00005560 return NULL;
5561 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
5562 NULL, NULL);
5563 if (new == NULL)
5564 return NULL;
5565 Py_INCREF(su->type);
5566 Py_INCREF(obj);
5567 new->type = su->type;
5568 new->obj = obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005569 new->obj_type = obj_type;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005570 return (PyObject *)new;
5571 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005572}
5573
5574static int
5575super_init(PyObject *self, PyObject *args, PyObject *kwds)
5576{
5577 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00005578 PyTypeObject *type;
5579 PyObject *obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005580 PyTypeObject *obj_type = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005581
5582 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
5583 return -1;
5584 if (obj == Py_None)
5585 obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005586 if (obj != NULL) {
5587 obj_type = supercheck(type, obj);
5588 if (obj_type == NULL)
5589 return -1;
5590 Py_INCREF(obj);
5591 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005592 Py_INCREF(type);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005593 su->type = type;
5594 su->obj = obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005595 su->obj_type = obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005596 return 0;
5597}
5598
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005599PyDoc_STRVAR(super_doc,
Guido van Rossum705f0f52001-08-24 16:47:00 +00005600"super(type) -> unbound super object\n"
5601"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00005602"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00005603"Typical use to call a cooperative superclass method:\n"
5604"class C(B):\n"
5605" def meth(self, arg):\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005606" super(C, self).meth(arg)");
Guido van Rossum705f0f52001-08-24 16:47:00 +00005607
Guido van Rossum048eb752001-10-02 21:24:57 +00005608static int
5609super_traverse(PyObject *self, visitproc visit, void *arg)
5610{
5611 superobject *su = (superobject *)self;
5612 int err;
5613
5614#define VISIT(SLOT) \
5615 if (SLOT) { \
5616 err = visit((PyObject *)(SLOT), arg); \
5617 if (err) \
5618 return err; \
5619 }
5620
5621 VISIT(su->obj);
5622 VISIT(su->type);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005623 VISIT(su->obj_type);
Guido van Rossum048eb752001-10-02 21:24:57 +00005624
5625#undef VISIT
5626
5627 return 0;
5628}
5629
Guido van Rossum705f0f52001-08-24 16:47:00 +00005630PyTypeObject PySuper_Type = {
5631 PyObject_HEAD_INIT(&PyType_Type)
5632 0, /* ob_size */
5633 "super", /* tp_name */
5634 sizeof(superobject), /* tp_basicsize */
5635 0, /* tp_itemsize */
5636 /* methods */
5637 super_dealloc, /* tp_dealloc */
5638 0, /* tp_print */
5639 0, /* tp_getattr */
5640 0, /* tp_setattr */
5641 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005642 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005643 0, /* tp_as_number */
5644 0, /* tp_as_sequence */
5645 0, /* tp_as_mapping */
5646 0, /* tp_hash */
5647 0, /* tp_call */
5648 0, /* tp_str */
5649 super_getattro, /* tp_getattro */
5650 0, /* tp_setattro */
5651 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00005652 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
5653 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005654 super_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00005655 super_traverse, /* tp_traverse */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005656 0, /* tp_clear */
5657 0, /* tp_richcompare */
5658 0, /* tp_weaklistoffset */
5659 0, /* tp_iter */
5660 0, /* tp_iternext */
5661 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005662 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005663 0, /* tp_getset */
5664 0, /* tp_base */
5665 0, /* tp_dict */
5666 super_descr_get, /* tp_descr_get */
5667 0, /* tp_descr_set */
5668 0, /* tp_dictoffset */
5669 super_init, /* tp_init */
5670 PyType_GenericAlloc, /* tp_alloc */
5671 PyType_GenericNew, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00005672 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005673};