blob: b0297774b5c21fc860511442f3c218d5f5da0e14 [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
133static int
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000134mro_subclasses(PyTypeObject *type, PyObject* temp)
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000135{
136 PyTypeObject *subclass;
137 PyObject *ref, *subclasses, *old_mro;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000138 int i, n;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000139
140 subclasses = type->tp_subclasses;
141 if (subclasses == NULL)
142 return 0;
143 assert(PyList_Check(subclasses));
144 n = PyList_GET_SIZE(subclasses);
145 for (i = 0; i < n; i++) {
146 ref = PyList_GET_ITEM(subclasses, i);
147 assert(PyWeakref_CheckRef(ref));
148 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
149 assert(subclass != NULL);
150 if ((PyObject *)subclass == Py_None)
151 continue;
152 assert(PyType_Check(subclass));
153 old_mro = subclass->tp_mro;
154 if (mro_internal(subclass) < 0) {
155 subclass->tp_mro = old_mro;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000156 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000157 }
158 else {
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000159 PyObject* tuple;
160 tuple = Py_BuildValue("OO", subclass, old_mro);
161 if (!tuple)
162 return -1;
163 if (PyList_Append(temp, tuple) < 0)
164 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000165 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000166 if (mro_subclasses(subclass, temp) < 0)
167 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000168 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000169 return 0;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000170}
171
172static int
173type_set_bases(PyTypeObject *type, PyObject *value, void *context)
174{
175 int i, r = 0;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000176 PyObject *ob, *temp;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000177 PyTypeObject *new_base, *old_base;
178 PyObject *old_bases, *old_mro;
179
180 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
181 PyErr_Format(PyExc_TypeError,
182 "can't set %s.__bases__", type->tp_name);
183 return -1;
184 }
185 if (!value) {
186 PyErr_Format(PyExc_TypeError,
187 "can't delete %s.__bases__", type->tp_name);
188 return -1;
189 }
190 if (!PyTuple_Check(value)) {
191 PyErr_Format(PyExc_TypeError,
192 "can only assign tuple to %s.__bases__, not %s",
193 type->tp_name, value->ob_type->tp_name);
194 return -1;
195 }
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +0000196 if (PyTuple_GET_SIZE(value) == 0) {
197 PyErr_Format(PyExc_TypeError,
198 "can only assign non-empty tuple to %s.__bases__, not ()",
199 type->tp_name);
200 return -1;
201 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000202 for (i = 0; i < PyTuple_GET_SIZE(value); i++) {
203 ob = PyTuple_GET_ITEM(value, i);
204 if (!PyClass_Check(ob) && !PyType_Check(ob)) {
205 PyErr_Format(
206 PyExc_TypeError,
207 "%s.__bases__ must be tuple of old- or new-style classes, not '%s'",
208 type->tp_name, ob->ob_type->tp_name);
209 return -1;
210 }
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +0000211 if (PyType_Check(ob)) {
212 if (PyType_IsSubtype((PyTypeObject*)ob, type)) {
213 PyErr_SetString(PyExc_TypeError,
214 "a __bases__ item causes an inheritance cycle");
215 return -1;
216 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000217 }
218 }
219
220 new_base = best_base(value);
221
222 if (!new_base) {
223 return -1;
224 }
225
226 if (!compatible_for_assignment(type->tp_base, new_base, "__bases__"))
227 return -1;
228
229 Py_INCREF(new_base);
230 Py_INCREF(value);
231
232 old_bases = type->tp_bases;
233 old_base = type->tp_base;
234 old_mro = type->tp_mro;
235
236 type->tp_bases = value;
237 type->tp_base = new_base;
238
239 if (mro_internal(type) < 0) {
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000240 goto bail;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000241 }
242
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000243 temp = PyList_New(0);
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000244 if (!temp)
245 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000246
247 r = mro_subclasses(type, temp);
248
249 if (r < 0) {
250 for (i = 0; i < PyList_Size(temp); i++) {
251 PyTypeObject* cls;
252 PyObject* mro;
253 PyArg_ParseTuple(PyList_GetItem(temp, i),
254 "OO", &cls, &mro);
255 Py_DECREF(cls->tp_mro);
256 cls->tp_mro = mro;
257 Py_INCREF(cls->tp_mro);
258 }
259 Py_DECREF(temp);
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000260 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000261 }
262
263 Py_DECREF(temp);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000264
265 /* any base that was in __bases__ but now isn't, we
Raymond Hettingera8285862002-12-14 17:17:56 +0000266 need to remove |type| from its tp_subclasses.
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000267 conversely, any class now in __bases__ that wasn't
Raymond Hettingera8285862002-12-14 17:17:56 +0000268 needs to have |type| added to its subclasses. */
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000269
270 /* for now, sod that: just remove from all old_bases,
271 add to all new_bases */
272
273 for (i = PyTuple_GET_SIZE(old_bases) - 1; i >= 0; i--) {
274 ob = PyTuple_GET_ITEM(old_bases, i);
275 if (PyType_Check(ob)) {
276 remove_subclass(
277 (PyTypeObject*)ob, type);
278 }
279 }
280
281 for (i = PyTuple_GET_SIZE(value) - 1; i >= 0; i--) {
282 ob = PyTuple_GET_ITEM(value, i);
283 if (PyType_Check(ob)) {
284 if (add_subclass((PyTypeObject*)ob, type) < 0)
285 r = -1;
286 }
287 }
288
289 update_all_slots(type);
290
291 Py_DECREF(old_bases);
292 Py_DECREF(old_base);
293 Py_DECREF(old_mro);
294
295 return r;
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000296
297 bail:
298 type->tp_bases = old_bases;
299 type->tp_base = old_base;
300 type->tp_mro = old_mro;
Tim Petersea7f75d2002-12-07 21:39:16 +0000301
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000302 Py_DECREF(value);
303 Py_DECREF(new_base);
Tim Petersea7f75d2002-12-07 21:39:16 +0000304
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000305 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000306}
307
308static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000309type_dict(PyTypeObject *type, void *context)
310{
311 if (type->tp_dict == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000312 Py_INCREF(Py_None);
313 return Py_None;
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000314 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000315 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000316}
317
Tim Peters24008312002-03-17 18:56:20 +0000318static PyObject *
319type_get_doc(PyTypeObject *type, void *context)
320{
321 PyObject *result;
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000322 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL)
Tim Peters24008312002-03-17 18:56:20 +0000323 return PyString_FromString(type->tp_doc);
Tim Peters24008312002-03-17 18:56:20 +0000324 result = PyDict_GetItemString(type->tp_dict, "__doc__");
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000325 if (result == NULL) {
326 result = Py_None;
327 Py_INCREF(result);
328 }
329 else if (result->ob_type->tp_descr_get) {
Tim Peters2b858972002-04-18 04:12:28 +0000330 result = result->ob_type->tp_descr_get(result, NULL,
331 (PyObject *)type);
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000332 }
333 else {
334 Py_INCREF(result);
335 }
Tim Peters24008312002-03-17 18:56:20 +0000336 return result;
337}
338
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000339static PyGetSetDef type_getsets[] = {
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000340 {"__name__", (getter)type_name, (setter)type_set_name, NULL},
341 {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL},
Guido van Rossum3926a632001-09-25 16:25:58 +0000342 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000343 {"__dict__", (getter)type_dict, NULL, NULL},
Tim Peters24008312002-03-17 18:56:20 +0000344 {"__doc__", (getter)type_get_doc, NULL, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000345 {0}
346};
347
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000348static int
349type_compare(PyObject *v, PyObject *w)
350{
351 /* This is called with type objects only. So we
352 can just compare the addresses. */
353 Py_uintptr_t vv = (Py_uintptr_t)v;
354 Py_uintptr_t ww = (Py_uintptr_t)w;
355 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
356}
357
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000358static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000359type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000360{
Barry Warsaw7ce36942001-08-24 18:34:26 +0000361 PyObject *mod, *name, *rtn;
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000362 char *kind;
Guido van Rossumc3542212001-08-16 09:18:56 +0000363
364 mod = type_module(type, NULL);
365 if (mod == NULL)
366 PyErr_Clear();
367 else if (!PyString_Check(mod)) {
368 Py_DECREF(mod);
369 mod = NULL;
370 }
371 name = type_name(type, NULL);
372 if (name == NULL)
373 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000374
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000375 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
376 kind = "class";
377 else
378 kind = "type";
379
Barry Warsaw7ce36942001-08-24 18:34:26 +0000380 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__")) {
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000381 rtn = PyString_FromFormat("<%s '%s.%s'>",
382 kind,
Barry Warsaw7ce36942001-08-24 18:34:26 +0000383 PyString_AS_STRING(mod),
384 PyString_AS_STRING(name));
385 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000386 else
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000387 rtn = PyString_FromFormat("<%s '%s'>", kind, type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000388
Guido van Rossumc3542212001-08-16 09:18:56 +0000389 Py_XDECREF(mod);
390 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000391 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000392}
393
Tim Peters6d6c1a32001-08-02 04:15:00 +0000394static PyObject *
395type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
396{
397 PyObject *obj;
398
399 if (type->tp_new == NULL) {
400 PyErr_Format(PyExc_TypeError,
401 "cannot create '%.100s' instances",
402 type->tp_name);
403 return NULL;
404 }
405
Tim Peters3f996e72001-09-13 19:18:27 +0000406 obj = type->tp_new(type, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000407 if (obj != NULL) {
Guido van Rossumf76de622001-10-18 15:49:21 +0000408 /* Ugly exception: when the call was type(something),
409 don't call tp_init on the result. */
410 if (type == &PyType_Type &&
411 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
412 (kwds == NULL ||
413 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
414 return obj;
Guido van Rossum8ace1ab2002-04-06 01:05:01 +0000415 /* If the returned object is not an instance of type,
416 it won't be initialized. */
417 if (!PyType_IsSubtype(obj->ob_type, type))
418 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000419 type = obj->ob_type;
Jeremy Hylton719841e2002-07-16 19:39:38 +0000420 if (PyType_HasFeature(type, Py_TPFLAGS_HAVE_CLASS) &&
421 type->tp_init != NULL &&
Tim Peters6d6c1a32001-08-02 04:15:00 +0000422 type->tp_init(obj, args, kwds) < 0) {
423 Py_DECREF(obj);
424 obj = NULL;
425 }
426 }
427 return obj;
428}
429
430PyObject *
431PyType_GenericAlloc(PyTypeObject *type, int nitems)
432{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000433 PyObject *obj;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000434 const size_t size = _PyObject_VAR_SIZE(type, nitems+1);
435 /* note that we need to add one, for the sentinel */
Tim Peters406fe3b2001-10-06 19:04:01 +0000436
437 if (PyType_IS_GC(type))
Neil Schemenauer09a2ae52002-04-12 03:06:53 +0000438 obj = _PyObject_GC_Malloc(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000439 else
Neil Schemenauerc806c882001-08-29 23:54:54 +0000440 obj = PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000441
Neil Schemenauerc806c882001-08-29 23:54:54 +0000442 if (obj == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000443 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000444
Neil Schemenauerc806c882001-08-29 23:54:54 +0000445 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000446
Tim Peters6d6c1a32001-08-02 04:15:00 +0000447 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
448 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000449
Tim Peters6d6c1a32001-08-02 04:15:00 +0000450 if (type->tp_itemsize == 0)
451 PyObject_INIT(obj, type);
452 else
453 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000454
Tim Peters6d6c1a32001-08-02 04:15:00 +0000455 if (PyType_IS_GC(type))
Neil Schemenauerc806c882001-08-29 23:54:54 +0000456 _PyObject_GC_TRACK(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000457 return obj;
458}
459
460PyObject *
461PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
462{
463 return type->tp_alloc(type, 0);
464}
465
Guido van Rossum9475a232001-10-05 20:51:39 +0000466/* Helpers for subtyping */
467
468static int
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000469traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
470{
471 int i, n;
472 PyMemberDef *mp;
473
474 n = type->ob_size;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000475 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000476 for (i = 0; i < n; i++, mp++) {
477 if (mp->type == T_OBJECT_EX) {
478 char *addr = (char *)self + mp->offset;
479 PyObject *obj = *(PyObject **)addr;
480 if (obj != NULL) {
481 int err = visit(obj, arg);
482 if (err)
483 return err;
484 }
485 }
486 }
487 return 0;
488}
489
490static int
Guido van Rossum9475a232001-10-05 20:51:39 +0000491subtype_traverse(PyObject *self, visitproc visit, void *arg)
492{
493 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000494 traverseproc basetraverse;
Guido van Rossum9475a232001-10-05 20:51:39 +0000495
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000496 /* Find the nearest base with a different tp_traverse,
497 and traverse slots while we're at it */
Guido van Rossum9475a232001-10-05 20:51:39 +0000498 type = self->ob_type;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000499 base = type;
500 while ((basetraverse = base->tp_traverse) == subtype_traverse) {
501 if (base->ob_size) {
502 int err = traverse_slots(base, self, visit, arg);
503 if (err)
504 return err;
505 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000506 base = base->tp_base;
507 assert(base);
508 }
509
510 if (type->tp_dictoffset != base->tp_dictoffset) {
511 PyObject **dictptr = _PyObject_GetDictPtr(self);
512 if (dictptr && *dictptr) {
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000513 int err = visit(*dictptr, arg);
Guido van Rossum9475a232001-10-05 20:51:39 +0000514 if (err)
515 return err;
516 }
517 }
518
Guido van Rossuma3862092002-06-10 15:24:42 +0000519 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
520 /* For a heaptype, the instances count as references
521 to the type. Traverse the type so the collector
522 can find cycles involving this link. */
523 int err = visit((PyObject *)type, arg);
524 if (err)
525 return err;
526 }
527
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000528 if (basetraverse)
529 return basetraverse(self, visit, arg);
530 return 0;
531}
532
533static void
534clear_slots(PyTypeObject *type, PyObject *self)
535{
536 int i, n;
537 PyMemberDef *mp;
538
539 n = type->ob_size;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000540 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000541 for (i = 0; i < n; i++, mp++) {
542 if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
543 char *addr = (char *)self + mp->offset;
544 PyObject *obj = *(PyObject **)addr;
545 if (obj != NULL) {
546 Py_DECREF(obj);
547 *(PyObject **)addr = NULL;
548 }
549 }
550 }
551}
552
553static int
554subtype_clear(PyObject *self)
555{
556 PyTypeObject *type, *base;
557 inquiry baseclear;
558
559 /* Find the nearest base with a different tp_clear
560 and clear slots while we're at it */
561 type = self->ob_type;
562 base = type;
563 while ((baseclear = base->tp_clear) == subtype_clear) {
564 if (base->ob_size)
565 clear_slots(base, self);
566 base = base->tp_base;
567 assert(base);
568 }
569
Guido van Rossuma3862092002-06-10 15:24:42 +0000570 /* There's no need to clear the instance dict (if any);
571 the collector will call its tp_clear handler. */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000572
573 if (baseclear)
574 return baseclear(self);
Guido van Rossum9475a232001-10-05 20:51:39 +0000575 return 0;
576}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000577
578static void
579subtype_dealloc(PyObject *self)
580{
Guido van Rossum14227b42001-12-06 02:35:58 +0000581 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000582 destructor basedealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000583
Guido van Rossum22b13872002-08-06 21:41:44 +0000584 /* Extract the type; we expect it to be a heap type */
585 type = self->ob_type;
586 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000587
Guido van Rossum22b13872002-08-06 21:41:44 +0000588 /* Test whether the type has GC exactly once */
589
590 if (!PyType_IS_GC(type)) {
591 /* It's really rare to find a dynamic type that doesn't have
592 GC; it can only happen when deriving from 'object' and not
593 adding any slots or instance variables. This allows
594 certain simplifications: there's no need to call
595 clear_slots(), or DECREF the dict, or clear weakrefs. */
596
597 /* Maybe call finalizer; exit early if resurrected */
Guido van Rossumfebd61d2002-08-08 20:55:20 +0000598 if (type->tp_del) {
599 type->tp_del(self);
600 if (self->ob_refcnt > 0)
601 return;
602 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000603
604 /* Find the nearest base with a different tp_dealloc */
605 base = type;
606 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
607 assert(base->ob_size == 0);
608 base = base->tp_base;
609 assert(base);
610 }
611
612 /* Call the base tp_dealloc() */
613 assert(basedealloc);
614 basedealloc(self);
615
616 /* Can't reference self beyond this point */
617 Py_DECREF(type);
618
619 /* Done */
620 return;
621 }
622
623 /* We get here only if the type has GC */
624
625 /* UnTrack and re-Track around the trashcan macro, alas */
Andrew M. Kuchlingc9172d32003-02-06 15:22:49 +0000626 /* See explanation at end of function for full disclosure */
Guido van Rossum0906e072002-08-07 20:42:09 +0000627 PyObject_GC_UnTrack(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000628 ++_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000629 Py_TRASHCAN_SAFE_BEGIN(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000630 --_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000631 _PyObject_GC_TRACK(self); /* We'll untrack for real later */
632
633 /* Maybe call finalizer; exit early if resurrected */
Guido van Rossumfebd61d2002-08-08 20:55:20 +0000634 if (type->tp_del) {
635 type->tp_del(self);
636 if (self->ob_refcnt > 0)
637 goto endlabel;
638 }
Guido van Rossum7ad2d1e2001-10-29 22:11:00 +0000639
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000640 /* Find the nearest base with a different tp_dealloc
641 and clear slots while we're at it */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000642 base = type;
643 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
644 if (base->ob_size)
645 clear_slots(base, self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000646 base = base->tp_base;
647 assert(base);
Guido van Rossum14227b42001-12-06 02:35:58 +0000648 }
649
Tim Peters6d6c1a32001-08-02 04:15:00 +0000650 /* If we added a dict, DECREF it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000651 if (type->tp_dictoffset && !base->tp_dictoffset) {
652 PyObject **dictptr = _PyObject_GetDictPtr(self);
653 if (dictptr != NULL) {
654 PyObject *dict = *dictptr;
655 if (dict != NULL) {
656 Py_DECREF(dict);
657 *dictptr = NULL;
658 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000659 }
660 }
661
Guido van Rossum9676b222001-08-17 20:32:36 +0000662 /* If we added weaklist, we clear it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000663 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
Guido van Rossum9676b222001-08-17 20:32:36 +0000664 PyObject_ClearWeakRefs(self);
665
Tim Peters6d6c1a32001-08-02 04:15:00 +0000666 /* Finalize GC if the base doesn't do GC and we do */
Guido van Rossum22b13872002-08-06 21:41:44 +0000667 if (!PyType_IS_GC(base))
Guido van Rossum048eb752001-10-02 21:24:57 +0000668 _PyObject_GC_UNTRACK(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000669
670 /* Call the base tp_dealloc() */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000671 assert(basedealloc);
672 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000673
674 /* Can't reference self beyond this point */
Guido van Rossum22b13872002-08-06 21:41:44 +0000675 Py_DECREF(type);
676
Guido van Rossum0906e072002-08-07 20:42:09 +0000677 endlabel:
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000678 ++_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000679 Py_TRASHCAN_SAFE_END(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000680 --_PyTrash_delete_nesting;
681
682 /* Explanation of the weirdness around the trashcan macros:
683
684 Q. What do the trashcan macros do?
685
686 A. Read the comment titled "Trashcan mechanism" in object.h.
687 For one, this explains why there must be a call to GC-untrack
688 before the trashcan begin macro. Without understanding the
689 trashcan code, the answers to the following questions don't make
690 sense.
691
692 Q. Why do we GC-untrack before the trashcan and then immediately
693 GC-track again afterward?
694
695 A. In the case that the base class is GC-aware, the base class
696 probably GC-untracks the object. If it does that using the
697 UNTRACK macro, this will crash when the object is already
698 untracked. Because we don't know what the base class does, the
699 only safe thing is to make sure the object is tracked when we
700 call the base class dealloc. But... The trashcan begin macro
701 requires that the object is *untracked* before it is called. So
702 the dance becomes:
703
704 GC untrack
705 trashcan begin
706 GC track
707
708 Q. Why the bizarre (net-zero) manipulation of
709 _PyTrash_delete_nesting around the trashcan macros?
710
711 A. Some base classes (e.g. list) also use the trashcan mechanism.
712 The following scenario used to be possible:
713
714 - suppose the trashcan level is one below the trashcan limit
715
716 - subtype_dealloc() is called
717
718 - the trashcan limit is not yet reached, so the trashcan level
719 is incremented and the code between trashcan begin and end is
720 executed
721
722 - this destroys much of the object's contents, including its
723 slots and __dict__
724
725 - basedealloc() is called; this is really list_dealloc(), or
726 some other type which also uses the trashcan macros
727
728 - the trashcan limit is now reached, so the object is put on the
729 trashcan's to-be-deleted-later list
730
731 - basedealloc() returns
732
733 - subtype_dealloc() decrefs the object's type
734
735 - subtype_dealloc() returns
736
737 - later, the trashcan code starts deleting the objects from its
738 to-be-deleted-later list
739
740 - subtype_dealloc() is called *AGAIN* for the same object
741
742 - at the very least (if the destroyed slots and __dict__ don't
743 cause problems) the object's type gets decref'ed a second
744 time, which is *BAD*!!!
745
746 The remedy is to make sure that if the code between trashcan
747 begin and end in subtype_dealloc() is called, the code between
748 trashcan begin and end in basedealloc() will also be called.
749 This is done by decrementing the level after passing into the
750 trashcan block, and incrementing it just before leaving the
751 block.
752
753 But now it's possible that a chain of objects consisting solely
754 of objects whose deallocator is subtype_dealloc() will defeat
755 the trashcan mechanism completely: the decremented level means
756 that the effective level never reaches the limit. Therefore, we
757 *increment* the level *before* entering the trashcan block, and
758 matchingly decrement it after leaving. This means the trashcan
759 code will trigger a little early, but that's no big deal.
760
761 Q. Are there any live examples of code in need of all this
762 complexity?
763
764 A. Yes. See SF bug 668433 for code that crashed (when Python was
765 compiled in debug mode) before the trashcan level manipulations
766 were added. For more discussion, see SF patches 581742, 575073
767 and bug 574207.
768 */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000769}
770
Jeremy Hylton938ace62002-07-17 16:30:39 +0000771static PyTypeObject *solid_base(PyTypeObject *type);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000772
Tim Peters6d6c1a32001-08-02 04:15:00 +0000773/* type test with subclassing support */
774
775int
776PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
777{
778 PyObject *mro;
779
Guido van Rossum9478d072001-09-07 18:52:13 +0000780 if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
781 return b == a || b == &PyBaseObject_Type;
782
Tim Peters6d6c1a32001-08-02 04:15:00 +0000783 mro = a->tp_mro;
784 if (mro != NULL) {
785 /* Deal with multiple inheritance without recursion
786 by walking the MRO tuple */
787 int i, n;
788 assert(PyTuple_Check(mro));
789 n = PyTuple_GET_SIZE(mro);
790 for (i = 0; i < n; i++) {
791 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
792 return 1;
793 }
794 return 0;
795 }
796 else {
797 /* a is not completely initilized yet; follow tp_base */
798 do {
799 if (a == b)
800 return 1;
801 a = a->tp_base;
802 } while (a != NULL);
803 return b == &PyBaseObject_Type;
804 }
805}
806
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000807/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +0000808 without looking in the instance dictionary
809 (so we can't use PyObject_GetAttr) but still binding
810 it to the instance. The arguments are the object,
811 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000812 static variable used to cache the interned Python string.
813
814 Two variants:
815
816 - lookup_maybe() returns NULL without raising an exception
817 when the _PyType_Lookup() call fails;
818
819 - lookup_method() always raises an exception upon errors.
820*/
Guido van Rossum60718732001-08-28 17:47:51 +0000821
822static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000823lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +0000824{
825 PyObject *res;
826
827 if (*attrobj == NULL) {
828 *attrobj = PyString_InternFromString(attrstr);
829 if (*attrobj == NULL)
830 return NULL;
831 }
832 res = _PyType_Lookup(self->ob_type, *attrobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000833 if (res != NULL) {
Guido van Rossum60718732001-08-28 17:47:51 +0000834 descrgetfunc f;
835 if ((f = res->ob_type->tp_descr_get) == NULL)
836 Py_INCREF(res);
837 else
838 res = f(res, self, (PyObject *)(self->ob_type));
839 }
840 return res;
841}
842
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000843static PyObject *
844lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
845{
846 PyObject *res = lookup_maybe(self, attrstr, attrobj);
847 if (res == NULL && !PyErr_Occurred())
848 PyErr_SetObject(PyExc_AttributeError, *attrobj);
849 return res;
850}
851
Guido van Rossum2730b132001-08-28 18:22:14 +0000852/* A variation of PyObject_CallMethod that uses lookup_method()
853 instead of PyObject_GetAttrString(). This uses the same convention
854 as lookup_method to cache the interned name string object. */
855
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000856static PyObject *
Guido van Rossum2730b132001-08-28 18:22:14 +0000857call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
858{
859 va_list va;
860 PyObject *args, *func = 0, *retval;
Guido van Rossum2730b132001-08-28 18:22:14 +0000861 va_start(va, format);
862
Guido van Rossumda21c012001-10-03 00:50:18 +0000863 func = lookup_maybe(o, name, nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000864 if (func == NULL) {
865 va_end(va);
866 if (!PyErr_Occurred())
Guido van Rossumda21c012001-10-03 00:50:18 +0000867 PyErr_SetObject(PyExc_AttributeError, *nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000868 return NULL;
869 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000870
871 if (format && *format)
872 args = Py_VaBuildValue(format, va);
873 else
874 args = PyTuple_New(0);
875
876 va_end(va);
877
878 if (args == NULL)
879 return NULL;
880
881 assert(PyTuple_Check(args));
882 retval = PyObject_Call(func, args, NULL);
883
884 Py_DECREF(args);
885 Py_DECREF(func);
886
887 return retval;
888}
889
890/* Clone of call_method() that returns NotImplemented when the lookup fails. */
891
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000892static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000893call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
894{
895 va_list va;
896 PyObject *args, *func = 0, *retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000897 va_start(va, format);
898
Guido van Rossumda21c012001-10-03 00:50:18 +0000899 func = lookup_maybe(o, name, nameobj);
Guido van Rossum2730b132001-08-28 18:22:14 +0000900 if (func == NULL) {
901 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000902 if (!PyErr_Occurred()) {
903 Py_INCREF(Py_NotImplemented);
904 return Py_NotImplemented;
905 }
Guido van Rossum717ce002001-09-14 16:58:08 +0000906 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +0000907 }
908
909 if (format && *format)
910 args = Py_VaBuildValue(format, va);
911 else
912 args = PyTuple_New(0);
913
914 va_end(va);
915
Guido van Rossum717ce002001-09-14 16:58:08 +0000916 if (args == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +0000917 return NULL;
918
Guido van Rossum717ce002001-09-14 16:58:08 +0000919 assert(PyTuple_Check(args));
920 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +0000921
922 Py_DECREF(args);
923 Py_DECREF(func);
924
925 return retval;
926}
927
Tim Petersa91e9642001-11-14 23:32:33 +0000928static int
929fill_classic_mro(PyObject *mro, PyObject *cls)
930{
931 PyObject *bases, *base;
932 int i, n;
933
934 assert(PyList_Check(mro));
935 assert(PyClass_Check(cls));
936 i = PySequence_Contains(mro, cls);
937 if (i < 0)
938 return -1;
939 if (!i) {
940 if (PyList_Append(mro, cls) < 0)
941 return -1;
942 }
943 bases = ((PyClassObject *)cls)->cl_bases;
944 assert(bases && PyTuple_Check(bases));
945 n = PyTuple_GET_SIZE(bases);
946 for (i = 0; i < n; i++) {
947 base = PyTuple_GET_ITEM(bases, i);
948 if (fill_classic_mro(mro, base) < 0)
949 return -1;
950 }
951 return 0;
952}
953
954static PyObject *
955classic_mro(PyObject *cls)
956{
957 PyObject *mro;
958
959 assert(PyClass_Check(cls));
960 mro = PyList_New(0);
961 if (mro != NULL) {
962 if (fill_classic_mro(mro, cls) == 0)
963 return mro;
964 Py_DECREF(mro);
965 }
966 return NULL;
967}
968
Tim Petersea7f75d2002-12-07 21:39:16 +0000969/*
Guido van Rossum1f121312002-11-14 19:49:16 +0000970 Method resolution order algorithm C3 described in
971 "A Monotonic Superclass Linearization for Dylan",
972 by Kim Barrett, Bob Cassel, Paul Haahr,
Tim Petersea7f75d2002-12-07 21:39:16 +0000973 David A. Moon, Keith Playford, and P. Tucker Withington.
Guido van Rossum1f121312002-11-14 19:49:16 +0000974 (OOPSLA 1996)
975
Guido van Rossum98f33732002-11-25 21:36:54 +0000976 Some notes about the rules implied by C3:
977
Tim Petersea7f75d2002-12-07 21:39:16 +0000978 No duplicate bases.
Guido van Rossum98f33732002-11-25 21:36:54 +0000979 It isn't legal to repeat a class in a list of base classes.
980
981 The next three properties are the 3 constraints in "C3".
982
Tim Petersea7f75d2002-12-07 21:39:16 +0000983 Local precendece order.
Guido van Rossum98f33732002-11-25 21:36:54 +0000984 If A precedes B in C's MRO, then A will precede B in the MRO of all
985 subclasses of C.
986
987 Monotonicity.
988 The MRO of a class must be an extension without reordering of the
989 MRO of each of its superclasses.
990
991 Extended Precedence Graph (EPG).
992 Linearization is consistent if there is a path in the EPG from
993 each class to all its successors in the linearization. See
994 the paper for definition of EPG.
Guido van Rossum1f121312002-11-14 19:49:16 +0000995 */
996
Tim Petersea7f75d2002-12-07 21:39:16 +0000997static int
Guido van Rossum1f121312002-11-14 19:49:16 +0000998tail_contains(PyObject *list, int whence, PyObject *o) {
999 int j, size;
1000 size = PyList_GET_SIZE(list);
1001
1002 for (j = whence+1; j < size; j++) {
1003 if (PyList_GET_ITEM(list, j) == o)
1004 return 1;
1005 }
1006 return 0;
1007}
1008
Guido van Rossum98f33732002-11-25 21:36:54 +00001009static PyObject *
1010class_name(PyObject *cls)
1011{
1012 PyObject *name = PyObject_GetAttrString(cls, "__name__");
1013 if (name == NULL) {
1014 PyErr_Clear();
1015 Py_XDECREF(name);
1016 name = PyObject_Repr(cls);
1017 }
1018 if (name == NULL)
1019 return NULL;
1020 if (!PyString_Check(name)) {
1021 Py_DECREF(name);
1022 return NULL;
1023 }
1024 return name;
1025}
1026
1027static int
1028check_duplicates(PyObject *list)
1029{
1030 int i, j, n;
1031 /* Let's use a quadratic time algorithm,
1032 assuming that the bases lists is short.
1033 */
1034 n = PyList_GET_SIZE(list);
1035 for (i = 0; i < n; i++) {
1036 PyObject *o = PyList_GET_ITEM(list, i);
1037 for (j = i + 1; j < n; j++) {
1038 if (PyList_GET_ITEM(list, j) == o) {
1039 o = class_name(o);
1040 PyErr_Format(PyExc_TypeError,
1041 "duplicate base class %s",
1042 o ? PyString_AS_STRING(o) : "?");
1043 Py_XDECREF(o);
1044 return -1;
1045 }
1046 }
1047 }
1048 return 0;
1049}
1050
1051/* Raise a TypeError for an MRO order disagreement.
1052
1053 It's hard to produce a good error message. In the absence of better
1054 insight into error reporting, report the classes that were candidates
1055 to be put next into the MRO. There is some conflict between the
1056 order in which they should be put in the MRO, but it's hard to
1057 diagnose what constraint can't be satisfied.
1058*/
1059
1060static void
1061set_mro_error(PyObject *to_merge, int *remain)
1062{
1063 int i, n, off, to_merge_size;
1064 char buf[1000];
1065 PyObject *k, *v;
1066 PyObject *set = PyDict_New();
1067
1068 to_merge_size = PyList_GET_SIZE(to_merge);
1069 for (i = 0; i < to_merge_size; i++) {
1070 PyObject *L = PyList_GET_ITEM(to_merge, i);
1071 if (remain[i] < PyList_GET_SIZE(L)) {
1072 PyObject *c = PyList_GET_ITEM(L, remain[i]);
1073 if (PyDict_SetItem(set, c, Py_None) < 0)
1074 return;
1075 }
1076 }
1077 n = PyDict_Size(set);
1078
Raymond Hettinger83245b52003-03-12 04:25:42 +00001079 off = PyOS_snprintf(buf, sizeof(buf), "Cannot create class.\
1080The superclasses have conflicting\n\
1081inheritance trees which leave the method resolution order (MRO)\n\
1082undefined for bases");
Guido van Rossum98f33732002-11-25 21:36:54 +00001083 i = 0;
1084 while (PyDict_Next(set, &i, &k, &v) && off < sizeof(buf)) {
1085 PyObject *name = class_name(k);
1086 off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s",
1087 name ? PyString_AS_STRING(name) : "?");
1088 Py_XDECREF(name);
1089 if (--n && off+1 < sizeof(buf)) {
1090 buf[off++] = ',';
1091 buf[off] = '\0';
1092 }
1093 }
1094 PyErr_SetString(PyExc_TypeError, buf);
1095 Py_DECREF(set);
1096}
1097
Tim Petersea7f75d2002-12-07 21:39:16 +00001098static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001099pmerge(PyObject *acc, PyObject* to_merge) {
1100 int i, j, to_merge_size;
1101 int *remain;
1102 int ok, empty_cnt;
Tim Petersea7f75d2002-12-07 21:39:16 +00001103
Guido van Rossum1f121312002-11-14 19:49:16 +00001104 to_merge_size = PyList_GET_SIZE(to_merge);
1105
Guido van Rossum98f33732002-11-25 21:36:54 +00001106 /* remain stores an index into each sublist of to_merge.
1107 remain[i] is the index of the next base in to_merge[i]
1108 that is not included in acc.
1109 */
Guido van Rossum1f121312002-11-14 19:49:16 +00001110 remain = PyMem_MALLOC(SIZEOF_INT*to_merge_size);
1111 if (remain == NULL)
1112 return -1;
1113 for (i = 0; i < to_merge_size; i++)
1114 remain[i] = 0;
1115
1116 again:
1117 empty_cnt = 0;
1118 for (i = 0; i < to_merge_size; i++) {
1119 PyObject *candidate;
Tim Petersea7f75d2002-12-07 21:39:16 +00001120
Guido van Rossum1f121312002-11-14 19:49:16 +00001121 PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
1122
1123 if (remain[i] >= PyList_GET_SIZE(cur_list)) {
1124 empty_cnt++;
1125 continue;
1126 }
1127
Guido van Rossum98f33732002-11-25 21:36:54 +00001128 /* Choose next candidate for MRO.
1129
1130 The input sequences alone can determine the choice.
1131 If not, choose the class which appears in the MRO
1132 of the earliest direct superclass of the new class.
1133 */
1134
Guido van Rossum1f121312002-11-14 19:49:16 +00001135 candidate = PyList_GET_ITEM(cur_list, remain[i]);
1136 for (j = 0; j < to_merge_size; j++) {
1137 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum98f33732002-11-25 21:36:54 +00001138 if (tail_contains(j_lst, remain[j], candidate)) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001139 goto skip; /* continue outer loop */
Guido van Rossum98f33732002-11-25 21:36:54 +00001140 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001141 }
1142 ok = PyList_Append(acc, candidate);
1143 if (ok < 0) {
1144 PyMem_Free(remain);
1145 return -1;
1146 }
1147 for (j = 0; j < to_merge_size; j++) {
1148 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum768158c2002-12-31 16:33:01 +00001149 if (remain[j] < PyList_GET_SIZE(j_lst) &&
1150 PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001151 remain[j]++;
1152 }
1153 }
1154 goto again;
Tim Peters9a6b8d82002-11-14 23:22:33 +00001155 skip: ;
Guido van Rossum1f121312002-11-14 19:49:16 +00001156 }
1157
Guido van Rossum98f33732002-11-25 21:36:54 +00001158 if (empty_cnt == to_merge_size) {
1159 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001160 return 0;
Guido van Rossum98f33732002-11-25 21:36:54 +00001161 }
1162 set_mro_error(to_merge, remain);
1163 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001164 return -1;
1165}
1166
Tim Peters6d6c1a32001-08-02 04:15:00 +00001167static PyObject *
1168mro_implementation(PyTypeObject *type)
1169{
1170 int i, n, ok;
1171 PyObject *bases, *result;
Guido van Rossum1f121312002-11-14 19:49:16 +00001172 PyObject *to_merge, *bases_aslist;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001173
Guido van Rossum63517572002-06-18 16:44:57 +00001174 if(type->tp_dict == NULL) {
1175 if(PyType_Ready(type) < 0)
1176 return NULL;
1177 }
1178
Guido van Rossum98f33732002-11-25 21:36:54 +00001179 /* Find a superclass linearization that honors the constraints
1180 of the explicit lists of bases and the constraints implied by
Tim Petersea7f75d2002-12-07 21:39:16 +00001181 each base class.
Guido van Rossum98f33732002-11-25 21:36:54 +00001182
1183 to_merge is a list of lists, where each list is a superclass
1184 linearization implied by a base class. The last element of
1185 to_merge is the declared list of bases.
1186 */
1187
Tim Peters6d6c1a32001-08-02 04:15:00 +00001188 bases = type->tp_bases;
1189 n = PyTuple_GET_SIZE(bases);
Guido van Rossum1f121312002-11-14 19:49:16 +00001190
1191 to_merge = PyList_New(n+1);
1192 if (to_merge == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001193 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001194
Tim Peters6d6c1a32001-08-02 04:15:00 +00001195 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001196 PyObject *base = PyTuple_GET_ITEM(bases, i);
1197 PyObject *parentMRO;
1198 if (PyType_Check(base))
1199 parentMRO = PySequence_List(
1200 ((PyTypeObject*)base)->tp_mro);
1201 else
1202 parentMRO = classic_mro(base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001203 if (parentMRO == NULL) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001204 Py_DECREF(to_merge);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001205 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001206 }
1207
1208 PyList_SET_ITEM(to_merge, i, parentMRO);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001209 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001210
1211 bases_aslist = PySequence_List(bases);
1212 if (bases_aslist == NULL) {
1213 Py_DECREF(to_merge);
1214 return NULL;
1215 }
Guido van Rossum98f33732002-11-25 21:36:54 +00001216 /* This is just a basic sanity check. */
1217 if (check_duplicates(bases_aslist) < 0) {
1218 Py_DECREF(to_merge);
1219 Py_DECREF(bases_aslist);
1220 return NULL;
1221 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001222 PyList_SET_ITEM(to_merge, n, bases_aslist);
1223
1224 result = Py_BuildValue("[O]", (PyObject *)type);
1225 if (result == NULL) {
1226 Py_DECREF(to_merge);
1227 return NULL;
1228 }
1229
1230 ok = pmerge(result, to_merge);
1231 Py_DECREF(to_merge);
1232 if (ok < 0) {
1233 Py_DECREF(result);
1234 return NULL;
1235 }
1236
Tim Peters6d6c1a32001-08-02 04:15:00 +00001237 return result;
1238}
1239
1240static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001241mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001242{
1243 PyTypeObject *type = (PyTypeObject *)self;
1244
Tim Peters6d6c1a32001-08-02 04:15:00 +00001245 return mro_implementation(type);
1246}
1247
1248static int
1249mro_internal(PyTypeObject *type)
1250{
1251 PyObject *mro, *result, *tuple;
1252
1253 if (type->ob_type == &PyType_Type) {
1254 result = mro_implementation(type);
1255 }
1256 else {
Guido van Rossum60718732001-08-28 17:47:51 +00001257 static PyObject *mro_str;
1258 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001259 if (mro == NULL)
1260 return -1;
1261 result = PyObject_CallObject(mro, NULL);
1262 Py_DECREF(mro);
1263 }
1264 if (result == NULL)
1265 return -1;
1266 tuple = PySequence_Tuple(result);
1267 Py_DECREF(result);
1268 type->tp_mro = tuple;
1269 return 0;
1270}
1271
1272
1273/* Calculate the best base amongst multiple base classes.
1274 This is the first one that's on the path to the "solid base". */
1275
1276static PyTypeObject *
1277best_base(PyObject *bases)
1278{
1279 int i, n;
1280 PyTypeObject *base, *winner, *candidate, *base_i;
Tim Petersa91e9642001-11-14 23:32:33 +00001281 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001282
1283 assert(PyTuple_Check(bases));
1284 n = PyTuple_GET_SIZE(bases);
1285 assert(n > 0);
Tim Petersa91e9642001-11-14 23:32:33 +00001286 base = NULL;
1287 winner = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001288 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001289 base_proto = PyTuple_GET_ITEM(bases, i);
1290 if (PyClass_Check(base_proto))
1291 continue;
1292 if (!PyType_Check(base_proto)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001293 PyErr_SetString(
1294 PyExc_TypeError,
1295 "bases must be types");
1296 return NULL;
1297 }
Tim Petersa91e9642001-11-14 23:32:33 +00001298 base_i = (PyTypeObject *)base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001299 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001300 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001301 return NULL;
1302 }
1303 candidate = solid_base(base_i);
Tim Petersa91e9642001-11-14 23:32:33 +00001304 if (winner == NULL) {
1305 winner = candidate;
1306 base = base_i;
1307 }
1308 else if (PyType_IsSubtype(winner, candidate))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001309 ;
1310 else if (PyType_IsSubtype(candidate, winner)) {
1311 winner = candidate;
1312 base = base_i;
1313 }
1314 else {
1315 PyErr_SetString(
1316 PyExc_TypeError,
1317 "multiple bases have "
1318 "instance lay-out conflict");
1319 return NULL;
1320 }
1321 }
Guido van Rossume54616c2001-12-14 04:19:56 +00001322 if (base == NULL)
1323 PyErr_SetString(PyExc_TypeError,
1324 "a new-style class can't have only classic bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001325 return base;
1326}
1327
1328static int
1329extra_ivars(PyTypeObject *type, PyTypeObject *base)
1330{
Neil Schemenauerc806c882001-08-29 23:54:54 +00001331 size_t t_size = type->tp_basicsize;
1332 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001333
Guido van Rossum9676b222001-08-17 20:32:36 +00001334 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001335 if (type->tp_itemsize || base->tp_itemsize) {
1336 /* If itemsize is involved, stricter rules */
1337 return t_size != b_size ||
1338 type->tp_itemsize != base->tp_itemsize;
1339 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001340 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
1341 type->tp_weaklistoffset + sizeof(PyObject *) == t_size)
1342 t_size -= sizeof(PyObject *);
1343 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
1344 type->tp_dictoffset + sizeof(PyObject *) == t_size)
1345 t_size -= sizeof(PyObject *);
1346
1347 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001348}
1349
1350static PyTypeObject *
1351solid_base(PyTypeObject *type)
1352{
1353 PyTypeObject *base;
1354
1355 if (type->tp_base)
1356 base = solid_base(type->tp_base);
1357 else
1358 base = &PyBaseObject_Type;
1359 if (extra_ivars(type, base))
1360 return type;
1361 else
1362 return base;
1363}
1364
Jeremy Hylton938ace62002-07-17 16:30:39 +00001365static void object_dealloc(PyObject *);
1366static int object_init(PyObject *, PyObject *, PyObject *);
1367static int update_slot(PyTypeObject *, PyObject *);
1368static void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001369
1370static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001371subtype_dict(PyObject *obj, void *context)
1372{
1373 PyObject **dictptr = _PyObject_GetDictPtr(obj);
1374 PyObject *dict;
1375
1376 if (dictptr == NULL) {
1377 PyErr_SetString(PyExc_AttributeError,
1378 "This object has no __dict__");
1379 return NULL;
1380 }
1381 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +00001382 if (dict == NULL)
1383 *dictptr = dict = PyDict_New();
1384 Py_XINCREF(dict);
1385 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001386}
1387
Guido van Rossum6661be32001-10-26 04:26:12 +00001388static int
1389subtype_setdict(PyObject *obj, PyObject *value, void *context)
1390{
1391 PyObject **dictptr = _PyObject_GetDictPtr(obj);
1392 PyObject *dict;
1393
1394 if (dictptr == NULL) {
1395 PyErr_SetString(PyExc_AttributeError,
1396 "This object has no __dict__");
1397 return -1;
1398 }
Guido van Rossumd331cb52001-12-05 19:46:42 +00001399 if (value != NULL && !PyDict_Check(value)) {
Guido van Rossum6661be32001-10-26 04:26:12 +00001400 PyErr_SetString(PyExc_TypeError,
1401 "__dict__ must be set to a dictionary");
1402 return -1;
1403 }
1404 dict = *dictptr;
Guido van Rossumd331cb52001-12-05 19:46:42 +00001405 Py_XINCREF(value);
Guido van Rossum6661be32001-10-26 04:26:12 +00001406 *dictptr = value;
1407 Py_XDECREF(dict);
1408 return 0;
1409}
1410
Guido van Rossumad47da02002-08-12 19:05:44 +00001411static PyObject *
1412subtype_getweakref(PyObject *obj, void *context)
1413{
1414 PyObject **weaklistptr;
1415 PyObject *result;
1416
1417 if (obj->ob_type->tp_weaklistoffset == 0) {
1418 PyErr_SetString(PyExc_AttributeError,
1419 "This object has no __weaklist__");
1420 return NULL;
1421 }
1422 assert(obj->ob_type->tp_weaklistoffset > 0);
1423 assert(obj->ob_type->tp_weaklistoffset + sizeof(PyObject *) <=
Guido van Rossum3747a0f2002-08-12 19:25:08 +00001424 (size_t)(obj->ob_type->tp_basicsize));
Guido van Rossumad47da02002-08-12 19:05:44 +00001425 weaklistptr = (PyObject **)
Guido van Rossum3747a0f2002-08-12 19:25:08 +00001426 ((char *)obj + obj->ob_type->tp_weaklistoffset);
Guido van Rossumad47da02002-08-12 19:05:44 +00001427 if (*weaklistptr == NULL)
1428 result = Py_None;
1429 else
1430 result = *weaklistptr;
1431 Py_INCREF(result);
1432 return result;
1433}
1434
Guido van Rossum373c7412003-01-07 13:41:37 +00001435/* Three variants on the subtype_getsets list. */
1436
1437static PyGetSetDef subtype_getsets_full[] = {
Guido van Rossumad47da02002-08-12 19:05:44 +00001438 {"__dict__", subtype_dict, subtype_setdict,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001439 PyDoc_STR("dictionary for instance variables (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001440 {"__weakref__", subtype_getweakref, NULL,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001441 PyDoc_STR("list of weak references to the object (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001442 {0}
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001443};
1444
Guido van Rossum373c7412003-01-07 13:41:37 +00001445static PyGetSetDef subtype_getsets_dict_only[] = {
1446 {"__dict__", subtype_dict, subtype_setdict,
1447 PyDoc_STR("dictionary for instance variables (if defined)")},
1448 {0}
1449};
1450
1451static PyGetSetDef subtype_getsets_weakref_only[] = {
1452 {"__weakref__", subtype_getweakref, NULL,
1453 PyDoc_STR("list of weak references to the object (if defined)")},
1454 {0}
1455};
1456
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001457static int
1458valid_identifier(PyObject *s)
1459{
Guido van Rossum03013a02002-07-16 14:30:28 +00001460 unsigned char *p;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001461 int i, n;
1462
1463 if (!PyString_Check(s)) {
1464 PyErr_SetString(PyExc_TypeError,
1465 "__slots__ must be strings");
1466 return 0;
1467 }
Guido van Rossum03013a02002-07-16 14:30:28 +00001468 p = (unsigned char *) PyString_AS_STRING(s);
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001469 n = PyString_GET_SIZE(s);
1470 /* We must reject an empty name. As a hack, we bump the
1471 length to 1 so that the loop will balk on the trailing \0. */
1472 if (n == 0)
1473 n = 1;
1474 for (i = 0; i < n; i++, p++) {
1475 if (!(i == 0 ? isalpha(*p) : isalnum(*p)) && *p != '_') {
1476 PyErr_SetString(PyExc_TypeError,
1477 "__slots__ must be identifiers");
1478 return 0;
1479 }
1480 }
1481 return 1;
1482}
1483
Martin v. Löwisd919a592002-10-14 21:07:28 +00001484#ifdef Py_USING_UNICODE
1485/* Replace Unicode objects in slots. */
1486
1487static PyObject *
1488_unicode_to_string(PyObject *slots, int nslots)
1489{
1490 PyObject *tmp = slots;
1491 PyObject *o, *o1;
1492 int i;
1493 intintargfunc copy = slots->ob_type->tp_as_sequence->sq_slice;
1494 for (i = 0; i < nslots; i++) {
1495 if (PyUnicode_Check(o = PyTuple_GET_ITEM(tmp, i))) {
1496 if (tmp == slots) {
1497 tmp = copy(slots, 0, PyTuple_GET_SIZE(slots));
1498 if (tmp == NULL)
1499 return NULL;
1500 }
1501 o1 = _PyUnicode_AsDefaultEncodedString
1502 (o, NULL);
1503 if (o1 == NULL) {
1504 Py_DECREF(tmp);
1505 return 0;
1506 }
1507 Py_INCREF(o1);
1508 Py_DECREF(o);
1509 PyTuple_SET_ITEM(tmp, i, o1);
1510 }
1511 }
1512 return tmp;
1513}
1514#endif
1515
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001516static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001517type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
1518{
1519 PyObject *name, *bases, *dict;
1520 static char *kwlist[] = {"name", "bases", "dict", 0};
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001521 PyObject *slots, *tmp, *newslots;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001522 PyTypeObject *type, *base, *tmptype, *winner;
Guido van Rossume5c691a2003-03-07 15:13:17 +00001523 PyHeapTypeObject *et;
Guido van Rossum6f799372001-09-20 20:46:19 +00001524 PyMemberDef *mp;
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001525 int i, nbases, nslots, slotoffset, add_dict, add_weak;
Guido van Rossumad47da02002-08-12 19:05:44 +00001526 int j, may_add_dict, may_add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001527
Tim Peters3abca122001-10-27 19:37:48 +00001528 assert(args != NULL && PyTuple_Check(args));
1529 assert(kwds == NULL || PyDict_Check(kwds));
1530
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001531 /* Special case: type(x) should return x->ob_type */
Tim Peters3abca122001-10-27 19:37:48 +00001532 {
1533 const int nargs = PyTuple_GET_SIZE(args);
1534 const int nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
1535
1536 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
1537 PyObject *x = PyTuple_GET_ITEM(args, 0);
1538 Py_INCREF(x->ob_type);
1539 return (PyObject *) x->ob_type;
1540 }
1541
1542 /* SF bug 475327 -- if that didn't trigger, we need 3
1543 arguments. but PyArg_ParseTupleAndKeywords below may give
1544 a msg saying type() needs exactly 3. */
1545 if (nargs + nkwds != 3) {
1546 PyErr_SetString(PyExc_TypeError,
1547 "type() takes 1 or 3 arguments");
1548 return NULL;
1549 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001550 }
1551
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001552 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001553 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
1554 &name,
1555 &PyTuple_Type, &bases,
1556 &PyDict_Type, &dict))
1557 return NULL;
1558
1559 /* Determine the proper metatype to deal with this,
1560 and check for metatype conflicts while we're at it.
1561 Note that if some other metatype wins to contract,
1562 it's possible that its instances are not types. */
1563 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001564 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001565 for (i = 0; i < nbases; i++) {
1566 tmp = PyTuple_GET_ITEM(bases, i);
1567 tmptype = tmp->ob_type;
Tim Petersa91e9642001-11-14 23:32:33 +00001568 if (tmptype == &PyClass_Type)
1569 continue; /* Special case classic classes */
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001570 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001571 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001572 if (PyType_IsSubtype(tmptype, winner)) {
1573 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001574 continue;
1575 }
1576 PyErr_SetString(PyExc_TypeError,
1577 "metatype conflict among bases");
1578 return NULL;
1579 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001580 if (winner != metatype) {
1581 if (winner->tp_new != type_new) /* Pass it to the winner */
1582 return winner->tp_new(winner, args, kwds);
1583 metatype = winner;
1584 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001585
1586 /* Adjust for empty tuple bases */
1587 if (nbases == 0) {
1588 bases = Py_BuildValue("(O)", &PyBaseObject_Type);
1589 if (bases == NULL)
1590 return NULL;
1591 nbases = 1;
1592 }
1593 else
1594 Py_INCREF(bases);
1595
1596 /* XXX From here until type is allocated, "return NULL" leaks bases! */
1597
1598 /* Calculate best base, and check that all bases are type objects */
1599 base = best_base(bases);
1600 if (base == NULL)
1601 return NULL;
1602 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
1603 PyErr_Format(PyExc_TypeError,
1604 "type '%.100s' is not an acceptable base type",
1605 base->tp_name);
1606 return NULL;
1607 }
1608
Tim Peters6d6c1a32001-08-02 04:15:00 +00001609 /* Check for a __slots__ sequence variable in dict, and count it */
1610 slots = PyDict_GetItemString(dict, "__slots__");
1611 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +00001612 add_dict = 0;
1613 add_weak = 0;
Guido van Rossumad47da02002-08-12 19:05:44 +00001614 may_add_dict = base->tp_dictoffset == 0;
1615 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
1616 if (slots == NULL) {
1617 if (may_add_dict) {
1618 add_dict++;
1619 }
1620 if (may_add_weak) {
1621 add_weak++;
1622 }
1623 }
1624 else {
1625 /* Have slots */
1626
Tim Peters6d6c1a32001-08-02 04:15:00 +00001627 /* Make it into a tuple */
1628 if (PyString_Check(slots))
1629 slots = Py_BuildValue("(O)", slots);
1630 else
1631 slots = PySequence_Tuple(slots);
1632 if (slots == NULL)
1633 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00001634 assert(PyTuple_Check(slots));
1635
1636 /* Are slots allowed? */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001637 nslots = PyTuple_GET_SIZE(slots);
Guido van Rossume5c691a2003-03-07 15:13:17 +00001638 if (nslots > 0 && base->tp_itemsize != 0 && !PyType_Check(base)) {
1639 /* for the special case of meta types, allow slots */
Guido van Rossumc4141872001-08-30 04:43:35 +00001640 PyErr_Format(PyExc_TypeError,
1641 "nonempty __slots__ "
1642 "not supported for subtype of '%s'",
1643 base->tp_name);
Guido van Rossumad47da02002-08-12 19:05:44 +00001644 bad_slots:
1645 Py_DECREF(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +00001646 return NULL;
1647 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001648
Martin v. Löwisd919a592002-10-14 21:07:28 +00001649#ifdef Py_USING_UNICODE
1650 tmp = _unicode_to_string(slots, nslots);
Martin v. Löwis13b1a5c2002-10-14 21:11:34 +00001651 if (tmp != slots) {
1652 Py_DECREF(slots);
1653 slots = tmp;
1654 }
Martin v. Löwisd919a592002-10-14 21:07:28 +00001655 if (!tmp)
1656 return NULL;
1657#endif
Guido van Rossumad47da02002-08-12 19:05:44 +00001658 /* Check for valid slot names and two special cases */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001659 for (i = 0; i < nslots; i++) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001660 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
1661 char *s;
1662 if (!valid_identifier(tmp))
1663 goto bad_slots;
1664 assert(PyString_Check(tmp));
1665 s = PyString_AS_STRING(tmp);
1666 if (strcmp(s, "__dict__") == 0) {
1667 if (!may_add_dict || add_dict) {
1668 PyErr_SetString(PyExc_TypeError,
1669 "__dict__ slot disallowed: "
1670 "we already got one");
1671 goto bad_slots;
1672 }
1673 add_dict++;
1674 }
1675 if (strcmp(s, "__weakref__") == 0) {
1676 if (!may_add_weak || add_weak) {
1677 PyErr_SetString(PyExc_TypeError,
1678 "__weakref__ slot disallowed: "
1679 "either we already got one, "
1680 "or __itemsize__ != 0");
1681 goto bad_slots;
1682 }
1683 add_weak++;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001684 }
1685 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001686
Guido van Rossumad47da02002-08-12 19:05:44 +00001687 /* Copy slots into yet another tuple, demangling names */
1688 newslots = PyTuple_New(nslots - add_dict - add_weak);
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001689 if (newslots == NULL)
Guido van Rossumad47da02002-08-12 19:05:44 +00001690 goto bad_slots;
1691 for (i = j = 0; i < nslots; i++) {
1692 char *s;
Guido van Rossum8e829202002-08-16 03:47:49 +00001693 char buffer[256];
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001694 tmp = PyTuple_GET_ITEM(slots, i);
Guido van Rossumad47da02002-08-12 19:05:44 +00001695 s = PyString_AS_STRING(tmp);
1696 if ((add_dict && strcmp(s, "__dict__") == 0) ||
1697 (add_weak && strcmp(s, "__weakref__") == 0))
1698 continue;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001699 if (_Py_Mangle(PyString_AS_STRING(name),
Guido van Rossumad47da02002-08-12 19:05:44 +00001700 PyString_AS_STRING(tmp),
1701 buffer, sizeof(buffer)))
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001702 {
1703 tmp = PyString_FromString(buffer);
1704 } else {
1705 Py_INCREF(tmp);
1706 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001707 PyTuple_SET_ITEM(newslots, j, tmp);
1708 j++;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001709 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001710 assert(j == nslots - add_dict - add_weak);
1711 nslots = j;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001712 Py_DECREF(slots);
1713 slots = newslots;
1714
Guido van Rossumad47da02002-08-12 19:05:44 +00001715 /* Secondary bases may provide weakrefs or dict */
1716 if (nbases > 1 &&
1717 ((may_add_dict && !add_dict) ||
1718 (may_add_weak && !add_weak))) {
1719 for (i = 0; i < nbases; i++) {
1720 tmp = PyTuple_GET_ITEM(bases, i);
1721 if (tmp == (PyObject *)base)
1722 continue; /* Skip primary base */
1723 if (PyClass_Check(tmp)) {
1724 /* Classic base class provides both */
1725 if (may_add_dict && !add_dict)
1726 add_dict++;
1727 if (may_add_weak && !add_weak)
1728 add_weak++;
1729 break;
1730 }
1731 assert(PyType_Check(tmp));
1732 tmptype = (PyTypeObject *)tmp;
1733 if (may_add_dict && !add_dict &&
1734 tmptype->tp_dictoffset != 0)
1735 add_dict++;
1736 if (may_add_weak && !add_weak &&
1737 tmptype->tp_weaklistoffset != 0)
1738 add_weak++;
1739 if (may_add_dict && !add_dict)
1740 continue;
1741 if (may_add_weak && !add_weak)
1742 continue;
1743 /* Nothing more to check */
1744 break;
1745 }
1746 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001747 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001748
1749 /* XXX From here until type is safely allocated,
1750 "return NULL" may leak slots! */
1751
1752 /* Allocate the type object */
1753 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
Guido van Rossumad47da02002-08-12 19:05:44 +00001754 if (type == NULL) {
1755 Py_XDECREF(slots);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001756 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00001757 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001758
1759 /* Keep name and slots alive in the extended type object */
Guido van Rossume5c691a2003-03-07 15:13:17 +00001760 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001761 Py_INCREF(name);
1762 et->name = name;
1763 et->slots = slots;
1764
Guido van Rossumdc91b992001-08-08 22:26:22 +00001765 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001766 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
1767 Py_TPFLAGS_BASETYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00001768 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
1769 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00001770
1771 /* It's a new-style number unless it specifically inherits any
1772 old-style numeric behavior */
1773 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
1774 (base->tp_as_number == NULL))
1775 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
1776
1777 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001778 type->tp_as_number = &et->as_number;
1779 type->tp_as_sequence = &et->as_sequence;
1780 type->tp_as_mapping = &et->as_mapping;
1781 type->tp_as_buffer = &et->as_buffer;
1782 type->tp_name = PyString_AS_STRING(name);
1783
1784 /* Set tp_base and tp_bases */
1785 type->tp_bases = bases;
1786 Py_INCREF(base);
1787 type->tp_base = base;
1788
Guido van Rossum687ae002001-10-15 22:03:32 +00001789 /* Initialize tp_dict from passed-in dict */
1790 type->tp_dict = dict = PyDict_Copy(dict);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001791 if (dict == NULL) {
1792 Py_DECREF(type);
1793 return NULL;
1794 }
1795
Guido van Rossumc3542212001-08-16 09:18:56 +00001796 /* Set __module__ in the dict */
1797 if (PyDict_GetItemString(dict, "__module__") == NULL) {
1798 tmp = PyEval_GetGlobals();
1799 if (tmp != NULL) {
1800 tmp = PyDict_GetItemString(tmp, "__name__");
1801 if (tmp != NULL) {
1802 if (PyDict_SetItemString(dict, "__module__",
1803 tmp) < 0)
1804 return NULL;
1805 }
1806 }
1807 }
1808
Tim Peters2f93e282001-10-04 05:27:00 +00001809 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
Tim Peters24008312002-03-17 18:56:20 +00001810 and is a string. The __doc__ accessor will first look for tp_doc;
1811 if that fails, it will still look into __dict__.
Tim Peters2f93e282001-10-04 05:27:00 +00001812 */
1813 {
1814 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
1815 if (doc != NULL && PyString_Check(doc)) {
1816 const size_t n = (size_t)PyString_GET_SIZE(doc);
Tim Peters59f809d2001-10-04 05:43:02 +00001817 type->tp_doc = (char *)PyObject_MALLOC(n+1);
Tim Peters2f93e282001-10-04 05:27:00 +00001818 if (type->tp_doc == NULL) {
1819 Py_DECREF(type);
1820 return NULL;
1821 }
1822 memcpy(type->tp_doc, PyString_AS_STRING(doc), n+1);
1823 }
1824 }
1825
Tim Peters6d6c1a32001-08-02 04:15:00 +00001826 /* Special-case __new__: if it's a plain function,
1827 make it a static function */
1828 tmp = PyDict_GetItemString(dict, "__new__");
1829 if (tmp != NULL && PyFunction_Check(tmp)) {
1830 tmp = PyStaticMethod_New(tmp);
1831 if (tmp == NULL) {
1832 Py_DECREF(type);
1833 return NULL;
1834 }
1835 PyDict_SetItemString(dict, "__new__", tmp);
1836 Py_DECREF(tmp);
1837 }
1838
1839 /* Add descriptors for custom slots from __slots__, or for __dict__ */
Guido van Rossume5c691a2003-03-07 15:13:17 +00001840 mp = PyHeapType_GET_MEMBERS(et);
Neil Schemenauerc806c882001-08-29 23:54:54 +00001841 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001842 if (slots != NULL) {
1843 for (i = 0; i < nslots; i++, mp++) {
1844 mp->name = PyString_AS_STRING(
1845 PyTuple_GET_ITEM(slots, i));
Guido van Rossum64b206c2001-12-04 17:13:22 +00001846 mp->type = T_OBJECT_EX;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001847 mp->offset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +00001848 if (base->tp_weaklistoffset == 0 &&
Guido van Rossum64b206c2001-12-04 17:13:22 +00001849 strcmp(mp->name, "__weakref__") == 0) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001850 add_weak++;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001851 mp->type = T_OBJECT;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001852 mp->flags = READONLY;
Guido van Rossum9676b222001-08-17 20:32:36 +00001853 type->tp_weaklistoffset = slotoffset;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001854 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001855 slotoffset += sizeof(PyObject *);
1856 }
1857 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001858 if (add_dict) {
1859 if (base->tp_itemsize)
1860 type->tp_dictoffset = -(long)sizeof(PyObject *);
1861 else
1862 type->tp_dictoffset = slotoffset;
1863 slotoffset += sizeof(PyObject *);
1864 }
1865 if (add_weak) {
1866 assert(!base->tp_itemsize);
1867 type->tp_weaklistoffset = slotoffset;
1868 slotoffset += sizeof(PyObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001869 }
1870 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001871 type->tp_itemsize = base->tp_itemsize;
Guido van Rossume5c691a2003-03-07 15:13:17 +00001872 type->tp_members = PyHeapType_GET_MEMBERS(et);
Guido van Rossum373c7412003-01-07 13:41:37 +00001873
1874 if (type->tp_weaklistoffset && type->tp_dictoffset)
1875 type->tp_getset = subtype_getsets_full;
1876 else if (type->tp_weaklistoffset && !type->tp_dictoffset)
1877 type->tp_getset = subtype_getsets_weakref_only;
1878 else if (!type->tp_weaklistoffset && type->tp_dictoffset)
1879 type->tp_getset = subtype_getsets_dict_only;
1880 else
1881 type->tp_getset = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001882
1883 /* Special case some slots */
1884 if (type->tp_dictoffset != 0 || nslots > 0) {
1885 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
1886 type->tp_getattro = PyObject_GenericGetAttr;
1887 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
1888 type->tp_setattro = PyObject_GenericSetAttr;
1889 }
1890 type->tp_dealloc = subtype_dealloc;
1891
Guido van Rossum9475a232001-10-05 20:51:39 +00001892 /* Enable GC unless there are really no instance variables possible */
1893 if (!(type->tp_basicsize == sizeof(PyObject) &&
1894 type->tp_itemsize == 0))
1895 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
1896
Tim Peters6d6c1a32001-08-02 04:15:00 +00001897 /* Always override allocation strategy to use regular heap */
1898 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00001899 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001900 type->tp_free = PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00001901 type->tp_traverse = subtype_traverse;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001902 type->tp_clear = subtype_clear;
Guido van Rossum048eb752001-10-02 21:24:57 +00001903 }
1904 else
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001905 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001906
1907 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001908 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001909 Py_DECREF(type);
1910 return NULL;
1911 }
1912
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001913 /* Put the proper slots in place */
1914 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00001915
Tim Peters6d6c1a32001-08-02 04:15:00 +00001916 return (PyObject *)type;
1917}
1918
1919/* Internal API to look for a name through the MRO.
1920 This returns a borrowed reference, and doesn't set an exception! */
1921PyObject *
1922_PyType_Lookup(PyTypeObject *type, PyObject *name)
1923{
1924 int i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00001925 PyObject *mro, *res, *base, *dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001926
Guido van Rossum687ae002001-10-15 22:03:32 +00001927 /* Look in tp_dict of types in MRO */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001928 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00001929
1930 /* If mro is NULL, the type is either not yet initialized
1931 by PyType_Ready(), or already cleared by type_clear().
1932 Either way the safest thing to do is to return NULL. */
1933 if (mro == NULL)
1934 return NULL;
1935
Tim Peters6d6c1a32001-08-02 04:15:00 +00001936 assert(PyTuple_Check(mro));
1937 n = PyTuple_GET_SIZE(mro);
1938 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001939 base = PyTuple_GET_ITEM(mro, i);
1940 if (PyClass_Check(base))
1941 dict = ((PyClassObject *)base)->cl_dict;
1942 else {
1943 assert(PyType_Check(base));
1944 dict = ((PyTypeObject *)base)->tp_dict;
1945 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001946 assert(dict && PyDict_Check(dict));
1947 res = PyDict_GetItem(dict, name);
1948 if (res != NULL)
1949 return res;
1950 }
1951 return NULL;
1952}
1953
1954/* This is similar to PyObject_GenericGetAttr(),
1955 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
1956static PyObject *
1957type_getattro(PyTypeObject *type, PyObject *name)
1958{
1959 PyTypeObject *metatype = type->ob_type;
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001960 PyObject *meta_attribute, *attribute;
1961 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001962
1963 /* Initialize this type (we'll assume the metatype is initialized) */
1964 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001965 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001966 return NULL;
1967 }
1968
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001969 /* No readable descriptor found yet */
1970 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00001971
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001972 /* Look for the attribute in the metatype */
1973 meta_attribute = _PyType_Lookup(metatype, name);
1974
1975 if (meta_attribute != NULL) {
1976 meta_get = meta_attribute->ob_type->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00001977
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001978 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
1979 /* Data descriptors implement tp_descr_set to intercept
1980 * writes. Assume the attribute is not overridden in
1981 * type's tp_dict (and bases): call the descriptor now.
1982 */
1983 return meta_get(meta_attribute, (PyObject *)type,
1984 (PyObject *)metatype);
1985 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001986 }
1987
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001988 /* No data descriptor found on metatype. Look in tp_dict of this
1989 * type and its bases */
1990 attribute = _PyType_Lookup(type, name);
1991 if (attribute != NULL) {
1992 /* Implement descriptor functionality, if any */
1993 descrgetfunc local_get = attribute->ob_type->tp_descr_get;
1994 if (local_get != NULL) {
1995 /* NULL 2nd argument indicates the descriptor was
1996 * found on the target object itself (or a base) */
1997 return local_get(attribute, (PyObject *)NULL,
1998 (PyObject *)type);
1999 }
Tim Peters34592512002-07-11 06:23:50 +00002000
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002001 Py_INCREF(attribute);
2002 return attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002003 }
2004
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002005 /* No attribute found in local __dict__ (or bases): use the
2006 * descriptor from the metatype, if any */
2007 if (meta_get != NULL)
2008 return meta_get(meta_attribute, (PyObject *)type,
2009 (PyObject *)metatype);
2010
2011 /* If an ordinary attribute was found on the metatype, return it now */
2012 if (meta_attribute != NULL) {
2013 Py_INCREF(meta_attribute);
2014 return meta_attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002015 }
2016
2017 /* Give up */
2018 PyErr_Format(PyExc_AttributeError,
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002019 "type object '%.50s' has no attribute '%.400s'",
2020 type->tp_name, PyString_AS_STRING(name));
Tim Peters6d6c1a32001-08-02 04:15:00 +00002021 return NULL;
2022}
2023
2024static int
2025type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
2026{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002027 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2028 PyErr_Format(
2029 PyExc_TypeError,
2030 "can't set attributes of built-in/extension type '%s'",
2031 type->tp_name);
2032 return -1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002033 }
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002034 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
2035 return -1;
2036 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002037}
2038
2039static void
2040type_dealloc(PyTypeObject *type)
2041{
Guido van Rossume5c691a2003-03-07 15:13:17 +00002042 PyHeapTypeObject *et;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002043
2044 /* Assert this is a heap-allocated type object */
2045 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002046 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00002047 PyObject_ClearWeakRefs((PyObject *)type);
Guido van Rossume5c691a2003-03-07 15:13:17 +00002048 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002049 Py_XDECREF(type->tp_base);
2050 Py_XDECREF(type->tp_dict);
2051 Py_XDECREF(type->tp_bases);
2052 Py_XDECREF(type->tp_mro);
Guido van Rossum687ae002001-10-15 22:03:32 +00002053 Py_XDECREF(type->tp_cache);
Guido van Rossum1c450732001-10-08 15:18:27 +00002054 Py_XDECREF(type->tp_subclasses);
Neal Norwitzcee5ca02002-07-30 00:42:06 +00002055 PyObject_Free(type->tp_doc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002056 Py_XDECREF(et->name);
2057 Py_XDECREF(et->slots);
2058 type->ob_type->tp_free((PyObject *)type);
2059}
2060
Guido van Rossum1c450732001-10-08 15:18:27 +00002061static PyObject *
2062type_subclasses(PyTypeObject *type, PyObject *args_ignored)
2063{
2064 PyObject *list, *raw, *ref;
2065 int i, n;
2066
2067 list = PyList_New(0);
2068 if (list == NULL)
2069 return NULL;
2070 raw = type->tp_subclasses;
2071 if (raw == NULL)
2072 return list;
2073 assert(PyList_Check(raw));
2074 n = PyList_GET_SIZE(raw);
2075 for (i = 0; i < n; i++) {
2076 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00002077 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00002078 ref = PyWeakref_GET_OBJECT(ref);
2079 if (ref != Py_None) {
2080 if (PyList_Append(list, ref) < 0) {
2081 Py_DECREF(list);
2082 return NULL;
2083 }
2084 }
2085 }
2086 return list;
2087}
2088
Tim Peters6d6c1a32001-08-02 04:15:00 +00002089static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002090 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002091 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
Guido van Rossum1c450732001-10-08 15:18:27 +00002092 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002093 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002094 {0}
2095};
2096
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002097PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002098"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002099"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002100
Guido van Rossum048eb752001-10-02 21:24:57 +00002101static int
2102type_traverse(PyTypeObject *type, visitproc visit, void *arg)
2103{
Guido van Rossum048eb752001-10-02 21:24:57 +00002104 int err;
2105
Guido van Rossuma3862092002-06-10 15:24:42 +00002106 /* Because of type_is_gc(), the collector only calls this
2107 for heaptypes. */
2108 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002109
2110#define VISIT(SLOT) \
2111 if (SLOT) { \
2112 err = visit((PyObject *)(SLOT), arg); \
2113 if (err) \
2114 return err; \
2115 }
2116
2117 VISIT(type->tp_dict);
Guido van Rossum687ae002001-10-15 22:03:32 +00002118 VISIT(type->tp_cache);
Guido van Rossum048eb752001-10-02 21:24:57 +00002119 VISIT(type->tp_mro);
2120 VISIT(type->tp_bases);
2121 VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00002122
2123 /* There's no need to visit type->tp_subclasses or
Guido van Rossume5c691a2003-03-07 15:13:17 +00002124 ((PyHeapTypeObject *)type)->slots, because they can't be involved
Guido van Rossuma3862092002-06-10 15:24:42 +00002125 in cycles; tp_subclasses is a list of weak references,
2126 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00002127
2128#undef VISIT
2129
2130 return 0;
2131}
2132
2133static int
2134type_clear(PyTypeObject *type)
2135{
Guido van Rossum048eb752001-10-02 21:24:57 +00002136 PyObject *tmp;
2137
Guido van Rossuma3862092002-06-10 15:24:42 +00002138 /* Because of type_is_gc(), the collector only calls this
2139 for heaptypes. */
2140 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002141
2142#define CLEAR(SLOT) \
2143 if (SLOT) { \
2144 tmp = (PyObject *)(SLOT); \
2145 SLOT = NULL; \
2146 Py_DECREF(tmp); \
2147 }
2148
Guido van Rossuma3862092002-06-10 15:24:42 +00002149 /* The only field we need to clear is tp_mro, which is part of a
2150 hard cycle (its first element is the class itself) that won't
2151 be broken otherwise (it's a tuple and tuples don't have a
2152 tp_clear handler). None of the other fields need to be
2153 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00002154
Guido van Rossuma3862092002-06-10 15:24:42 +00002155 tp_dict:
2156 It is a dict, so the collector will call its tp_clear.
2157
2158 tp_cache:
2159 Not used; if it were, it would be a dict.
2160
2161 tp_bases, tp_base:
2162 If these are involved in a cycle, there must be at least
2163 one other, mutable object in the cycle, e.g. a base
2164 class's dict; the cycle will be broken that way.
2165
2166 tp_subclasses:
2167 A list of weak references can't be part of a cycle; and
2168 lists have their own tp_clear.
2169
Guido van Rossume5c691a2003-03-07 15:13:17 +00002170 slots (in PyHeapTypeObject):
Guido van Rossuma3862092002-06-10 15:24:42 +00002171 A tuple of strings can't be part of a cycle.
2172 */
2173
2174 CLEAR(type->tp_mro);
Tim Peters2f93e282001-10-04 05:27:00 +00002175
Guido van Rossum048eb752001-10-02 21:24:57 +00002176#undef CLEAR
2177
2178 return 0;
2179}
2180
2181static int
2182type_is_gc(PyTypeObject *type)
2183{
2184 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
2185}
2186
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002187PyTypeObject PyType_Type = {
2188 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002189 0, /* ob_size */
2190 "type", /* tp_name */
Guido van Rossume5c691a2003-03-07 15:13:17 +00002191 sizeof(PyHeapTypeObject), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00002192 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002193 (destructor)type_dealloc, /* tp_dealloc */
2194 0, /* tp_print */
2195 0, /* tp_getattr */
2196 0, /* tp_setattr */
2197 type_compare, /* tp_compare */
2198 (reprfunc)type_repr, /* tp_repr */
2199 0, /* tp_as_number */
2200 0, /* tp_as_sequence */
2201 0, /* tp_as_mapping */
2202 (hashfunc)_Py_HashPointer, /* tp_hash */
2203 (ternaryfunc)type_call, /* tp_call */
2204 0, /* tp_str */
2205 (getattrofunc)type_getattro, /* tp_getattro */
2206 (setattrofunc)type_setattro, /* tp_setattro */
2207 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00002208 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2209 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002210 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00002211 (traverseproc)type_traverse, /* tp_traverse */
2212 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002213 0, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00002214 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002215 0, /* tp_iter */
2216 0, /* tp_iternext */
2217 type_methods, /* tp_methods */
2218 type_members, /* tp_members */
2219 type_getsets, /* tp_getset */
2220 0, /* tp_base */
2221 0, /* tp_dict */
2222 0, /* tp_descr_get */
2223 0, /* tp_descr_set */
2224 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
2225 0, /* tp_init */
2226 0, /* tp_alloc */
2227 type_new, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002228 PyObject_GC_Del, /* tp_free */
Guido van Rossum048eb752001-10-02 21:24:57 +00002229 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002230};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002231
2232
2233/* The base type of all types (eventually)... except itself. */
2234
2235static int
2236object_init(PyObject *self, PyObject *args, PyObject *kwds)
2237{
2238 return 0;
2239}
2240
Guido van Rossum298e4212003-02-13 16:30:16 +00002241/* If we don't have a tp_new for a new-style class, new will use this one.
2242 Therefore this should take no arguments/keywords. However, this new may
2243 also be inherited by objects that define a tp_init but no tp_new. These
2244 objects WILL pass argumets to tp_new, because it gets the same args as
2245 tp_init. So only allow arguments if we aren't using the default init, in
2246 which case we expect init to handle argument parsing. */
2247static PyObject *
2248object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2249{
2250 if (type->tp_init == object_init && (PyTuple_GET_SIZE(args) ||
2251 (kwds && PyDict_Check(kwds) && PyDict_Size(kwds)))) {
2252 PyErr_SetString(PyExc_TypeError,
2253 "default __new__ takes no parameters");
2254 return NULL;
2255 }
2256 return type->tp_alloc(type, 0);
2257}
2258
Tim Peters6d6c1a32001-08-02 04:15:00 +00002259static void
2260object_dealloc(PyObject *self)
2261{
2262 self->ob_type->tp_free(self);
2263}
2264
Guido van Rossum8e248182001-08-12 05:17:56 +00002265static PyObject *
2266object_repr(PyObject *self)
2267{
Guido van Rossum76e69632001-08-16 18:52:43 +00002268 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00002269 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002270
Guido van Rossum76e69632001-08-16 18:52:43 +00002271 type = self->ob_type;
2272 mod = type_module(type, NULL);
2273 if (mod == NULL)
2274 PyErr_Clear();
2275 else if (!PyString_Check(mod)) {
2276 Py_DECREF(mod);
2277 mod = NULL;
2278 }
2279 name = type_name(type, NULL);
2280 if (name == NULL)
2281 return NULL;
2282 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002283 rtn = PyString_FromFormat("<%s.%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002284 PyString_AS_STRING(mod),
2285 PyString_AS_STRING(name),
2286 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002287 else
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002288 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002289 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002290 Py_XDECREF(mod);
2291 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00002292 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002293}
2294
Guido van Rossumb8f63662001-08-15 23:57:02 +00002295static PyObject *
2296object_str(PyObject *self)
2297{
2298 unaryfunc f;
2299
2300 f = self->ob_type->tp_repr;
2301 if (f == NULL)
2302 f = object_repr;
2303 return f(self);
2304}
2305
Guido van Rossum8e248182001-08-12 05:17:56 +00002306static long
2307object_hash(PyObject *self)
2308{
2309 return _Py_HashPointer(self);
2310}
Guido van Rossum8e248182001-08-12 05:17:56 +00002311
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002312static PyObject *
2313object_get_class(PyObject *self, void *closure)
2314{
2315 Py_INCREF(self->ob_type);
2316 return (PyObject *)(self->ob_type);
2317}
2318
2319static int
2320equiv_structs(PyTypeObject *a, PyTypeObject *b)
2321{
2322 return a == b ||
2323 (a != NULL &&
2324 b != NULL &&
2325 a->tp_basicsize == b->tp_basicsize &&
2326 a->tp_itemsize == b->tp_itemsize &&
2327 a->tp_dictoffset == b->tp_dictoffset &&
2328 a->tp_weaklistoffset == b->tp_weaklistoffset &&
2329 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
2330 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
2331}
2332
2333static int
2334same_slots_added(PyTypeObject *a, PyTypeObject *b)
2335{
2336 PyTypeObject *base = a->tp_base;
2337 int size;
2338
2339 if (base != b->tp_base)
2340 return 0;
2341 if (equiv_structs(a, base) && equiv_structs(b, base))
2342 return 1;
2343 size = base->tp_basicsize;
2344 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
2345 size += sizeof(PyObject *);
2346 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
2347 size += sizeof(PyObject *);
2348 return size == a->tp_basicsize && size == b->tp_basicsize;
2349}
2350
2351static int
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002352compatible_for_assignment(PyTypeObject* old, PyTypeObject* new, char* attr)
2353{
2354 PyTypeObject *newbase, *oldbase;
2355
2356 if (new->tp_dealloc != old->tp_dealloc ||
2357 new->tp_free != old->tp_free)
2358 {
2359 PyErr_Format(PyExc_TypeError,
2360 "%s assignment: "
2361 "'%s' deallocator differs from '%s'",
2362 attr,
2363 new->tp_name,
2364 old->tp_name);
2365 return 0;
2366 }
2367 newbase = new;
2368 oldbase = old;
2369 while (equiv_structs(newbase, newbase->tp_base))
2370 newbase = newbase->tp_base;
2371 while (equiv_structs(oldbase, oldbase->tp_base))
2372 oldbase = oldbase->tp_base;
2373 if (newbase != oldbase &&
2374 (newbase->tp_base != oldbase->tp_base ||
2375 !same_slots_added(newbase, oldbase))) {
2376 PyErr_Format(PyExc_TypeError,
2377 "%s assignment: "
2378 "'%s' object layout differs from '%s'",
2379 attr,
2380 new->tp_name,
2381 old->tp_name);
2382 return 0;
2383 }
Tim Petersea7f75d2002-12-07 21:39:16 +00002384
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002385 return 1;
2386}
2387
2388static int
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002389object_set_class(PyObject *self, PyObject *value, void *closure)
2390{
2391 PyTypeObject *old = self->ob_type;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002392 PyTypeObject *new;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002393
Guido van Rossumb6b89422002-04-15 01:03:30 +00002394 if (value == NULL) {
2395 PyErr_SetString(PyExc_TypeError,
2396 "can't delete __class__ attribute");
2397 return -1;
2398 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002399 if (!PyType_Check(value)) {
2400 PyErr_Format(PyExc_TypeError,
2401 "__class__ must be set to new-style class, not '%s' object",
2402 value->ob_type->tp_name);
2403 return -1;
2404 }
2405 new = (PyTypeObject *)value;
Guido van Rossum40af8892002-08-10 05:42:07 +00002406 if (!(new->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
2407 !(old->tp_flags & Py_TPFLAGS_HEAPTYPE))
2408 {
2409 PyErr_Format(PyExc_TypeError,
2410 "__class__ assignment: only for heap types");
2411 return -1;
2412 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002413 if (compatible_for_assignment(new, old, "__class__")) {
2414 Py_INCREF(new);
2415 self->ob_type = new;
2416 Py_DECREF(old);
2417 return 0;
2418 }
2419 else {
Guido van Rossum9ee4b942002-05-24 18:47:47 +00002420 return -1;
2421 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002422}
2423
2424static PyGetSetDef object_getsets[] = {
2425 {"__class__", object_get_class, object_set_class,
Neal Norwitz858e34f2002-08-13 17:18:45 +00002426 PyDoc_STR("the object's class")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002427 {0}
2428};
2429
Guido van Rossumc53f0092003-02-18 22:05:12 +00002430
Guido van Rossum036f9992003-02-21 22:02:54 +00002431/* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
2432 We fall back to helpers in copy_reg for:
2433 - pickle protocols < 2
2434 - calculating the list of slot names (done only once per class)
2435 - the __newobj__ function (which is used as a token but never called)
2436*/
2437
2438static PyObject *
2439import_copy_reg(void)
2440{
2441 static PyObject *copy_reg_str;
Guido van Rossum3926a632001-09-25 16:25:58 +00002442
2443 if (!copy_reg_str) {
2444 copy_reg_str = PyString_InternFromString("copy_reg");
2445 if (copy_reg_str == NULL)
2446 return NULL;
2447 }
Guido van Rossum036f9992003-02-21 22:02:54 +00002448
2449 return PyImport_Import(copy_reg_str);
2450}
2451
2452static PyObject *
2453slotnames(PyObject *cls)
2454{
2455 PyObject *clsdict;
2456 PyObject *copy_reg;
2457 PyObject *slotnames;
2458
2459 if (!PyType_Check(cls)) {
2460 Py_INCREF(Py_None);
2461 return Py_None;
2462 }
2463
2464 clsdict = ((PyTypeObject *)cls)->tp_dict;
2465 slotnames = PyDict_GetItemString(clsdict, "__slotnames__");
2466 if (slotnames != NULL) {
2467 Py_INCREF(slotnames);
2468 return slotnames;
2469 }
2470
2471 copy_reg = import_copy_reg();
2472 if (copy_reg == NULL)
2473 return NULL;
2474
2475 slotnames = PyObject_CallMethod(copy_reg, "_slotnames", "O", cls);
2476 Py_DECREF(copy_reg);
2477 if (slotnames != NULL &&
2478 slotnames != Py_None &&
2479 !PyList_Check(slotnames))
2480 {
2481 PyErr_SetString(PyExc_TypeError,
2482 "copy_reg._slotnames didn't return a list or None");
2483 Py_DECREF(slotnames);
2484 slotnames = NULL;
2485 }
2486
2487 return slotnames;
2488}
2489
2490static PyObject *
2491reduce_2(PyObject *obj)
2492{
2493 PyObject *cls, *getnewargs;
2494 PyObject *args = NULL, *args2 = NULL;
2495 PyObject *getstate = NULL, *state = NULL, *names = NULL;
2496 PyObject *slots = NULL, *listitems = NULL, *dictitems = NULL;
2497 PyObject *copy_reg = NULL, *newobj = NULL, *res = NULL;
2498 int i, n;
2499
2500 cls = PyObject_GetAttrString(obj, "__class__");
2501 if (cls == NULL)
2502 return NULL;
2503
2504 getnewargs = PyObject_GetAttrString(obj, "__getnewargs__");
2505 if (getnewargs != NULL) {
2506 args = PyObject_CallObject(getnewargs, NULL);
2507 Py_DECREF(getnewargs);
2508 if (args != NULL && !PyTuple_Check(args)) {
2509 PyErr_SetString(PyExc_TypeError,
2510 "__getnewargs__ should return a tuple");
2511 goto end;
2512 }
2513 }
2514 else {
2515 PyErr_Clear();
2516 args = PyTuple_New(0);
2517 }
2518 if (args == NULL)
2519 goto end;
2520
2521 getstate = PyObject_GetAttrString(obj, "__getstate__");
2522 if (getstate != NULL) {
2523 state = PyObject_CallObject(getstate, NULL);
2524 Py_DECREF(getstate);
2525 }
2526 else {
2527 state = PyObject_GetAttrString(obj, "__dict__");
2528 if (state == NULL) {
2529 PyErr_Clear();
2530 state = Py_None;
2531 Py_INCREF(state);
2532 }
2533 names = slotnames(cls);
2534 if (names == NULL)
2535 goto end;
2536 if (names != Py_None) {
2537 assert(PyList_Check(names));
2538 slots = PyDict_New();
2539 if (slots == NULL)
2540 goto end;
2541 n = 0;
2542 /* Can't pre-compute the list size; the list
2543 is stored on the class so accessible to other
2544 threads, which may be run by DECREF */
2545 for (i = 0; i < PyList_GET_SIZE(names); i++) {
2546 PyObject *name, *value;
2547 name = PyList_GET_ITEM(names, i);
2548 value = PyObject_GetAttr(obj, name);
2549 if (value == NULL)
2550 PyErr_Clear();
2551 else {
2552 int err = PyDict_SetItem(slots, name,
2553 value);
2554 Py_DECREF(value);
2555 if (err)
2556 goto end;
2557 n++;
2558 }
2559 }
2560 if (n) {
2561 state = Py_BuildValue("(NO)", state, slots);
2562 if (state == NULL)
2563 goto end;
2564 }
2565 }
2566 }
2567
2568 if (!PyList_Check(obj)) {
2569 listitems = Py_None;
2570 Py_INCREF(listitems);
2571 }
2572 else {
2573 listitems = PyObject_GetIter(obj);
2574 if (listitems == NULL)
2575 goto end;
2576 }
2577
2578 if (!PyDict_Check(obj)) {
2579 dictitems = Py_None;
2580 Py_INCREF(dictitems);
2581 }
2582 else {
2583 dictitems = PyObject_CallMethod(obj, "iteritems", "");
2584 if (dictitems == NULL)
2585 goto end;
2586 }
2587
2588 copy_reg = import_copy_reg();
2589 if (copy_reg == NULL)
2590 goto end;
2591 newobj = PyObject_GetAttrString(copy_reg, "__newobj__");
2592 if (newobj == NULL)
2593 goto end;
2594
2595 n = PyTuple_GET_SIZE(args);
2596 args2 = PyTuple_New(n+1);
2597 if (args2 == NULL)
2598 goto end;
2599 PyTuple_SET_ITEM(args2, 0, cls);
2600 cls = NULL;
2601 for (i = 0; i < n; i++) {
2602 PyObject *v = PyTuple_GET_ITEM(args, i);
2603 Py_INCREF(v);
2604 PyTuple_SET_ITEM(args2, i+1, v);
2605 }
2606
2607 res = Py_BuildValue("(OOOOO)",
2608 newobj, args2, state, listitems, dictitems);
2609
2610 end:
2611 Py_XDECREF(cls);
2612 Py_XDECREF(args);
2613 Py_XDECREF(args2);
2614 Py_XDECREF(state);
2615 Py_XDECREF(names);
2616 Py_XDECREF(listitems);
2617 Py_XDECREF(dictitems);
2618 Py_XDECREF(copy_reg);
2619 Py_XDECREF(newobj);
2620 return res;
2621}
2622
2623static PyObject *
2624object_reduce_ex(PyObject *self, PyObject *args)
2625{
2626 /* Call copy_reg._reduce_ex(self, proto) */
2627 PyObject *reduce, *copy_reg, *res;
2628 int proto = 0;
2629
2630 if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
2631 return NULL;
2632
2633 reduce = PyObject_GetAttrString(self, "__reduce__");
2634 if (reduce == NULL)
2635 PyErr_Clear();
2636 else {
2637 PyObject *cls, *clsreduce, *objreduce;
2638 int override;
2639 cls = PyObject_GetAttrString(self, "__class__");
2640 if (cls == NULL) {
2641 Py_DECREF(reduce);
2642 return NULL;
2643 }
2644 clsreduce = PyObject_GetAttrString(cls, "__reduce__");
2645 Py_DECREF(cls);
2646 if (clsreduce == NULL) {
2647 Py_DECREF(reduce);
2648 return NULL;
2649 }
2650 objreduce = PyDict_GetItemString(PyBaseObject_Type.tp_dict,
2651 "__reduce__");
2652 override = (clsreduce != objreduce);
2653 Py_DECREF(clsreduce);
2654 if (override) {
2655 res = PyObject_CallObject(reduce, NULL);
2656 Py_DECREF(reduce);
2657 return res;
2658 }
2659 else
2660 Py_DECREF(reduce);
2661 }
2662
2663 if (proto >= 2)
2664 return reduce_2(self);
2665
2666 copy_reg = import_copy_reg();
Guido van Rossum3926a632001-09-25 16:25:58 +00002667 if (!copy_reg)
2668 return NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00002669
Guido van Rossumc53f0092003-02-18 22:05:12 +00002670 res = PyEval_CallMethod(copy_reg, "_reduce_ex", "(Oi)", self, proto);
Guido van Rossum3926a632001-09-25 16:25:58 +00002671 Py_DECREF(copy_reg);
Guido van Rossum036f9992003-02-21 22:02:54 +00002672
Guido van Rossum3926a632001-09-25 16:25:58 +00002673 return res;
2674}
2675
2676static PyMethodDef object_methods[] = {
Guido van Rossumc53f0092003-02-18 22:05:12 +00002677 {"__reduce_ex__", object_reduce_ex, METH_VARARGS,
2678 PyDoc_STR("helper for pickle")},
2679 {"__reduce__", object_reduce_ex, METH_VARARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002680 PyDoc_STR("helper for pickle")},
Guido van Rossum3926a632001-09-25 16:25:58 +00002681 {0}
2682};
2683
Guido van Rossum036f9992003-02-21 22:02:54 +00002684
Tim Peters6d6c1a32001-08-02 04:15:00 +00002685PyTypeObject PyBaseObject_Type = {
2686 PyObject_HEAD_INIT(&PyType_Type)
2687 0, /* ob_size */
2688 "object", /* tp_name */
2689 sizeof(PyObject), /* tp_basicsize */
2690 0, /* tp_itemsize */
2691 (destructor)object_dealloc, /* tp_dealloc */
2692 0, /* tp_print */
2693 0, /* tp_getattr */
2694 0, /* tp_setattr */
2695 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002696 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002697 0, /* tp_as_number */
2698 0, /* tp_as_sequence */
2699 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002700 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002701 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002702 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002703 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002704 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002705 0, /* tp_as_buffer */
2706 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002707 PyDoc_STR("The most base type"), /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002708 0, /* tp_traverse */
2709 0, /* tp_clear */
2710 0, /* tp_richcompare */
2711 0, /* tp_weaklistoffset */
2712 0, /* tp_iter */
2713 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00002714 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002715 0, /* tp_members */
2716 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002717 0, /* tp_base */
2718 0, /* tp_dict */
2719 0, /* tp_descr_get */
2720 0, /* tp_descr_set */
2721 0, /* tp_dictoffset */
2722 object_init, /* tp_init */
2723 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossum298e4212003-02-13 16:30:16 +00002724 object_new, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002725 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002726};
2727
2728
2729/* Initialize the __dict__ in a type object */
2730
2731static int
2732add_methods(PyTypeObject *type, PyMethodDef *meth)
2733{
Guido van Rossum687ae002001-10-15 22:03:32 +00002734 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002735
2736 for (; meth->ml_name != NULL; meth++) {
2737 PyObject *descr;
2738 if (PyDict_GetItemString(dict, meth->ml_name))
2739 continue;
Fred Drake7bf97152002-03-28 05:33:33 +00002740 if (meth->ml_flags & METH_CLASS) {
2741 if (meth->ml_flags & METH_STATIC) {
2742 PyErr_SetString(PyExc_ValueError,
2743 "method cannot be both class and static");
2744 return -1;
2745 }
Tim Petersbca1cbc2002-12-09 22:56:13 +00002746 descr = PyDescr_NewClassMethod(type, meth);
Fred Drake7bf97152002-03-28 05:33:33 +00002747 }
2748 else if (meth->ml_flags & METH_STATIC) {
Guido van Rossum9af48ff2003-02-11 17:12:46 +00002749 PyObject *cfunc = PyCFunction_New(meth, NULL);
2750 if (cfunc == NULL)
2751 return -1;
2752 descr = PyStaticMethod_New(cfunc);
2753 Py_DECREF(cfunc);
Fred Drake7bf97152002-03-28 05:33:33 +00002754 }
2755 else {
2756 descr = PyDescr_NewMethod(type, meth);
2757 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002758 if (descr == NULL)
2759 return -1;
Fred Drake7bf97152002-03-28 05:33:33 +00002760 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002761 return -1;
2762 Py_DECREF(descr);
2763 }
2764 return 0;
2765}
2766
2767static int
Guido van Rossum6f799372001-09-20 20:46:19 +00002768add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002769{
Guido van Rossum687ae002001-10-15 22:03:32 +00002770 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002771
2772 for (; memb->name != NULL; memb++) {
2773 PyObject *descr;
2774 if (PyDict_GetItemString(dict, memb->name))
2775 continue;
2776 descr = PyDescr_NewMember(type, memb);
2777 if (descr == NULL)
2778 return -1;
2779 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
2780 return -1;
2781 Py_DECREF(descr);
2782 }
2783 return 0;
2784}
2785
2786static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00002787add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002788{
Guido van Rossum687ae002001-10-15 22:03:32 +00002789 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002790
2791 for (; gsp->name != NULL; gsp++) {
2792 PyObject *descr;
2793 if (PyDict_GetItemString(dict, gsp->name))
2794 continue;
2795 descr = PyDescr_NewGetSet(type, gsp);
2796
2797 if (descr == NULL)
2798 return -1;
2799 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
2800 return -1;
2801 Py_DECREF(descr);
2802 }
2803 return 0;
2804}
2805
Guido van Rossum13d52f02001-08-10 21:24:08 +00002806static void
2807inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002808{
2809 int oldsize, newsize;
2810
Guido van Rossum13d52f02001-08-10 21:24:08 +00002811 /* Special flag magic */
2812 if (!type->tp_as_buffer && base->tp_as_buffer) {
2813 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
2814 type->tp_flags |=
2815 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
2816 }
2817 if (!type->tp_as_sequence && base->tp_as_sequence) {
2818 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
2819 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
2820 }
2821 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
2822 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
2823 if ((!type->tp_as_number && base->tp_as_number) ||
2824 (!type->tp_as_sequence && base->tp_as_sequence)) {
2825 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
2826 if (!type->tp_as_number && !type->tp_as_sequence) {
2827 type->tp_flags |= base->tp_flags &
2828 Py_TPFLAGS_HAVE_INPLACEOPS;
2829 }
2830 }
2831 /* Wow */
2832 }
2833 if (!type->tp_as_number && base->tp_as_number) {
2834 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
2835 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
2836 }
2837
2838 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00002839 oldsize = base->tp_basicsize;
2840 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
2841 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
2842 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00002843 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
2844 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00002845 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00002846 if (type->tp_traverse == NULL)
2847 type->tp_traverse = base->tp_traverse;
2848 if (type->tp_clear == NULL)
2849 type->tp_clear = base->tp_clear;
2850 }
2851 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
Guido van Rossumf884b742001-12-17 17:14:22 +00002852 /* The condition below could use some explanation.
2853 It appears that tp_new is not inherited for static types
2854 whose base class is 'object'; this seems to be a precaution
2855 so that old extension types don't suddenly become
2856 callable (object.__new__ wouldn't insure the invariants
2857 that the extension type's own factory function ensures).
2858 Heap types, of course, are under our control, so they do
2859 inherit tp_new; static extension types that specify some
2860 other built-in type as the default are considered
2861 new-style-aware so they also inherit object.__new__. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002862 if (base != &PyBaseObject_Type ||
2863 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2864 if (type->tp_new == NULL)
2865 type->tp_new = base->tp_new;
2866 }
2867 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00002868 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00002869
2870 /* Copy other non-function slots */
2871
2872#undef COPYVAL
2873#define COPYVAL(SLOT) \
2874 if (type->SLOT == 0) type->SLOT = base->SLOT
2875
2876 COPYVAL(tp_itemsize);
2877 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
2878 COPYVAL(tp_weaklistoffset);
2879 }
2880 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2881 COPYVAL(tp_dictoffset);
2882 }
Guido van Rossum13d52f02001-08-10 21:24:08 +00002883}
2884
2885static void
2886inherit_slots(PyTypeObject *type, PyTypeObject *base)
2887{
2888 PyTypeObject *basebase;
2889
2890#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00002891#undef COPYSLOT
2892#undef COPYNUM
2893#undef COPYSEQ
2894#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00002895#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00002896
2897#define SLOTDEFINED(SLOT) \
2898 (base->SLOT != 0 && \
2899 (basebase == NULL || base->SLOT != basebase->SLOT))
2900
Tim Peters6d6c1a32001-08-02 04:15:00 +00002901#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00002902 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00002903
2904#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
2905#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
2906#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00002907#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002908
Guido van Rossum13d52f02001-08-10 21:24:08 +00002909 /* This won't inherit indirect slots (from tp_as_number etc.)
2910 if type doesn't provide the space. */
2911
2912 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
2913 basebase = base->tp_base;
2914 if (basebase->tp_as_number == NULL)
2915 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002916 COPYNUM(nb_add);
2917 COPYNUM(nb_subtract);
2918 COPYNUM(nb_multiply);
2919 COPYNUM(nb_divide);
2920 COPYNUM(nb_remainder);
2921 COPYNUM(nb_divmod);
2922 COPYNUM(nb_power);
2923 COPYNUM(nb_negative);
2924 COPYNUM(nb_positive);
2925 COPYNUM(nb_absolute);
2926 COPYNUM(nb_nonzero);
2927 COPYNUM(nb_invert);
2928 COPYNUM(nb_lshift);
2929 COPYNUM(nb_rshift);
2930 COPYNUM(nb_and);
2931 COPYNUM(nb_xor);
2932 COPYNUM(nb_or);
2933 COPYNUM(nb_coerce);
2934 COPYNUM(nb_int);
2935 COPYNUM(nb_long);
2936 COPYNUM(nb_float);
2937 COPYNUM(nb_oct);
2938 COPYNUM(nb_hex);
2939 COPYNUM(nb_inplace_add);
2940 COPYNUM(nb_inplace_subtract);
2941 COPYNUM(nb_inplace_multiply);
2942 COPYNUM(nb_inplace_divide);
2943 COPYNUM(nb_inplace_remainder);
2944 COPYNUM(nb_inplace_power);
2945 COPYNUM(nb_inplace_lshift);
2946 COPYNUM(nb_inplace_rshift);
2947 COPYNUM(nb_inplace_and);
2948 COPYNUM(nb_inplace_xor);
2949 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00002950 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
2951 COPYNUM(nb_true_divide);
2952 COPYNUM(nb_floor_divide);
2953 COPYNUM(nb_inplace_true_divide);
2954 COPYNUM(nb_inplace_floor_divide);
2955 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002956 }
2957
Guido van Rossum13d52f02001-08-10 21:24:08 +00002958 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
2959 basebase = base->tp_base;
2960 if (basebase->tp_as_sequence == NULL)
2961 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002962 COPYSEQ(sq_length);
2963 COPYSEQ(sq_concat);
2964 COPYSEQ(sq_repeat);
2965 COPYSEQ(sq_item);
2966 COPYSEQ(sq_slice);
2967 COPYSEQ(sq_ass_item);
2968 COPYSEQ(sq_ass_slice);
2969 COPYSEQ(sq_contains);
2970 COPYSEQ(sq_inplace_concat);
2971 COPYSEQ(sq_inplace_repeat);
2972 }
2973
Guido van Rossum13d52f02001-08-10 21:24:08 +00002974 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
2975 basebase = base->tp_base;
2976 if (basebase->tp_as_mapping == NULL)
2977 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002978 COPYMAP(mp_length);
2979 COPYMAP(mp_subscript);
2980 COPYMAP(mp_ass_subscript);
2981 }
2982
Tim Petersfc57ccb2001-10-12 02:38:24 +00002983 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
2984 basebase = base->tp_base;
2985 if (basebase->tp_as_buffer == NULL)
2986 basebase = NULL;
2987 COPYBUF(bf_getreadbuffer);
2988 COPYBUF(bf_getwritebuffer);
2989 COPYBUF(bf_getsegcount);
2990 COPYBUF(bf_getcharbuffer);
2991 }
2992
Guido van Rossum13d52f02001-08-10 21:24:08 +00002993 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002994
Tim Peters6d6c1a32001-08-02 04:15:00 +00002995 COPYSLOT(tp_dealloc);
2996 COPYSLOT(tp_print);
2997 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
2998 type->tp_getattr = base->tp_getattr;
2999 type->tp_getattro = base->tp_getattro;
3000 }
3001 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
3002 type->tp_setattr = base->tp_setattr;
3003 type->tp_setattro = base->tp_setattro;
3004 }
3005 /* tp_compare see tp_richcompare */
3006 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003007 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003008 COPYSLOT(tp_call);
3009 COPYSLOT(tp_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003010 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003011 if (type->tp_compare == NULL &&
3012 type->tp_richcompare == NULL &&
3013 type->tp_hash == NULL)
3014 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003015 type->tp_compare = base->tp_compare;
3016 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003017 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003018 }
3019 }
3020 else {
3021 COPYSLOT(tp_compare);
3022 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003023 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
3024 COPYSLOT(tp_iter);
3025 COPYSLOT(tp_iternext);
3026 }
3027 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
3028 COPYSLOT(tp_descr_get);
3029 COPYSLOT(tp_descr_set);
3030 COPYSLOT(tp_dictoffset);
3031 COPYSLOT(tp_init);
3032 COPYSLOT(tp_alloc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003033 COPYSLOT(tp_free);
Guido van Rossumcc8fe042002-04-05 17:10:16 +00003034 COPYSLOT(tp_is_gc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003035 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003036}
3037
Jeremy Hylton938ace62002-07-17 16:30:39 +00003038static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00003039
Tim Peters6d6c1a32001-08-02 04:15:00 +00003040int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00003041PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003042{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003043 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003044 PyTypeObject *base;
3045 int i, n;
3046
Guido van Rossumcab05802002-06-10 15:29:03 +00003047 if (type->tp_flags & Py_TPFLAGS_READY) {
3048 assert(type->tp_dict != NULL);
Guido van Rossumd614f972001-08-10 17:39:49 +00003049 return 0;
Guido van Rossumcab05802002-06-10 15:29:03 +00003050 }
Guido van Rossumd614f972001-08-10 17:39:49 +00003051 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00003052
3053 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003054
3055 /* Initialize tp_base (defaults to BaseObject unless that's us) */
3056 base = type->tp_base;
3057 if (base == NULL && type != &PyBaseObject_Type)
3058 base = type->tp_base = &PyBaseObject_Type;
3059
Guido van Rossum323a9cf2002-08-14 17:26:30 +00003060 /* Initialize the base class */
3061 if (base && base->tp_dict == NULL) {
3062 if (PyType_Ready(base) < 0)
3063 goto error;
3064 }
3065
Guido van Rossum0986d822002-04-08 01:38:42 +00003066 /* Initialize ob_type if NULL. This means extensions that want to be
3067 compilable separately on Windows can call PyType_Ready() instead of
3068 initializing the ob_type field of their type objects. */
3069 if (type->ob_type == NULL)
3070 type->ob_type = base->ob_type;
3071
Tim Peters6d6c1a32001-08-02 04:15:00 +00003072 /* Initialize tp_bases */
3073 bases = type->tp_bases;
3074 if (bases == NULL) {
3075 if (base == NULL)
3076 bases = PyTuple_New(0);
3077 else
3078 bases = Py_BuildValue("(O)", base);
3079 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003080 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003081 type->tp_bases = bases;
3082 }
3083
Guido van Rossum687ae002001-10-15 22:03:32 +00003084 /* Initialize tp_dict */
3085 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003086 if (dict == NULL) {
3087 dict = PyDict_New();
3088 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003089 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00003090 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003091 }
3092
Guido van Rossum687ae002001-10-15 22:03:32 +00003093 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003094 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003095 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003096 if (type->tp_methods != NULL) {
3097 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003098 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003099 }
3100 if (type->tp_members != NULL) {
3101 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003102 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003103 }
3104 if (type->tp_getset != NULL) {
3105 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003106 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003107 }
3108
Tim Peters6d6c1a32001-08-02 04:15:00 +00003109 /* Calculate method resolution order */
3110 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00003111 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003112 }
3113
Guido van Rossum13d52f02001-08-10 21:24:08 +00003114 /* Inherit special flags from dominant base */
3115 if (type->tp_base != NULL)
3116 inherit_special(type, type->tp_base);
3117
Tim Peters6d6c1a32001-08-02 04:15:00 +00003118 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003119 bases = type->tp_mro;
3120 assert(bases != NULL);
3121 assert(PyTuple_Check(bases));
3122 n = PyTuple_GET_SIZE(bases);
3123 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003124 PyObject *b = PyTuple_GET_ITEM(bases, i);
3125 if (PyType_Check(b))
3126 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003127 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003128
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003129 /* if the type dictionary doesn't contain a __doc__, set it from
3130 the tp_doc slot.
3131 */
3132 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
3133 if (type->tp_doc != NULL) {
3134 PyObject *doc = PyString_FromString(type->tp_doc);
3135 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
3136 Py_DECREF(doc);
3137 } else {
Guido van Rossumd4641072002-04-03 02:13:37 +00003138 PyDict_SetItemString(type->tp_dict,
3139 "__doc__", Py_None);
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003140 }
3141 }
3142
Guido van Rossum13d52f02001-08-10 21:24:08 +00003143 /* Some more special stuff */
3144 base = type->tp_base;
3145 if (base != NULL) {
3146 if (type->tp_as_number == NULL)
3147 type->tp_as_number = base->tp_as_number;
3148 if (type->tp_as_sequence == NULL)
3149 type->tp_as_sequence = base->tp_as_sequence;
3150 if (type->tp_as_mapping == NULL)
3151 type->tp_as_mapping = base->tp_as_mapping;
Guido van Rossumeea47182003-02-11 20:39:59 +00003152 if (type->tp_as_buffer == NULL)
3153 type->tp_as_buffer = base->tp_as_buffer;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003154 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003155
Guido van Rossum1c450732001-10-08 15:18:27 +00003156 /* Link into each base class's list of subclasses */
3157 bases = type->tp_bases;
3158 n = PyTuple_GET_SIZE(bases);
3159 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003160 PyObject *b = PyTuple_GET_ITEM(bases, i);
3161 if (PyType_Check(b) &&
3162 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00003163 goto error;
3164 }
3165
Guido van Rossum13d52f02001-08-10 21:24:08 +00003166 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00003167 assert(type->tp_dict != NULL);
3168 type->tp_flags =
3169 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003170 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00003171
3172 error:
3173 type->tp_flags &= ~Py_TPFLAGS_READYING;
3174 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003175}
3176
Guido van Rossum1c450732001-10-08 15:18:27 +00003177static int
3178add_subclass(PyTypeObject *base, PyTypeObject *type)
3179{
3180 int i;
3181 PyObject *list, *ref, *new;
3182
3183 list = base->tp_subclasses;
3184 if (list == NULL) {
3185 base->tp_subclasses = list = PyList_New(0);
3186 if (list == NULL)
3187 return -1;
3188 }
3189 assert(PyList_Check(list));
3190 new = PyWeakref_NewRef((PyObject *)type, NULL);
3191 i = PyList_GET_SIZE(list);
3192 while (--i >= 0) {
3193 ref = PyList_GET_ITEM(list, i);
3194 assert(PyWeakref_CheckRef(ref));
Guido van Rossum3930bc32002-10-18 13:51:49 +00003195 if (PyWeakref_GET_OBJECT(ref) == Py_None)
3196 return PyList_SetItem(list, i, new);
Guido van Rossum1c450732001-10-08 15:18:27 +00003197 }
3198 i = PyList_Append(list, new);
3199 Py_DECREF(new);
3200 return i;
3201}
3202
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003203static void
3204remove_subclass(PyTypeObject *base, PyTypeObject *type)
3205{
3206 int i;
3207 PyObject *list, *ref;
3208
3209 list = base->tp_subclasses;
3210 if (list == NULL) {
3211 return;
3212 }
3213 assert(PyList_Check(list));
3214 i = PyList_GET_SIZE(list);
3215 while (--i >= 0) {
3216 ref = PyList_GET_ITEM(list, i);
3217 assert(PyWeakref_CheckRef(ref));
3218 if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
3219 /* this can't fail, right? */
3220 PySequence_DelItem(list, i);
3221 return;
3222 }
3223 }
3224}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003225
3226/* Generic wrappers for overloadable 'operators' such as __getitem__ */
3227
3228/* There's a wrapper *function* for each distinct function typedef used
3229 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
3230 wrapper *table* for each distinct operation (e.g. __len__, __add__).
3231 Most tables have only one entry; the tables for binary operators have two
3232 entries, one regular and one with reversed arguments. */
3233
3234static PyObject *
3235wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
3236{
3237 inquiry func = (inquiry)wrapped;
3238 int res;
3239
3240 if (!PyArg_ParseTuple(args, ""))
3241 return NULL;
3242 res = (*func)(self);
3243 if (res == -1 && PyErr_Occurred())
3244 return NULL;
3245 return PyInt_FromLong((long)res);
3246}
3247
Tim Peters6d6c1a32001-08-02 04:15:00 +00003248static PyObject *
3249wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
3250{
3251 binaryfunc func = (binaryfunc)wrapped;
3252 PyObject *other;
3253
3254 if (!PyArg_ParseTuple(args, "O", &other))
3255 return NULL;
3256 return (*func)(self, other);
3257}
3258
3259static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003260wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
3261{
3262 binaryfunc func = (binaryfunc)wrapped;
3263 PyObject *other;
3264
3265 if (!PyArg_ParseTuple(args, "O", &other))
3266 return NULL;
3267 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003268 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003269 Py_INCREF(Py_NotImplemented);
3270 return Py_NotImplemented;
3271 }
3272 return (*func)(self, other);
3273}
3274
3275static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003276wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3277{
3278 binaryfunc func = (binaryfunc)wrapped;
3279 PyObject *other;
3280
3281 if (!PyArg_ParseTuple(args, "O", &other))
3282 return NULL;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003283 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003284 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003285 Py_INCREF(Py_NotImplemented);
3286 return Py_NotImplemented;
3287 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003288 return (*func)(other, self);
3289}
3290
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003291static PyObject *
3292wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
3293{
3294 coercion func = (coercion)wrapped;
3295 PyObject *other, *res;
3296 int ok;
3297
3298 if (!PyArg_ParseTuple(args, "O", &other))
3299 return NULL;
3300 ok = func(&self, &other);
3301 if (ok < 0)
3302 return NULL;
3303 if (ok > 0) {
3304 Py_INCREF(Py_NotImplemented);
3305 return Py_NotImplemented;
3306 }
3307 res = PyTuple_New(2);
3308 if (res == NULL) {
3309 Py_DECREF(self);
3310 Py_DECREF(other);
3311 return NULL;
3312 }
3313 PyTuple_SET_ITEM(res, 0, self);
3314 PyTuple_SET_ITEM(res, 1, other);
3315 return res;
3316}
3317
Tim Peters6d6c1a32001-08-02 04:15:00 +00003318static PyObject *
3319wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
3320{
3321 ternaryfunc func = (ternaryfunc)wrapped;
3322 PyObject *other;
3323 PyObject *third = Py_None;
3324
3325 /* Note: This wrapper only works for __pow__() */
3326
3327 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
3328 return NULL;
3329 return (*func)(self, other, third);
3330}
3331
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00003332static PyObject *
3333wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3334{
3335 ternaryfunc func = (ternaryfunc)wrapped;
3336 PyObject *other;
3337 PyObject *third = Py_None;
3338
3339 /* Note: This wrapper only works for __pow__() */
3340
3341 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
3342 return NULL;
3343 return (*func)(other, self, third);
3344}
3345
Tim Peters6d6c1a32001-08-02 04:15:00 +00003346static PyObject *
3347wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
3348{
3349 unaryfunc func = (unaryfunc)wrapped;
3350
3351 if (!PyArg_ParseTuple(args, ""))
3352 return NULL;
3353 return (*func)(self);
3354}
3355
Tim Peters6d6c1a32001-08-02 04:15:00 +00003356static PyObject *
3357wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
3358{
3359 intargfunc func = (intargfunc)wrapped;
3360 int i;
3361
3362 if (!PyArg_ParseTuple(args, "i", &i))
3363 return NULL;
3364 return (*func)(self, i);
3365}
3366
Guido van Rossum5d815f32001-08-17 21:57:47 +00003367static int
3368getindex(PyObject *self, PyObject *arg)
3369{
3370 int i;
3371
3372 i = PyInt_AsLong(arg);
3373 if (i == -1 && PyErr_Occurred())
3374 return -1;
3375 if (i < 0) {
3376 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
3377 if (sq && sq->sq_length) {
3378 int n = (*sq->sq_length)(self);
3379 if (n < 0)
3380 return -1;
3381 i += n;
3382 }
3383 }
3384 return i;
3385}
3386
3387static PyObject *
3388wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
3389{
3390 intargfunc func = (intargfunc)wrapped;
3391 PyObject *arg;
3392 int i;
3393
Guido van Rossumf4593e02001-10-03 12:09:30 +00003394 if (PyTuple_GET_SIZE(args) == 1) {
3395 arg = PyTuple_GET_ITEM(args, 0);
3396 i = getindex(self, arg);
3397 if (i == -1 && PyErr_Occurred())
3398 return NULL;
3399 return (*func)(self, i);
3400 }
3401 PyArg_ParseTuple(args, "O", &arg);
3402 assert(PyErr_Occurred());
3403 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003404}
3405
Tim Peters6d6c1a32001-08-02 04:15:00 +00003406static PyObject *
3407wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
3408{
3409 intintargfunc func = (intintargfunc)wrapped;
3410 int i, j;
3411
3412 if (!PyArg_ParseTuple(args, "ii", &i, &j))
3413 return NULL;
3414 return (*func)(self, i, j);
3415}
3416
Tim Peters6d6c1a32001-08-02 04:15:00 +00003417static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003418wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003419{
3420 intobjargproc func = (intobjargproc)wrapped;
3421 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003422 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003423
Guido van Rossum5d815f32001-08-17 21:57:47 +00003424 if (!PyArg_ParseTuple(args, "OO", &arg, &value))
3425 return NULL;
3426 i = getindex(self, arg);
3427 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00003428 return NULL;
3429 res = (*func)(self, i, value);
3430 if (res == -1 && PyErr_Occurred())
3431 return NULL;
3432 Py_INCREF(Py_None);
3433 return Py_None;
3434}
3435
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003436static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003437wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003438{
3439 intobjargproc func = (intobjargproc)wrapped;
3440 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003441 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003442
Guido van Rossum5d815f32001-08-17 21:57:47 +00003443 if (!PyArg_ParseTuple(args, "O", &arg))
3444 return NULL;
3445 i = getindex(self, arg);
3446 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003447 return NULL;
3448 res = (*func)(self, i, NULL);
3449 if (res == -1 && PyErr_Occurred())
3450 return NULL;
3451 Py_INCREF(Py_None);
3452 return Py_None;
3453}
3454
Tim Peters6d6c1a32001-08-02 04:15:00 +00003455static PyObject *
3456wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
3457{
3458 intintobjargproc func = (intintobjargproc)wrapped;
3459 int i, j, res;
3460 PyObject *value;
3461
3462 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
3463 return NULL;
3464 res = (*func)(self, i, j, value);
3465 if (res == -1 && PyErr_Occurred())
3466 return NULL;
3467 Py_INCREF(Py_None);
3468 return Py_None;
3469}
3470
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003471static PyObject *
3472wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
3473{
3474 intintobjargproc func = (intintobjargproc)wrapped;
3475 int i, j, res;
3476
3477 if (!PyArg_ParseTuple(args, "ii", &i, &j))
3478 return NULL;
3479 res = (*func)(self, i, j, NULL);
3480 if (res == -1 && PyErr_Occurred())
3481 return NULL;
3482 Py_INCREF(Py_None);
3483 return Py_None;
3484}
3485
Tim Peters6d6c1a32001-08-02 04:15:00 +00003486/* XXX objobjproc is a misnomer; should be objargpred */
3487static PyObject *
3488wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
3489{
3490 objobjproc func = (objobjproc)wrapped;
3491 int res;
3492 PyObject *value;
3493
3494 if (!PyArg_ParseTuple(args, "O", &value))
3495 return NULL;
3496 res = (*func)(self, value);
3497 if (res == -1 && PyErr_Occurred())
3498 return NULL;
3499 return PyInt_FromLong((long)res);
3500}
3501
Tim Peters6d6c1a32001-08-02 04:15:00 +00003502static PyObject *
3503wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
3504{
3505 objobjargproc func = (objobjargproc)wrapped;
3506 int res;
3507 PyObject *key, *value;
3508
3509 if (!PyArg_ParseTuple(args, "OO", &key, &value))
3510 return NULL;
3511 res = (*func)(self, key, value);
3512 if (res == -1 && PyErr_Occurred())
3513 return NULL;
3514 Py_INCREF(Py_None);
3515 return Py_None;
3516}
3517
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003518static PyObject *
3519wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
3520{
3521 objobjargproc func = (objobjargproc)wrapped;
3522 int res;
3523 PyObject *key;
3524
3525 if (!PyArg_ParseTuple(args, "O", &key))
3526 return NULL;
3527 res = (*func)(self, key, NULL);
3528 if (res == -1 && PyErr_Occurred())
3529 return NULL;
3530 Py_INCREF(Py_None);
3531 return Py_None;
3532}
3533
Tim Peters6d6c1a32001-08-02 04:15:00 +00003534static PyObject *
3535wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
3536{
3537 cmpfunc func = (cmpfunc)wrapped;
3538 int res;
3539 PyObject *other;
3540
3541 if (!PyArg_ParseTuple(args, "O", &other))
3542 return NULL;
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00003543 if (other->ob_type->tp_compare != func &&
3544 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00003545 PyErr_Format(
3546 PyExc_TypeError,
3547 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
3548 self->ob_type->tp_name,
3549 self->ob_type->tp_name,
3550 other->ob_type->tp_name);
3551 return NULL;
3552 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003553 res = (*func)(self, other);
3554 if (PyErr_Occurred())
3555 return NULL;
3556 return PyInt_FromLong((long)res);
3557}
3558
Tim Peters6d6c1a32001-08-02 04:15:00 +00003559static PyObject *
3560wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
3561{
3562 setattrofunc func = (setattrofunc)wrapped;
3563 int res;
3564 PyObject *name, *value;
3565
3566 if (!PyArg_ParseTuple(args, "OO", &name, &value))
3567 return NULL;
3568 res = (*func)(self, name, value);
3569 if (res < 0)
3570 return NULL;
3571 Py_INCREF(Py_None);
3572 return Py_None;
3573}
3574
3575static PyObject *
3576wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
3577{
3578 setattrofunc func = (setattrofunc)wrapped;
3579 int res;
3580 PyObject *name;
3581
3582 if (!PyArg_ParseTuple(args, "O", &name))
3583 return NULL;
3584 res = (*func)(self, name, NULL);
3585 if (res < 0)
3586 return NULL;
3587 Py_INCREF(Py_None);
3588 return Py_None;
3589}
3590
Tim Peters6d6c1a32001-08-02 04:15:00 +00003591static PyObject *
3592wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
3593{
3594 hashfunc func = (hashfunc)wrapped;
3595 long res;
3596
3597 if (!PyArg_ParseTuple(args, ""))
3598 return NULL;
3599 res = (*func)(self);
3600 if (res == -1 && PyErr_Occurred())
3601 return NULL;
3602 return PyInt_FromLong(res);
3603}
3604
Tim Peters6d6c1a32001-08-02 04:15:00 +00003605static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00003606wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003607{
3608 ternaryfunc func = (ternaryfunc)wrapped;
3609
Guido van Rossumc8e56452001-10-22 00:43:43 +00003610 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003611}
3612
Tim Peters6d6c1a32001-08-02 04:15:00 +00003613static PyObject *
3614wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
3615{
3616 richcmpfunc func = (richcmpfunc)wrapped;
3617 PyObject *other;
3618
3619 if (!PyArg_ParseTuple(args, "O", &other))
3620 return NULL;
3621 return (*func)(self, other, op);
3622}
3623
3624#undef RICHCMP_WRAPPER
3625#define RICHCMP_WRAPPER(NAME, OP) \
3626static PyObject * \
3627richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
3628{ \
3629 return wrap_richcmpfunc(self, args, wrapped, OP); \
3630}
3631
Jack Jansen8e938b42001-08-08 15:29:49 +00003632RICHCMP_WRAPPER(lt, Py_LT)
3633RICHCMP_WRAPPER(le, Py_LE)
3634RICHCMP_WRAPPER(eq, Py_EQ)
3635RICHCMP_WRAPPER(ne, Py_NE)
3636RICHCMP_WRAPPER(gt, Py_GT)
3637RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003638
Tim Peters6d6c1a32001-08-02 04:15:00 +00003639static PyObject *
3640wrap_next(PyObject *self, PyObject *args, void *wrapped)
3641{
3642 unaryfunc func = (unaryfunc)wrapped;
3643 PyObject *res;
3644
3645 if (!PyArg_ParseTuple(args, ""))
3646 return NULL;
3647 res = (*func)(self);
3648 if (res == NULL && !PyErr_Occurred())
3649 PyErr_SetNone(PyExc_StopIteration);
3650 return res;
3651}
3652
Tim Peters6d6c1a32001-08-02 04:15:00 +00003653static PyObject *
3654wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
3655{
3656 descrgetfunc func = (descrgetfunc)wrapped;
3657 PyObject *obj;
3658 PyObject *type = NULL;
3659
3660 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
3661 return NULL;
Guido van Rossum82ed25c2003-02-11 16:25:43 +00003662 if (obj == Py_None)
3663 obj = NULL;
3664 if (type == Py_None)
3665 type = NULL;
3666 if (type == NULL &&obj == NULL) {
3667 PyErr_SetString(PyExc_TypeError,
3668 "__get__(None, None) is invalid");
3669 return NULL;
3670 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003671 return (*func)(self, obj, type);
3672}
3673
Tim Peters6d6c1a32001-08-02 04:15:00 +00003674static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003675wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003676{
3677 descrsetfunc func = (descrsetfunc)wrapped;
3678 PyObject *obj, *value;
3679 int ret;
3680
3681 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
3682 return NULL;
3683 ret = (*func)(self, obj, value);
3684 if (ret < 0)
3685 return NULL;
3686 Py_INCREF(Py_None);
3687 return Py_None;
3688}
Guido van Rossum22b13872002-08-06 21:41:44 +00003689
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00003690static PyObject *
3691wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
3692{
3693 descrsetfunc func = (descrsetfunc)wrapped;
3694 PyObject *obj;
3695 int ret;
3696
3697 if (!PyArg_ParseTuple(args, "O", &obj))
3698 return NULL;
3699 ret = (*func)(self, obj, NULL);
3700 if (ret < 0)
3701 return NULL;
3702 Py_INCREF(Py_None);
3703 return Py_None;
3704}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003705
Tim Peters6d6c1a32001-08-02 04:15:00 +00003706static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00003707wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003708{
3709 initproc func = (initproc)wrapped;
3710
Guido van Rossumc8e56452001-10-22 00:43:43 +00003711 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003712 return NULL;
3713 Py_INCREF(Py_None);
3714 return Py_None;
3715}
3716
Tim Peters6d6c1a32001-08-02 04:15:00 +00003717static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003718tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003719{
Barry Warsaw60f01882001-08-22 19:24:42 +00003720 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003721 PyObject *arg0, *res;
3722
3723 if (self == NULL || !PyType_Check(self))
3724 Py_FatalError("__new__() called with non-type 'self'");
3725 type = (PyTypeObject *)self;
3726 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003727 PyErr_Format(PyExc_TypeError,
3728 "%s.__new__(): not enough arguments",
3729 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003730 return NULL;
3731 }
3732 arg0 = PyTuple_GET_ITEM(args, 0);
3733 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003734 PyErr_Format(PyExc_TypeError,
3735 "%s.__new__(X): X is not a type object (%s)",
3736 type->tp_name,
3737 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003738 return NULL;
3739 }
3740 subtype = (PyTypeObject *)arg0;
3741 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003742 PyErr_Format(PyExc_TypeError,
3743 "%s.__new__(%s): %s is not a subtype of %s",
3744 type->tp_name,
3745 subtype->tp_name,
3746 subtype->tp_name,
3747 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003748 return NULL;
3749 }
Barry Warsaw60f01882001-08-22 19:24:42 +00003750
3751 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00003752 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00003753 most derived base that's not a heap type is this type. */
3754 staticbase = subtype;
3755 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
3756 staticbase = staticbase->tp_base;
Guido van Rossuma8c60f42001-09-14 19:43:36 +00003757 if (staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003758 PyErr_Format(PyExc_TypeError,
3759 "%s.__new__(%s) is not safe, use %s.__new__()",
3760 type->tp_name,
3761 subtype->tp_name,
3762 staticbase == NULL ? "?" : staticbase->tp_name);
3763 return NULL;
3764 }
3765
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003766 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
3767 if (args == NULL)
3768 return NULL;
3769 res = type->tp_new(subtype, args, kwds);
3770 Py_DECREF(args);
3771 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003772}
3773
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003774static struct PyMethodDef tp_new_methoddef[] = {
3775 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00003776 PyDoc_STR("T.__new__(S, ...) -> "
3777 "a new object with type S, a subtype of T")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00003778 {0}
3779};
3780
3781static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003782add_tp_new_wrapper(PyTypeObject *type)
3783{
Guido van Rossumf040ede2001-08-07 16:40:56 +00003784 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003785
Guido van Rossum687ae002001-10-15 22:03:32 +00003786 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00003787 return 0;
3788 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003789 if (func == NULL)
3790 return -1;
Guido van Rossum687ae002001-10-15 22:03:32 +00003791 return PyDict_SetItemString(type->tp_dict, "__new__", func);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003792}
3793
Guido van Rossumf040ede2001-08-07 16:40:56 +00003794/* Slot wrappers that call the corresponding __foo__ slot. See comments
3795 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003796
Guido van Rossumdc91b992001-08-08 22:26:22 +00003797#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003798static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003799FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003800{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00003801 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003802 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003803}
3804
Guido van Rossumdc91b992001-08-08 22:26:22 +00003805#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003806static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003807FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003808{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003809 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003810 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003811}
3812
Guido van Rossumcd118802003-01-06 22:57:47 +00003813/* Boolean helper for SLOT1BINFULL().
3814 right.__class__ is a nontrivial subclass of left.__class__. */
3815static int
3816method_is_overloaded(PyObject *left, PyObject *right, char *name)
3817{
3818 PyObject *a, *b;
3819 int ok;
3820
3821 b = PyObject_GetAttrString((PyObject *)(right->ob_type), name);
3822 if (b == NULL) {
3823 PyErr_Clear();
3824 /* If right doesn't have it, it's not overloaded */
3825 return 0;
3826 }
3827
3828 a = PyObject_GetAttrString((PyObject *)(left->ob_type), name);
3829 if (a == NULL) {
3830 PyErr_Clear();
3831 Py_DECREF(b);
3832 /* If right has it but left doesn't, it's overloaded */
3833 return 1;
3834 }
3835
3836 ok = PyObject_RichCompareBool(a, b, Py_NE);
3837 Py_DECREF(a);
3838 Py_DECREF(b);
3839 if (ok < 0) {
3840 PyErr_Clear();
3841 return 0;
3842 }
3843
3844 return ok;
3845}
3846
Guido van Rossumdc91b992001-08-08 22:26:22 +00003847
3848#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003849static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003850FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003851{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003852 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00003853 int do_other = self->ob_type != other->ob_type && \
3854 other->ob_type->tp_as_number != NULL && \
3855 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003856 if (self->ob_type->tp_as_number != NULL && \
3857 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
3858 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00003859 if (do_other && \
Guido van Rossumcd118802003-01-06 22:57:47 +00003860 PyType_IsSubtype(other->ob_type, self->ob_type) && \
3861 method_is_overloaded(self, other, ROPSTR)) { \
Guido van Rossum55f20992001-10-01 17:18:22 +00003862 r = call_maybe( \
3863 other, ROPSTR, &rcache_str, "(O)", self); \
3864 if (r != Py_NotImplemented) \
3865 return r; \
3866 Py_DECREF(r); \
3867 do_other = 0; \
3868 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00003869 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00003870 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003871 if (r != Py_NotImplemented || \
3872 other->ob_type == self->ob_type) \
3873 return r; \
3874 Py_DECREF(r); \
3875 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00003876 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00003877 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00003878 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003879 } \
3880 Py_INCREF(Py_NotImplemented); \
3881 return Py_NotImplemented; \
3882}
3883
3884#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
3885 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
3886
3887#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
3888static PyObject * \
3889FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
3890{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003891 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003892 return call_method(self, OPSTR, &cache_str, \
3893 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003894}
3895
3896static int
3897slot_sq_length(PyObject *self)
3898{
Guido van Rossum2730b132001-08-28 18:22:14 +00003899 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00003900 PyObject *res = call_method(self, "__len__", &len_str, "()");
Guido van Rossum26111622001-10-01 16:42:49 +00003901 int len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003902
3903 if (res == NULL)
3904 return -1;
Guido van Rossum26111622001-10-01 16:42:49 +00003905 len = (int)PyInt_AsLong(res);
3906 Py_DECREF(res);
Jeremy Hylton73a088e2002-07-25 16:43:29 +00003907 if (len == -1 && PyErr_Occurred())
3908 return -1;
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00003909 if (len < 0) {
Guido van Rossum22b13872002-08-06 21:41:44 +00003910 PyErr_SetString(PyExc_ValueError,
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00003911 "__len__() should return >= 0");
3912 return -1;
3913 }
Guido van Rossum26111622001-10-01 16:42:49 +00003914 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003915}
3916
Guido van Rossumdc91b992001-08-08 22:26:22 +00003917SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
3918SLOT1(slot_sq_repeat, "__mul__", int, "i")
Guido van Rossumf4593e02001-10-03 12:09:30 +00003919
3920/* Super-optimized version of slot_sq_item.
3921 Other slots could do the same... */
3922static PyObject *
3923slot_sq_item(PyObject *self, int i)
3924{
3925 static PyObject *getitem_str;
3926 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
3927 descrgetfunc f;
3928
3929 if (getitem_str == NULL) {
3930 getitem_str = PyString_InternFromString("__getitem__");
3931 if (getitem_str == NULL)
3932 return NULL;
3933 }
3934 func = _PyType_Lookup(self->ob_type, getitem_str);
3935 if (func != NULL) {
Guido van Rossumf4593e02001-10-03 12:09:30 +00003936 if ((f = func->ob_type->tp_descr_get) == NULL)
3937 Py_INCREF(func);
Neal Norwitz673cd822002-10-18 16:33:13 +00003938 else {
Guido van Rossumf4593e02001-10-03 12:09:30 +00003939 func = f(func, self, (PyObject *)(self->ob_type));
Neal Norwitz673cd822002-10-18 16:33:13 +00003940 if (func == NULL) {
3941 return NULL;
3942 }
3943 }
Guido van Rossumf4593e02001-10-03 12:09:30 +00003944 ival = PyInt_FromLong(i);
3945 if (ival != NULL) {
3946 args = PyTuple_New(1);
3947 if (args != NULL) {
3948 PyTuple_SET_ITEM(args, 0, ival);
3949 retval = PyObject_Call(func, args, NULL);
3950 Py_XDECREF(args);
3951 Py_XDECREF(func);
3952 return retval;
3953 }
3954 }
3955 }
3956 else {
3957 PyErr_SetObject(PyExc_AttributeError, getitem_str);
3958 }
3959 Py_XDECREF(args);
3960 Py_XDECREF(ival);
3961 Py_XDECREF(func);
3962 return NULL;
3963}
3964
Guido van Rossumdc91b992001-08-08 22:26:22 +00003965SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003966
3967static int
3968slot_sq_ass_item(PyObject *self, int index, PyObject *value)
3969{
3970 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003971 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003972
3973 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003974 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003975 "(i)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003976 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003977 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003978 "(iO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003979 if (res == NULL)
3980 return -1;
3981 Py_DECREF(res);
3982 return 0;
3983}
3984
3985static int
3986slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
3987{
3988 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003989 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003990
3991 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003992 res = call_method(self, "__delslice__", &delslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003993 "(ii)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003994 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003995 res = call_method(self, "__setslice__", &setslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003996 "(iiO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003997 if (res == NULL)
3998 return -1;
3999 Py_DECREF(res);
4000 return 0;
4001}
4002
4003static int
4004slot_sq_contains(PyObject *self, PyObject *value)
4005{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004006 PyObject *func, *res, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00004007 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004008
Guido van Rossum55f20992001-10-01 17:18:22 +00004009 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004010
4011 if (func != NULL) {
4012 args = Py_BuildValue("(O)", value);
4013 if (args == NULL)
4014 res = NULL;
4015 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004016 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004017 Py_DECREF(args);
4018 }
4019 Py_DECREF(func);
4020 if (res == NULL)
4021 return -1;
4022 return PyObject_IsTrue(res);
4023 }
Guido van Rossum55f20992001-10-01 17:18:22 +00004024 else if (PyErr_Occurred())
4025 return -1;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004026 else {
Tim Peters16a77ad2001-09-08 04:00:12 +00004027 return _PySequence_IterSearch(self, value,
4028 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004029 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004030}
4031
Guido van Rossumdc91b992001-08-08 22:26:22 +00004032SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
4033SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004034
4035#define slot_mp_length slot_sq_length
4036
Guido van Rossumdc91b992001-08-08 22:26:22 +00004037SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004038
4039static int
4040slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
4041{
4042 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004043 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004044
4045 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004046 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004047 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004048 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004049 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004050 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004051 if (res == NULL)
4052 return -1;
4053 Py_DECREF(res);
4054 return 0;
4055}
4056
Guido van Rossumdc91b992001-08-08 22:26:22 +00004057SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
4058SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
4059SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
4060SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
4061SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
4062SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
4063
Jeremy Hylton938ace62002-07-17 16:30:39 +00004064static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00004065
4066SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
4067 nb_power, "__pow__", "__rpow__")
4068
4069static PyObject *
4070slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
4071{
Guido van Rossum2730b132001-08-28 18:22:14 +00004072 static PyObject *pow_str;
4073
Guido van Rossumdc91b992001-08-08 22:26:22 +00004074 if (modulus == Py_None)
4075 return slot_nb_power_binary(self, other);
Guido van Rossum23094982002-06-10 14:30:43 +00004076 /* Three-arg power doesn't use __rpow__. But ternary_op
4077 can call this when the second argument's type uses
4078 slot_nb_power, so check before calling self.__pow__. */
4079 if (self->ob_type->tp_as_number != NULL &&
4080 self->ob_type->tp_as_number->nb_power == slot_nb_power) {
4081 return call_method(self, "__pow__", &pow_str,
4082 "(OO)", other, modulus);
4083 }
4084 Py_INCREF(Py_NotImplemented);
4085 return Py_NotImplemented;
Guido van Rossumdc91b992001-08-08 22:26:22 +00004086}
4087
4088SLOT0(slot_nb_negative, "__neg__")
4089SLOT0(slot_nb_positive, "__pos__")
4090SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004091
4092static int
4093slot_nb_nonzero(PyObject *self)
4094{
Tim Petersea7f75d2002-12-07 21:39:16 +00004095 PyObject *func, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00004096 static PyObject *nonzero_str, *len_str;
Tim Petersea7f75d2002-12-07 21:39:16 +00004097 int result = -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004098
Guido van Rossum55f20992001-10-01 17:18:22 +00004099 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004100 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00004101 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00004102 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00004103 func = lookup_maybe(self, "__len__", &len_str);
Tim Petersea7f75d2002-12-07 21:39:16 +00004104 if (func == NULL)
4105 return PyErr_Occurred() ? -1 : 1;
4106 }
4107 args = PyTuple_New(0);
4108 if (args != NULL) {
4109 PyObject *temp = PyObject_Call(func, args, NULL);
4110 Py_DECREF(args);
4111 if (temp != NULL) {
4112 result = PyObject_IsTrue(temp);
4113 Py_DECREF(temp);
Guido van Rossum55f20992001-10-01 17:18:22 +00004114 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004115 }
Guido van Rossum55f20992001-10-01 17:18:22 +00004116 Py_DECREF(func);
Tim Petersea7f75d2002-12-07 21:39:16 +00004117 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004118}
4119
Guido van Rossumdc91b992001-08-08 22:26:22 +00004120SLOT0(slot_nb_invert, "__invert__")
4121SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
4122SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
4123SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
4124SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
4125SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004126
4127static int
4128slot_nb_coerce(PyObject **a, PyObject **b)
4129{
4130 static PyObject *coerce_str;
4131 PyObject *self = *a, *other = *b;
4132
4133 if (self->ob_type->tp_as_number != NULL &&
4134 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
4135 PyObject *r;
4136 r = call_maybe(
4137 self, "__coerce__", &coerce_str, "(O)", other);
4138 if (r == NULL)
4139 return -1;
4140 if (r == Py_NotImplemented) {
4141 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004142 }
Guido van Rossum55f20992001-10-01 17:18:22 +00004143 else {
4144 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
4145 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004146 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00004147 Py_DECREF(r);
4148 return -1;
4149 }
4150 *a = PyTuple_GET_ITEM(r, 0);
4151 Py_INCREF(*a);
4152 *b = PyTuple_GET_ITEM(r, 1);
4153 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004154 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00004155 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004156 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004157 }
4158 if (other->ob_type->tp_as_number != NULL &&
4159 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
4160 PyObject *r;
4161 r = call_maybe(
4162 other, "__coerce__", &coerce_str, "(O)", self);
4163 if (r == NULL)
4164 return -1;
4165 if (r == Py_NotImplemented) {
4166 Py_DECREF(r);
4167 return 1;
4168 }
4169 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
4170 PyErr_SetString(PyExc_TypeError,
4171 "__coerce__ didn't return a 2-tuple");
4172 Py_DECREF(r);
4173 return -1;
4174 }
4175 *a = PyTuple_GET_ITEM(r, 1);
4176 Py_INCREF(*a);
4177 *b = PyTuple_GET_ITEM(r, 0);
4178 Py_INCREF(*b);
4179 Py_DECREF(r);
4180 return 0;
4181 }
4182 return 1;
4183}
4184
Guido van Rossumdc91b992001-08-08 22:26:22 +00004185SLOT0(slot_nb_int, "__int__")
4186SLOT0(slot_nb_long, "__long__")
4187SLOT0(slot_nb_float, "__float__")
4188SLOT0(slot_nb_oct, "__oct__")
4189SLOT0(slot_nb_hex, "__hex__")
4190SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
4191SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
4192SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
4193SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
4194SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Guido van Rossum6e5680f2002-10-15 01:01:53 +00004195SLOT1(slot_nb_inplace_power, "__ipow__", PyObject *, "O")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004196SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
4197SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
4198SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
4199SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
4200SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
4201SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
4202 "__floordiv__", "__rfloordiv__")
4203SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
4204SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
4205SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004206
4207static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00004208half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004209{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004210 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004211 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004212 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004213
Guido van Rossum60718732001-08-28 17:47:51 +00004214 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004215 if (func == NULL) {
4216 PyErr_Clear();
4217 }
4218 else {
4219 args = Py_BuildValue("(O)", other);
4220 if (args == NULL)
4221 res = NULL;
4222 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004223 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004224 Py_DECREF(args);
4225 }
Raymond Hettingerab5dae32002-06-24 13:08:16 +00004226 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004227 if (res != Py_NotImplemented) {
4228 if (res == NULL)
4229 return -2;
4230 c = PyInt_AsLong(res);
4231 Py_DECREF(res);
4232 if (c == -1 && PyErr_Occurred())
4233 return -2;
4234 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
4235 }
4236 Py_DECREF(res);
4237 }
4238 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004239}
4240
Guido van Rossumab3b0342001-09-18 20:38:53 +00004241/* This slot is published for the benefit of try_3way_compare in object.c */
4242int
4243_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00004244{
4245 int c;
4246
Guido van Rossumab3b0342001-09-18 20:38:53 +00004247 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004248 c = half_compare(self, other);
4249 if (c <= 1)
4250 return c;
4251 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00004252 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004253 c = half_compare(other, self);
4254 if (c < -1)
4255 return -2;
4256 if (c <= 1)
4257 return -c;
4258 }
4259 return (void *)self < (void *)other ? -1 :
4260 (void *)self > (void *)other ? 1 : 0;
4261}
4262
4263static PyObject *
4264slot_tp_repr(PyObject *self)
4265{
4266 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004267 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004268
Guido van Rossum60718732001-08-28 17:47:51 +00004269 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004270 if (func != NULL) {
4271 res = PyEval_CallObject(func, NULL);
4272 Py_DECREF(func);
4273 return res;
4274 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00004275 PyErr_Clear();
4276 return PyString_FromFormat("<%s object at %p>",
4277 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004278}
4279
4280static PyObject *
4281slot_tp_str(PyObject *self)
4282{
4283 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004284 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004285
Guido van Rossum60718732001-08-28 17:47:51 +00004286 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004287 if (func != NULL) {
4288 res = PyEval_CallObject(func, NULL);
4289 Py_DECREF(func);
4290 return res;
4291 }
4292 else {
4293 PyErr_Clear();
4294 return slot_tp_repr(self);
4295 }
4296}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004297
4298static long
4299slot_tp_hash(PyObject *self)
4300{
Tim Peters61ce0a92002-12-06 23:38:02 +00004301 PyObject *func;
Guido van Rossum60718732001-08-28 17:47:51 +00004302 static PyObject *hash_str, *eq_str, *cmp_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004303 long h;
4304
Guido van Rossum60718732001-08-28 17:47:51 +00004305 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004306
4307 if (func != NULL) {
Tim Peters61ce0a92002-12-06 23:38:02 +00004308 PyObject *res = PyEval_CallObject(func, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004309 Py_DECREF(func);
4310 if (res == NULL)
4311 return -1;
4312 h = PyInt_AsLong(res);
Tim Peters61ce0a92002-12-06 23:38:02 +00004313 Py_DECREF(res);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004314 }
4315 else {
4316 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004317 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004318 if (func == NULL) {
4319 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004320 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004321 }
4322 if (func != NULL) {
4323 Py_DECREF(func);
4324 PyErr_SetString(PyExc_TypeError, "unhashable type");
4325 return -1;
4326 }
4327 PyErr_Clear();
4328 h = _Py_HashPointer((void *)self);
4329 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004330 if (h == -1 && !PyErr_Occurred())
4331 h = -2;
4332 return h;
4333}
4334
4335static PyObject *
4336slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
4337{
Guido van Rossum60718732001-08-28 17:47:51 +00004338 static PyObject *call_str;
4339 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004340 PyObject *res;
4341
4342 if (meth == NULL)
4343 return NULL;
4344 res = PyObject_Call(meth, args, kwds);
4345 Py_DECREF(meth);
4346 return res;
4347}
4348
Guido van Rossum14a6f832001-10-17 13:59:09 +00004349/* There are two slot dispatch functions for tp_getattro.
4350
4351 - slot_tp_getattro() is used when __getattribute__ is overridden
4352 but no __getattr__ hook is present;
4353
4354 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
4355
Guido van Rossumc334df52002-04-04 23:44:47 +00004356 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
4357 detects the absence of __getattr__ and then installs the simpler slot if
4358 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00004359
Tim Peters6d6c1a32001-08-02 04:15:00 +00004360static PyObject *
4361slot_tp_getattro(PyObject *self, PyObject *name)
4362{
Guido van Rossum14a6f832001-10-17 13:59:09 +00004363 static PyObject *getattribute_str = NULL;
4364 return call_method(self, "__getattribute__", &getattribute_str,
4365 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004366}
4367
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004368static PyObject *
4369slot_tp_getattr_hook(PyObject *self, PyObject *name)
4370{
4371 PyTypeObject *tp = self->ob_type;
4372 PyObject *getattr, *getattribute, *res;
4373 static PyObject *getattribute_str = NULL;
4374 static PyObject *getattr_str = NULL;
4375
4376 if (getattr_str == NULL) {
4377 getattr_str = PyString_InternFromString("__getattr__");
4378 if (getattr_str == NULL)
4379 return NULL;
4380 }
4381 if (getattribute_str == NULL) {
4382 getattribute_str =
4383 PyString_InternFromString("__getattribute__");
4384 if (getattribute_str == NULL)
4385 return NULL;
4386 }
4387 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004388 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004389 /* No __getattr__ hook: use a simpler dispatcher */
4390 tp->tp_getattro = slot_tp_getattro;
4391 return slot_tp_getattro(self, name);
4392 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004393 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004394 if (getattribute == NULL ||
4395 (getattribute->ob_type == &PyWrapperDescr_Type &&
4396 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
4397 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004398 res = PyObject_GenericGetAttr(self, name);
4399 else
4400 res = PyObject_CallFunction(getattribute, "OO", self, name);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004401 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004402 PyErr_Clear();
4403 res = PyObject_CallFunction(getattr, "OO", self, name);
4404 }
4405 return res;
4406}
4407
Tim Peters6d6c1a32001-08-02 04:15:00 +00004408static int
4409slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
4410{
4411 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004412 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004413
4414 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004415 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004416 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004417 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004418 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004419 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004420 if (res == NULL)
4421 return -1;
4422 Py_DECREF(res);
4423 return 0;
4424}
4425
4426/* Map rich comparison operators to their __xx__ namesakes */
4427static char *name_op[] = {
4428 "__lt__",
4429 "__le__",
4430 "__eq__",
4431 "__ne__",
4432 "__gt__",
4433 "__ge__",
4434};
4435
4436static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00004437half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004438{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004439 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004440 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00004441
Guido van Rossum60718732001-08-28 17:47:51 +00004442 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004443 if (func == NULL) {
4444 PyErr_Clear();
4445 Py_INCREF(Py_NotImplemented);
4446 return Py_NotImplemented;
4447 }
4448 args = Py_BuildValue("(O)", other);
4449 if (args == NULL)
4450 res = NULL;
4451 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004452 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004453 Py_DECREF(args);
4454 }
4455 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004456 return res;
4457}
4458
Guido van Rossumb8f63662001-08-15 23:57:02 +00004459/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
4460static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
4461
4462static PyObject *
4463slot_tp_richcompare(PyObject *self, PyObject *other, int op)
4464{
4465 PyObject *res;
4466
4467 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
4468 res = half_richcompare(self, other, op);
4469 if (res != Py_NotImplemented)
4470 return res;
4471 Py_DECREF(res);
4472 }
4473 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
4474 res = half_richcompare(other, self, swapped_op[op]);
4475 if (res != Py_NotImplemented) {
4476 return res;
4477 }
4478 Py_DECREF(res);
4479 }
4480 Py_INCREF(Py_NotImplemented);
4481 return Py_NotImplemented;
4482}
4483
4484static PyObject *
4485slot_tp_iter(PyObject *self)
4486{
4487 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004488 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004489
Guido van Rossum60718732001-08-28 17:47:51 +00004490 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004491 if (func != NULL) {
Guido van Rossum84b2bed2002-08-16 17:01:09 +00004492 PyObject *args;
4493 args = res = PyTuple_New(0);
4494 if (args != NULL) {
4495 res = PyObject_Call(func, args, NULL);
4496 Py_DECREF(args);
4497 }
4498 Py_DECREF(func);
4499 return res;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004500 }
4501 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004502 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004503 if (func == NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00004504 PyErr_SetString(PyExc_TypeError,
4505 "iteration over non-sequence");
Guido van Rossumb8f63662001-08-15 23:57:02 +00004506 return NULL;
4507 }
4508 Py_DECREF(func);
4509 return PySeqIter_New(self);
4510}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004511
4512static PyObject *
4513slot_tp_iternext(PyObject *self)
4514{
Guido van Rossum2730b132001-08-28 18:22:14 +00004515 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00004516 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004517}
4518
Guido van Rossum1a493502001-08-17 16:47:50 +00004519static PyObject *
4520slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4521{
4522 PyTypeObject *tp = self->ob_type;
4523 PyObject *get;
4524 static PyObject *get_str = NULL;
4525
4526 if (get_str == NULL) {
4527 get_str = PyString_InternFromString("__get__");
4528 if (get_str == NULL)
4529 return NULL;
4530 }
4531 get = _PyType_Lookup(tp, get_str);
4532 if (get == NULL) {
4533 /* Avoid further slowdowns */
4534 if (tp->tp_descr_get == slot_tp_descr_get)
4535 tp->tp_descr_get = NULL;
4536 Py_INCREF(self);
4537 return self;
4538 }
Guido van Rossum2c252392001-08-24 10:13:31 +00004539 if (obj == NULL)
4540 obj = Py_None;
4541 if (type == NULL)
4542 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00004543 return PyObject_CallFunction(get, "OOO", self, obj, type);
4544}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004545
4546static int
4547slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
4548{
Guido van Rossum2c252392001-08-24 10:13:31 +00004549 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004550 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00004551
4552 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00004553 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004554 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00004555 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004556 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004557 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004558 if (res == NULL)
4559 return -1;
4560 Py_DECREF(res);
4561 return 0;
4562}
4563
4564static int
4565slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
4566{
Guido van Rossum60718732001-08-28 17:47:51 +00004567 static PyObject *init_str;
4568 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004569 PyObject *res;
4570
4571 if (meth == NULL)
4572 return -1;
4573 res = PyObject_Call(meth, args, kwds);
4574 Py_DECREF(meth);
4575 if (res == NULL)
4576 return -1;
4577 Py_DECREF(res);
4578 return 0;
4579}
4580
4581static PyObject *
4582slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4583{
Guido van Rossum7bed2132002-08-08 21:57:53 +00004584 static PyObject *new_str;
4585 PyObject *func;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004586 PyObject *newargs, *x;
4587 int i, n;
4588
Guido van Rossum7bed2132002-08-08 21:57:53 +00004589 if (new_str == NULL) {
4590 new_str = PyString_InternFromString("__new__");
4591 if (new_str == NULL)
4592 return NULL;
4593 }
4594 func = PyObject_GetAttr((PyObject *)type, new_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004595 if (func == NULL)
4596 return NULL;
4597 assert(PyTuple_Check(args));
4598 n = PyTuple_GET_SIZE(args);
4599 newargs = PyTuple_New(n+1);
4600 if (newargs == NULL)
4601 return NULL;
4602 Py_INCREF(type);
4603 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
4604 for (i = 0; i < n; i++) {
4605 x = PyTuple_GET_ITEM(args, i);
4606 Py_INCREF(x);
4607 PyTuple_SET_ITEM(newargs, i+1, x);
4608 }
4609 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00004610 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004611 Py_DECREF(func);
4612 return x;
4613}
4614
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004615static void
4616slot_tp_del(PyObject *self)
4617{
4618 static PyObject *del_str = NULL;
4619 PyObject *del, *res;
4620 PyObject *error_type, *error_value, *error_traceback;
4621
4622 /* Temporarily resurrect the object. */
4623 assert(self->ob_refcnt == 0);
4624 self->ob_refcnt = 1;
4625
4626 /* Save the current exception, if any. */
4627 PyErr_Fetch(&error_type, &error_value, &error_traceback);
4628
4629 /* Execute __del__ method, if any. */
4630 del = lookup_maybe(self, "__del__", &del_str);
4631 if (del != NULL) {
4632 res = PyEval_CallObject(del, NULL);
4633 if (res == NULL)
4634 PyErr_WriteUnraisable(del);
4635 else
4636 Py_DECREF(res);
4637 Py_DECREF(del);
4638 }
4639
4640 /* Restore the saved exception. */
4641 PyErr_Restore(error_type, error_value, error_traceback);
4642
4643 /* Undo the temporary resurrection; can't use DECREF here, it would
4644 * cause a recursive call.
4645 */
4646 assert(self->ob_refcnt > 0);
4647 if (--self->ob_refcnt == 0)
4648 return; /* this is the normal path out */
4649
4650 /* __del__ resurrected it! Make it look like the original Py_DECREF
4651 * never happened.
4652 */
4653 {
4654 int refcnt = self->ob_refcnt;
4655 _Py_NewReference(self);
4656 self->ob_refcnt = refcnt;
4657 }
4658 assert(!PyType_IS_GC(self->ob_type) ||
4659 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
4660 /* If Py_REF_DEBUG, the original decref dropped _Py_RefTotal, but
4661 * _Py_NewReference bumped it again, so that's a wash.
4662 * If Py_TRACE_REFS, _Py_NewReference re-added self to the object
4663 * chain, so no more to do there either.
4664 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
4665 * _Py_NewReference bumped tp_allocs: both of those need to be
4666 * undone.
4667 */
4668#ifdef COUNT_ALLOCS
4669 --self->ob_type->tp_frees;
4670 --self->ob_type->tp_allocs;
4671#endif
4672}
4673
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004674
4675/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
Guido van Rossume5c691a2003-03-07 15:13:17 +00004676 functions. The offsets here are relative to the 'PyHeapTypeObject'
4677 structure, which incorporates the additional structures used for numbers,
4678 sequences and mappings.
4679 Note that multiple names may map to the same slot (e.g. __eq__,
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004680 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00004681 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
4682 terminated with an all-zero entry. (This table is further initialized and
4683 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004684
Guido van Rossum6d204072001-10-21 00:44:31 +00004685typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004686
4687#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00004688#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004689#undef ETSLOT
4690#undef SQSLOT
4691#undef MPSLOT
4692#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00004693#undef UNSLOT
4694#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004695#undef BINSLOT
4696#undef RBINSLOT
4697
Guido van Rossum6d204072001-10-21 00:44:31 +00004698#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004699 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
4700 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00004701#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
4702 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004703 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00004704#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Guido van Rossume5c691a2003-03-07 15:13:17 +00004705 {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004706 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00004707#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4708 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
4709#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4710 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
4711#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4712 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
4713#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4714 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
4715 "x." NAME "() <==> " DOC)
4716#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4717 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
4718 "x." NAME "(y) <==> x" DOC "y")
4719#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
4720 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
4721 "x." NAME "(y) <==> x" DOC "y")
4722#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
4723 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
4724 "x." NAME "(y) <==> y" DOC "x")
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004725
4726static slotdef slotdefs[] = {
Guido van Rossum6d204072001-10-21 00:44:31 +00004727 SQSLOT("__len__", sq_length, slot_sq_length, wrap_inquiry,
4728 "x.__len__() <==> len(x)"),
4729 SQSLOT("__add__", sq_concat, slot_sq_concat, wrap_binaryfunc,
4730 "x.__add__(y) <==> x+y"),
4731 SQSLOT("__mul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
4732 "x.__mul__(n) <==> x*n"),
4733 SQSLOT("__rmul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
4734 "x.__rmul__(n) <==> n*x"),
4735 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
4736 "x.__getitem__(y) <==> x[y]"),
4737 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_intintargfunc,
4738 "x.__getslice__(i, j) <==> x[i:j]"),
4739 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
4740 "x.__setitem__(i, y) <==> x[i]=y"),
4741 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
4742 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004743 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Guido van Rossum6d204072001-10-21 00:44:31 +00004744 wrap_intintobjargproc,
4745 "x.__setslice__(i, j, y) <==> x[i:j]=y"),
4746 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
4747 "x.__delslice__(i, j) <==> del x[i:j]"),
4748 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
4749 "x.__contains__(y) <==> y in x"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004750 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat,
Guido van Rossum6d204072001-10-21 00:44:31 +00004751 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004752 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat,
Guido van Rossum6d204072001-10-21 00:44:31 +00004753 wrap_intargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004754
Guido van Rossum6d204072001-10-21 00:44:31 +00004755 MPSLOT("__len__", mp_length, slot_mp_length, wrap_inquiry,
4756 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00004757 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004758 wrap_binaryfunc,
4759 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004760 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004761 wrap_objobjargproc,
4762 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004763 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004764 wrap_delitem,
4765 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004766
Guido van Rossum6d204072001-10-21 00:44:31 +00004767 BINSLOT("__add__", nb_add, slot_nb_add,
4768 "+"),
4769 RBINSLOT("__radd__", nb_add, slot_nb_add,
4770 "+"),
4771 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
4772 "-"),
4773 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
4774 "-"),
4775 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
4776 "*"),
4777 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
4778 "*"),
4779 BINSLOT("__div__", nb_divide, slot_nb_divide,
4780 "/"),
4781 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
4782 "/"),
4783 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
4784 "%"),
4785 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
4786 "%"),
4787 BINSLOT("__divmod__", nb_divmod, slot_nb_divmod,
4788 "divmod(x, y)"),
4789 RBINSLOT("__rdivmod__", nb_divmod, slot_nb_divmod,
4790 "divmod(y, x)"),
4791 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
4792 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
4793 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
4794 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
4795 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
4796 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
4797 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
4798 "abs(x)"),
Guido van Rossumdfce3bf2002-03-10 14:11:16 +00004799 UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquiry,
Guido van Rossum6d204072001-10-21 00:44:31 +00004800 "x != 0"),
4801 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
4802 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
4803 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
4804 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
4805 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
4806 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
4807 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
4808 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
4809 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
4810 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
4811 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
4812 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
4813 "x.__coerce__(y) <==> coerce(x, y)"),
4814 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
4815 "int(x)"),
4816 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
4817 "long(x)"),
4818 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
4819 "float(x)"),
4820 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
4821 "oct(x)"),
4822 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
4823 "hex(x)"),
4824 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
4825 wrap_binaryfunc, "+"),
4826 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
4827 wrap_binaryfunc, "-"),
4828 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
4829 wrap_binaryfunc, "*"),
4830 IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
4831 wrap_binaryfunc, "/"),
4832 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
4833 wrap_binaryfunc, "%"),
4834 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
Guido van Rossum6e5680f2002-10-15 01:01:53 +00004835 wrap_binaryfunc, "**"),
Guido van Rossum6d204072001-10-21 00:44:31 +00004836 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
4837 wrap_binaryfunc, "<<"),
4838 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
4839 wrap_binaryfunc, ">>"),
4840 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
4841 wrap_binaryfunc, "&"),
4842 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
4843 wrap_binaryfunc, "^"),
4844 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
4845 wrap_binaryfunc, "|"),
4846 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
4847 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
4848 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
4849 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
4850 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
4851 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
4852 IBSLOT("__itruediv__", nb_inplace_true_divide,
4853 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004854
Guido van Rossum6d204072001-10-21 00:44:31 +00004855 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
4856 "x.__str__() <==> str(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00004857 TPSLOT("__str__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00004858 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
4859 "x.__repr__() <==> repr(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00004860 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00004861 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
4862 "x.__cmp__(y) <==> cmp(x,y)"),
4863 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
4864 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00004865 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
4866 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004867 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00004868 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
4869 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
4870 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
4871 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
4872 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
4873 "x.__setattr__('name', value) <==> x.name = value"),
4874 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
4875 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
4876 "x.__delattr__('name') <==> del x.name"),
4877 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
4878 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
4879 "x.__lt__(y) <==> x<y"),
4880 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
4881 "x.__le__(y) <==> x<=y"),
4882 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
4883 "x.__eq__(y) <==> x==y"),
4884 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
4885 "x.__ne__(y) <==> x!=y"),
4886 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
4887 "x.__gt__(y) <==> x>y"),
4888 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
4889 "x.__ge__(y) <==> x>=y"),
4890 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
4891 "x.__iter__() <==> iter(x)"),
4892 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
4893 "x.next() -> the next value, or raise StopIteration"),
4894 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
4895 "descr.__get__(obj[, type]) -> value"),
4896 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
4897 "descr.__set__(obj, value)"),
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004898 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
4899 wrap_descr_delete, "descr.__delete__(obj)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00004900 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00004901 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00004902 "see x.__class__.__doc__ for signature",
4903 PyWrapperFlag_KEYWORDS),
4904 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004905 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004906 {NULL}
4907};
4908
Guido van Rossumc334df52002-04-04 23:44:47 +00004909/* Given a type pointer and an offset gotten from a slotdef entry, return a
4910 pointer to the actual slot. This is not quite the same as simply adding
4911 the offset to the type pointer, since it takes care to indirect through the
4912 proper indirection pointer (as_buffer, etc.); it returns NULL if the
4913 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004914static void **
4915slotptr(PyTypeObject *type, int offset)
4916{
4917 char *ptr;
4918
Guido van Rossume5c691a2003-03-07 15:13:17 +00004919 /* Note: this depends on the order of the members of PyHeapTypeObject! */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004920 assert(offset >= 0);
Guido van Rossume5c691a2003-03-07 15:13:17 +00004921 assert(offset < offsetof(PyHeapTypeObject, as_buffer));
4922 if (offset >= offsetof(PyHeapTypeObject, as_sequence)) {
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004923 ptr = (void *)type->tp_as_sequence;
Guido van Rossume5c691a2003-03-07 15:13:17 +00004924 offset -= offsetof(PyHeapTypeObject, as_sequence);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004925 }
Guido van Rossume5c691a2003-03-07 15:13:17 +00004926 else if (offset >= offsetof(PyHeapTypeObject, as_mapping)) {
Guido van Rossum09638c12002-06-13 19:17:46 +00004927 ptr = (void *)type->tp_as_mapping;
Guido van Rossume5c691a2003-03-07 15:13:17 +00004928 offset -= offsetof(PyHeapTypeObject, as_mapping);
Guido van Rossum09638c12002-06-13 19:17:46 +00004929 }
Guido van Rossume5c691a2003-03-07 15:13:17 +00004930 else if (offset >= offsetof(PyHeapTypeObject, as_number)) {
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004931 ptr = (void *)type->tp_as_number;
Guido van Rossume5c691a2003-03-07 15:13:17 +00004932 offset -= offsetof(PyHeapTypeObject, as_number);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004933 }
4934 else {
4935 ptr = (void *)type;
4936 }
4937 if (ptr != NULL)
4938 ptr += offset;
4939 return (void **)ptr;
4940}
Guido van Rossumf040ede2001-08-07 16:40:56 +00004941
Guido van Rossumc334df52002-04-04 23:44:47 +00004942/* Length of array of slotdef pointers used to store slots with the
4943 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
4944 the same __name__, for any __name__. Since that's a static property, it is
4945 appropriate to declare fixed-size arrays for this. */
4946#define MAX_EQUIV 10
4947
4948/* Return a slot pointer for a given name, but ONLY if the attribute has
4949 exactly one slot function. The name must be an interned string. */
4950static void **
4951resolve_slotdups(PyTypeObject *type, PyObject *name)
4952{
4953 /* XXX Maybe this could be optimized more -- but is it worth it? */
4954
4955 /* pname and ptrs act as a little cache */
4956 static PyObject *pname;
4957 static slotdef *ptrs[MAX_EQUIV];
4958 slotdef *p, **pp;
4959 void **res, **ptr;
4960
4961 if (pname != name) {
4962 /* Collect all slotdefs that match name into ptrs. */
4963 pname = name;
4964 pp = ptrs;
4965 for (p = slotdefs; p->name_strobj; p++) {
4966 if (p->name_strobj == name)
4967 *pp++ = p;
4968 }
4969 *pp = NULL;
4970 }
4971
4972 /* Look in all matching slots of the type; if exactly one of these has
4973 a filled-in slot, return its value. Otherwise return NULL. */
4974 res = NULL;
4975 for (pp = ptrs; *pp; pp++) {
4976 ptr = slotptr(type, (*pp)->offset);
4977 if (ptr == NULL || *ptr == NULL)
4978 continue;
4979 if (res != NULL)
4980 return NULL;
4981 res = ptr;
4982 }
4983 return res;
4984}
4985
4986/* Common code for update_these_slots() and fixup_slot_dispatchers(). This
4987 does some incredibly complex thinking and then sticks something into the
4988 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
4989 interests, and then stores a generic wrapper or a specific function into
4990 the slot.) Return a pointer to the next slotdef with a different offset,
4991 because that's convenient for fixup_slot_dispatchers(). */
4992static slotdef *
4993update_one_slot(PyTypeObject *type, slotdef *p)
4994{
4995 PyObject *descr;
4996 PyWrapperDescrObject *d;
4997 void *generic = NULL, *specific = NULL;
4998 int use_generic = 0;
4999 int offset = p->offset;
5000 void **ptr = slotptr(type, offset);
5001
5002 if (ptr == NULL) {
5003 do {
5004 ++p;
5005 } while (p->offset == offset);
5006 return p;
5007 }
5008 do {
5009 descr = _PyType_Lookup(type, p->name_strobj);
5010 if (descr == NULL)
5011 continue;
5012 if (descr->ob_type == &PyWrapperDescr_Type) {
5013 void **tptr = resolve_slotdups(type, p->name_strobj);
5014 if (tptr == NULL || tptr == ptr)
5015 generic = p->function;
5016 d = (PyWrapperDescrObject *)descr;
5017 if (d->d_base->wrapper == p->wrapper &&
5018 PyType_IsSubtype(type, d->d_type))
5019 {
5020 if (specific == NULL ||
5021 specific == d->d_wrapped)
5022 specific = d->d_wrapped;
5023 else
5024 use_generic = 1;
5025 }
5026 }
Guido van Rossum721f62e2002-08-09 02:14:34 +00005027 else if (descr->ob_type == &PyCFunction_Type &&
5028 PyCFunction_GET_FUNCTION(descr) ==
5029 (PyCFunction)tp_new_wrapper &&
5030 strcmp(p->name, "__new__") == 0)
5031 {
5032 /* The __new__ wrapper is not a wrapper descriptor,
5033 so must be special-cased differently.
5034 If we don't do this, creating an instance will
5035 always use slot_tp_new which will look up
5036 __new__ in the MRO which will call tp_new_wrapper
5037 which will look through the base classes looking
5038 for a static base and call its tp_new (usually
5039 PyType_GenericNew), after performing various
5040 sanity checks and constructing a new argument
5041 list. Cut all that nonsense short -- this speeds
5042 up instance creation tremendously. */
5043 specific = type->tp_new;
5044 /* XXX I'm not 100% sure that there isn't a hole
5045 in this reasoning that requires additional
5046 sanity checks. I'll buy the first person to
5047 point out a bug in this reasoning a beer. */
5048 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005049 else {
5050 use_generic = 1;
5051 generic = p->function;
5052 }
5053 } while ((++p)->offset == offset);
5054 if (specific && !use_generic)
5055 *ptr = specific;
5056 else
5057 *ptr = generic;
5058 return p;
5059}
5060
Guido van Rossum22b13872002-08-06 21:41:44 +00005061static int recurse_down_subclasses(PyTypeObject *type, slotdef **pp,
Jeremy Hylton938ace62002-07-17 16:30:39 +00005062 PyObject *name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005063
Guido van Rossumc334df52002-04-04 23:44:47 +00005064/* In the type, update the slots whose slotdefs are gathered in the pp0 array,
5065 and then do the same for all this type's subtypes. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005066static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005067update_these_slots(PyTypeObject *type, slotdef **pp0, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005068{
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005069 slotdef **pp;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005070
Guido van Rossumc334df52002-04-04 23:44:47 +00005071 for (pp = pp0; *pp; pp++)
5072 update_one_slot(type, *pp);
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005073 return recurse_down_subclasses(type, pp0, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005074}
5075
Guido van Rossumc334df52002-04-04 23:44:47 +00005076/* Update the slots whose slotdefs are gathered in the pp array in all (direct
5077 or indirect) subclasses of type. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005078static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005079recurse_down_subclasses(PyTypeObject *type, slotdef **pp, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005080{
5081 PyTypeObject *subclass;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005082 PyObject *ref, *subclasses, *dict;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005083 int i, n;
5084
5085 subclasses = type->tp_subclasses;
5086 if (subclasses == NULL)
5087 return 0;
5088 assert(PyList_Check(subclasses));
5089 n = PyList_GET_SIZE(subclasses);
5090 for (i = 0; i < n; i++) {
5091 ref = PyList_GET_ITEM(subclasses, i);
5092 assert(PyWeakref_CheckRef(ref));
5093 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
Guido van Rossum59e6c532002-06-14 02:27:07 +00005094 assert(subclass != NULL);
5095 if ((PyObject *)subclass == Py_None)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005096 continue;
5097 assert(PyType_Check(subclass));
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005098 /* Avoid recursing down into unaffected classes */
5099 dict = subclass->tp_dict;
5100 if (dict != NULL && PyDict_Check(dict) &&
5101 PyDict_GetItem(dict, name) != NULL)
5102 continue;
5103 if (update_these_slots(subclass, pp, name) < 0)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005104 return -1;
5105 }
5106 return 0;
5107}
5108
Guido van Rossumc334df52002-04-04 23:44:47 +00005109/* Comparison function for qsort() to compare slotdefs by their offset, and
5110 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005111static int
5112slotdef_cmp(const void *aa, const void *bb)
5113{
5114 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
5115 int c = a->offset - b->offset;
5116 if (c != 0)
5117 return c;
5118 else
5119 return a - b;
5120}
5121
Guido van Rossumc334df52002-04-04 23:44:47 +00005122/* Initialize the slotdefs table by adding interned string objects for the
5123 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005124static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005125init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005126{
5127 slotdef *p;
5128 static int initialized = 0;
5129
5130 if (initialized)
5131 return;
5132 for (p = slotdefs; p->name; p++) {
5133 p->name_strobj = PyString_InternFromString(p->name);
5134 if (!p->name_strobj)
Guido van Rossumc334df52002-04-04 23:44:47 +00005135 Py_FatalError("Out of memory interning slotdef names");
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005136 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005137 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
5138 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005139 initialized = 1;
5140}
5141
Guido van Rossumc334df52002-04-04 23:44:47 +00005142/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005143static int
5144update_slot(PyTypeObject *type, PyObject *name)
5145{
Guido van Rossumc334df52002-04-04 23:44:47 +00005146 slotdef *ptrs[MAX_EQUIV];
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005147 slotdef *p;
5148 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005149 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005150
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005151 init_slotdefs();
5152 pp = ptrs;
5153 for (p = slotdefs; p->name; p++) {
5154 /* XXX assume name is interned! */
5155 if (p->name_strobj == name)
5156 *pp++ = p;
5157 }
5158 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005159 for (pp = ptrs; *pp; pp++) {
5160 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005161 offset = p->offset;
5162 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005163 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005164 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005165 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005166 if (ptrs[0] == NULL)
5167 return 0; /* Not an attribute that affects any slots */
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005168 return update_these_slots(type, ptrs, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005169}
5170
Guido van Rossumc334df52002-04-04 23:44:47 +00005171/* Store the proper functions in the slot dispatches at class (type)
5172 definition time, based upon which operations the class overrides in its
5173 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00005174static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005175fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005176{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005177 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005178
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005179 init_slotdefs();
Guido van Rossumc334df52002-04-04 23:44:47 +00005180 for (p = slotdefs; p->name; )
5181 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005182}
Guido van Rossum705f0f52001-08-24 16:47:00 +00005183
Michael W. Hudson98bbc492002-11-26 14:47:27 +00005184static void
5185update_all_slots(PyTypeObject* type)
5186{
5187 slotdef *p;
5188
5189 init_slotdefs();
5190 for (p = slotdefs; p->name; p++) {
5191 /* update_slot returns int but can't actually fail */
5192 update_slot(type, p->name_strobj);
5193 }
5194}
5195
Guido van Rossum6d204072001-10-21 00:44:31 +00005196/* This function is called by PyType_Ready() to populate the type's
5197 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00005198 function slot (like tp_repr) that's defined in the type, one or more
5199 corresponding descriptors are added in the type's tp_dict dictionary
5200 under the appropriate name (like __repr__). Some function slots
5201 cause more than one descriptor to be added (for example, the nb_add
5202 slot adds both __add__ and __radd__ descriptors) and some function
5203 slots compete for the same descriptor (for example both sq_item and
5204 mp_subscript generate a __getitem__ descriptor).
5205
5206 In the latter case, the first slotdef entry encoutered wins. Since
Guido van Rossume5c691a2003-03-07 15:13:17 +00005207 slotdef entries are sorted by the offset of the slot in the
5208 PyHeapTypeObject, this gives us some control over disambiguating
5209 between competing slots: the members of PyHeapTypeObject are listed from most
Guido van Rossum09638c12002-06-13 19:17:46 +00005210 general to least general, so the most general slot is preferred. In
5211 particular, because as_mapping comes before as_sequence, for a type
5212 that defines both mp_subscript and sq_item, mp_subscript wins.
5213
5214 This only adds new descriptors and doesn't overwrite entries in
5215 tp_dict that were previously defined. The descriptors contain a
5216 reference to the C function they must call, so that it's safe if they
5217 are copied into a subtype's __dict__ and the subtype has a different
5218 C function in its slot -- calling the method defined by the
5219 descriptor will call the C function that was used to create it,
5220 rather than the C function present in the slot when it is called.
5221 (This is important because a subtype may have a C function in the
5222 slot that calls the method from the dictionary, and we want to avoid
5223 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00005224
5225static int
5226add_operators(PyTypeObject *type)
5227{
5228 PyObject *dict = type->tp_dict;
5229 slotdef *p;
5230 PyObject *descr;
5231 void **ptr;
5232
5233 init_slotdefs();
5234 for (p = slotdefs; p->name; p++) {
5235 if (p->wrapper == NULL)
5236 continue;
5237 ptr = slotptr(type, p->offset);
5238 if (!ptr || !*ptr)
5239 continue;
5240 if (PyDict_GetItem(dict, p->name_strobj))
5241 continue;
5242 descr = PyDescr_NewWrapper(type, p, *ptr);
5243 if (descr == NULL)
5244 return -1;
5245 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
5246 return -1;
5247 Py_DECREF(descr);
5248 }
5249 if (type->tp_new != NULL) {
5250 if (add_tp_new_wrapper(type) < 0)
5251 return -1;
5252 }
5253 return 0;
5254}
5255
Guido van Rossum705f0f52001-08-24 16:47:00 +00005256
5257/* Cooperative 'super' */
5258
5259typedef struct {
5260 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00005261 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005262 PyObject *obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005263 PyTypeObject *obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005264} superobject;
5265
Guido van Rossum6f799372001-09-20 20:46:19 +00005266static PyMemberDef super_members[] = {
5267 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
5268 "the class invoking super()"},
5269 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
5270 "the instance invoking super(); may be None"},
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005271 {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
5272 "the type of the the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005273 {0}
5274};
5275
Guido van Rossum705f0f52001-08-24 16:47:00 +00005276static void
5277super_dealloc(PyObject *self)
5278{
5279 superobject *su = (superobject *)self;
5280
Guido van Rossum048eb752001-10-02 21:24:57 +00005281 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005282 Py_XDECREF(su->obj);
5283 Py_XDECREF(su->type);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005284 Py_XDECREF(su->obj_type);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005285 self->ob_type->tp_free(self);
5286}
5287
5288static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005289super_repr(PyObject *self)
5290{
5291 superobject *su = (superobject *)self;
5292
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005293 if (su->obj_type)
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005294 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005295 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005296 su->type ? su->type->tp_name : "NULL",
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005297 su->obj_type->tp_name);
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005298 else
5299 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005300 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005301 su->type ? su->type->tp_name : "NULL");
5302}
5303
5304static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00005305super_getattro(PyObject *self, PyObject *name)
5306{
5307 superobject *su = (superobject *)self;
5308
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005309 if (su->obj_type != NULL) {
Tim Petersa91e9642001-11-14 23:32:33 +00005310 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005311 PyTypeObject *starttype;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005312 descrgetfunc f;
5313 int i, n;
5314
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005315 starttype = su->obj_type;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005316 mro = starttype->tp_mro;
5317
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005318 if (mro == NULL)
5319 n = 0;
5320 else {
5321 assert(PyTuple_Check(mro));
5322 n = PyTuple_GET_SIZE(mro);
5323 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005324 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00005325 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00005326 break;
5327 }
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005328#if 0
Guido van Rossume705ef12001-08-29 15:47:06 +00005329 if (i >= n && PyType_Check(su->obj)) {
Guido van Rossum155db9a2002-04-02 17:53:47 +00005330 starttype = (PyTypeObject *)(su->obj);
5331 mro = starttype->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005332 if (mro == NULL)
5333 n = 0;
5334 else {
5335 assert(PyTuple_Check(mro));
5336 n = PyTuple_GET_SIZE(mro);
5337 }
Guido van Rossume705ef12001-08-29 15:47:06 +00005338 for (i = 0; i < n; i++) {
5339 if ((PyObject *)(su->type) ==
5340 PyTuple_GET_ITEM(mro, i))
5341 break;
5342 }
Guido van Rossume705ef12001-08-29 15:47:06 +00005343 }
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005344#endif
Guido van Rossum705f0f52001-08-24 16:47:00 +00005345 i++;
5346 res = NULL;
5347 for (; i < n; i++) {
5348 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00005349 if (PyType_Check(tmp))
5350 dict = ((PyTypeObject *)tmp)->tp_dict;
5351 else if (PyClass_Check(tmp))
5352 dict = ((PyClassObject *)tmp)->cl_dict;
5353 else
5354 continue;
5355 res = PyDict_GetItem(dict, name);
Guido van Rossum5b443c62001-12-03 15:38:28 +00005356 if (res != NULL && !PyDescr_IsData(res)) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00005357 Py_INCREF(res);
5358 f = res->ob_type->tp_descr_get;
5359 if (f != NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00005360 tmp = f(res, su->obj,
5361 (PyObject *)starttype);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005362 Py_DECREF(res);
5363 res = tmp;
5364 }
5365 return res;
5366 }
5367 }
5368 }
5369 return PyObject_GenericGetAttr(self, name);
5370}
5371
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005372static PyTypeObject *
Guido van Rossum5b443c62001-12-03 15:38:28 +00005373supercheck(PyTypeObject *type, PyObject *obj)
5374{
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005375 /* Check that a super() call makes sense. Return a type object.
5376
5377 obj can be a new-style class, or an instance of one:
5378
5379 - If it is a class, it must be a subclass of 'type'. This case is
5380 used for class methods; the return value is obj.
5381
5382 - If it is an instance, it must be an instance of 'type'. This is
5383 the normal case; the return value is obj.__class__.
5384
5385 But... when obj is an instance, we want to allow for the case where
5386 obj->ob_type is not a subclass of type, but obj.__class__ is!
5387 This will allow using super() with a proxy for obj.
5388 */
5389
Guido van Rossum8e80a722003-02-18 19:22:22 +00005390 /* Check for first bullet above (special case) */
5391 if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
5392 Py_INCREF(obj);
5393 return (PyTypeObject *)obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005394 }
Guido van Rossum8e80a722003-02-18 19:22:22 +00005395
5396 /* Normal case */
5397 if (PyType_IsSubtype(obj->ob_type, type)) {
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005398 Py_INCREF(obj->ob_type);
5399 return obj->ob_type;
5400 }
5401 else {
5402 /* Try the slow way */
5403 static PyObject *class_str = NULL;
5404 PyObject *class_attr;
5405
5406 if (class_str == NULL) {
5407 class_str = PyString_FromString("__class__");
5408 if (class_str == NULL)
5409 return NULL;
5410 }
5411
5412 class_attr = PyObject_GetAttr(obj, class_str);
5413
5414 if (class_attr != NULL &&
5415 PyType_Check(class_attr) &&
5416 (PyTypeObject *)class_attr != obj->ob_type)
5417 {
5418 int ok = PyType_IsSubtype(
5419 (PyTypeObject *)class_attr, type);
5420 if (ok)
5421 return (PyTypeObject *)class_attr;
5422 }
5423
5424 if (class_attr == NULL)
5425 PyErr_Clear();
5426 else
5427 Py_DECREF(class_attr);
5428 }
5429
Tim Peters97e5ff52003-02-18 19:32:50 +00005430 PyErr_SetString(PyExc_TypeError,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005431 "super(type, obj): "
5432 "obj must be an instance or subtype of type");
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005433 return NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005434}
5435
Guido van Rossum705f0f52001-08-24 16:47:00 +00005436static PyObject *
5437super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5438{
5439 superobject *su = (superobject *)self;
5440 superobject *new;
5441
5442 if (obj == NULL || obj == Py_None || su->obj != NULL) {
5443 /* Not binding to an object, or already bound */
5444 Py_INCREF(self);
5445 return self;
5446 }
Guido van Rossum5b443c62001-12-03 15:38:28 +00005447 if (su->ob_type != &PySuper_Type)
5448 /* If su is an instance of a subclass of super,
5449 call its type */
5450 return PyObject_CallFunction((PyObject *)su->ob_type,
5451 "OO", su->type, obj);
5452 else {
5453 /* Inline the common case */
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005454 PyTypeObject *obj_type = supercheck(su->type, obj);
5455 if (obj_type == NULL)
Guido van Rossum5b443c62001-12-03 15:38:28 +00005456 return NULL;
5457 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
5458 NULL, NULL);
5459 if (new == NULL)
5460 return NULL;
5461 Py_INCREF(su->type);
5462 Py_INCREF(obj);
5463 new->type = su->type;
5464 new->obj = obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005465 new->obj_type = obj_type;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005466 return (PyObject *)new;
5467 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005468}
5469
5470static int
5471super_init(PyObject *self, PyObject *args, PyObject *kwds)
5472{
5473 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00005474 PyTypeObject *type;
5475 PyObject *obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005476 PyTypeObject *obj_type = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005477
5478 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
5479 return -1;
5480 if (obj == Py_None)
5481 obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005482 if (obj != NULL) {
5483 obj_type = supercheck(type, obj);
5484 if (obj_type == NULL)
5485 return -1;
5486 Py_INCREF(obj);
5487 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005488 Py_INCREF(type);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005489 su->type = type;
5490 su->obj = obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005491 su->obj_type = obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005492 return 0;
5493}
5494
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005495PyDoc_STRVAR(super_doc,
Guido van Rossum705f0f52001-08-24 16:47:00 +00005496"super(type) -> unbound super object\n"
5497"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00005498"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00005499"Typical use to call a cooperative superclass method:\n"
5500"class C(B):\n"
5501" def meth(self, arg):\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005502" super(C, self).meth(arg)");
Guido van Rossum705f0f52001-08-24 16:47:00 +00005503
Guido van Rossum048eb752001-10-02 21:24:57 +00005504static int
5505super_traverse(PyObject *self, visitproc visit, void *arg)
5506{
5507 superobject *su = (superobject *)self;
5508 int err;
5509
5510#define VISIT(SLOT) \
5511 if (SLOT) { \
5512 err = visit((PyObject *)(SLOT), arg); \
5513 if (err) \
5514 return err; \
5515 }
5516
5517 VISIT(su->obj);
5518 VISIT(su->type);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005519 VISIT(su->obj_type);
Guido van Rossum048eb752001-10-02 21:24:57 +00005520
5521#undef VISIT
5522
5523 return 0;
5524}
5525
Guido van Rossum705f0f52001-08-24 16:47:00 +00005526PyTypeObject PySuper_Type = {
5527 PyObject_HEAD_INIT(&PyType_Type)
5528 0, /* ob_size */
5529 "super", /* tp_name */
5530 sizeof(superobject), /* tp_basicsize */
5531 0, /* tp_itemsize */
5532 /* methods */
5533 super_dealloc, /* tp_dealloc */
5534 0, /* tp_print */
5535 0, /* tp_getattr */
5536 0, /* tp_setattr */
5537 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005538 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005539 0, /* tp_as_number */
5540 0, /* tp_as_sequence */
5541 0, /* tp_as_mapping */
5542 0, /* tp_hash */
5543 0, /* tp_call */
5544 0, /* tp_str */
5545 super_getattro, /* tp_getattro */
5546 0, /* tp_setattro */
5547 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00005548 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
5549 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005550 super_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00005551 super_traverse, /* tp_traverse */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005552 0, /* tp_clear */
5553 0, /* tp_richcompare */
5554 0, /* tp_weaklistoffset */
5555 0, /* tp_iter */
5556 0, /* tp_iternext */
5557 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005558 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005559 0, /* tp_getset */
5560 0, /* tp_base */
5561 0, /* tp_dict */
5562 super_descr_get, /* tp_descr_get */
5563 0, /* tp_descr_set */
5564 0, /* tp_dictoffset */
5565 super_init, /* tp_init */
5566 PyType_GenericAlloc, /* tp_alloc */
5567 PyType_GenericNew, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00005568 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005569};