blob: a067cd5963fbcbca1895368d93d043a82db6b196 [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
1079 off = PyOS_snprintf(buf, sizeof(buf), "MRO conflict among bases");
1080 i = 0;
1081 while (PyDict_Next(set, &i, &k, &v) && off < sizeof(buf)) {
1082 PyObject *name = class_name(k);
1083 off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s",
1084 name ? PyString_AS_STRING(name) : "?");
1085 Py_XDECREF(name);
1086 if (--n && off+1 < sizeof(buf)) {
1087 buf[off++] = ',';
1088 buf[off] = '\0';
1089 }
1090 }
1091 PyErr_SetString(PyExc_TypeError, buf);
1092 Py_DECREF(set);
1093}
1094
Tim Petersea7f75d2002-12-07 21:39:16 +00001095static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001096pmerge(PyObject *acc, PyObject* to_merge) {
1097 int i, j, to_merge_size;
1098 int *remain;
1099 int ok, empty_cnt;
Tim Petersea7f75d2002-12-07 21:39:16 +00001100
Guido van Rossum1f121312002-11-14 19:49:16 +00001101 to_merge_size = PyList_GET_SIZE(to_merge);
1102
Guido van Rossum98f33732002-11-25 21:36:54 +00001103 /* remain stores an index into each sublist of to_merge.
1104 remain[i] is the index of the next base in to_merge[i]
1105 that is not included in acc.
1106 */
Guido van Rossum1f121312002-11-14 19:49:16 +00001107 remain = PyMem_MALLOC(SIZEOF_INT*to_merge_size);
1108 if (remain == NULL)
1109 return -1;
1110 for (i = 0; i < to_merge_size; i++)
1111 remain[i] = 0;
1112
1113 again:
1114 empty_cnt = 0;
1115 for (i = 0; i < to_merge_size; i++) {
1116 PyObject *candidate;
Tim Petersea7f75d2002-12-07 21:39:16 +00001117
Guido van Rossum1f121312002-11-14 19:49:16 +00001118 PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
1119
1120 if (remain[i] >= PyList_GET_SIZE(cur_list)) {
1121 empty_cnt++;
1122 continue;
1123 }
1124
Guido van Rossum98f33732002-11-25 21:36:54 +00001125 /* Choose next candidate for MRO.
1126
1127 The input sequences alone can determine the choice.
1128 If not, choose the class which appears in the MRO
1129 of the earliest direct superclass of the new class.
1130 */
1131
Guido van Rossum1f121312002-11-14 19:49:16 +00001132 candidate = PyList_GET_ITEM(cur_list, remain[i]);
1133 for (j = 0; j < to_merge_size; j++) {
1134 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum98f33732002-11-25 21:36:54 +00001135 if (tail_contains(j_lst, remain[j], candidate)) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001136 goto skip; /* continue outer loop */
Guido van Rossum98f33732002-11-25 21:36:54 +00001137 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001138 }
1139 ok = PyList_Append(acc, candidate);
1140 if (ok < 0) {
1141 PyMem_Free(remain);
1142 return -1;
1143 }
1144 for (j = 0; j < to_merge_size; j++) {
1145 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum768158c2002-12-31 16:33:01 +00001146 if (remain[j] < PyList_GET_SIZE(j_lst) &&
1147 PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001148 remain[j]++;
1149 }
1150 }
1151 goto again;
Tim Peters9a6b8d82002-11-14 23:22:33 +00001152 skip: ;
Guido van Rossum1f121312002-11-14 19:49:16 +00001153 }
1154
Guido van Rossum98f33732002-11-25 21:36:54 +00001155 if (empty_cnt == to_merge_size) {
1156 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001157 return 0;
Guido van Rossum98f33732002-11-25 21:36:54 +00001158 }
1159 set_mro_error(to_merge, remain);
1160 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001161 return -1;
1162}
1163
Tim Peters6d6c1a32001-08-02 04:15:00 +00001164static PyObject *
1165mro_implementation(PyTypeObject *type)
1166{
1167 int i, n, ok;
1168 PyObject *bases, *result;
Guido van Rossum1f121312002-11-14 19:49:16 +00001169 PyObject *to_merge, *bases_aslist;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001170
Guido van Rossum63517572002-06-18 16:44:57 +00001171 if(type->tp_dict == NULL) {
1172 if(PyType_Ready(type) < 0)
1173 return NULL;
1174 }
1175
Guido van Rossum98f33732002-11-25 21:36:54 +00001176 /* Find a superclass linearization that honors the constraints
1177 of the explicit lists of bases and the constraints implied by
Tim Petersea7f75d2002-12-07 21:39:16 +00001178 each base class.
Guido van Rossum98f33732002-11-25 21:36:54 +00001179
1180 to_merge is a list of lists, where each list is a superclass
1181 linearization implied by a base class. The last element of
1182 to_merge is the declared list of bases.
1183 */
1184
Tim Peters6d6c1a32001-08-02 04:15:00 +00001185 bases = type->tp_bases;
1186 n = PyTuple_GET_SIZE(bases);
Guido van Rossum1f121312002-11-14 19:49:16 +00001187
1188 to_merge = PyList_New(n+1);
1189 if (to_merge == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001190 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001191
Tim Peters6d6c1a32001-08-02 04:15:00 +00001192 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001193 PyObject *base = PyTuple_GET_ITEM(bases, i);
1194 PyObject *parentMRO;
1195 if (PyType_Check(base))
1196 parentMRO = PySequence_List(
1197 ((PyTypeObject*)base)->tp_mro);
1198 else
1199 parentMRO = classic_mro(base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001200 if (parentMRO == NULL) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001201 Py_DECREF(to_merge);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001202 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001203 }
1204
1205 PyList_SET_ITEM(to_merge, i, parentMRO);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001206 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001207
1208 bases_aslist = PySequence_List(bases);
1209 if (bases_aslist == NULL) {
1210 Py_DECREF(to_merge);
1211 return NULL;
1212 }
Guido van Rossum98f33732002-11-25 21:36:54 +00001213 /* This is just a basic sanity check. */
1214 if (check_duplicates(bases_aslist) < 0) {
1215 Py_DECREF(to_merge);
1216 Py_DECREF(bases_aslist);
1217 return NULL;
1218 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001219 PyList_SET_ITEM(to_merge, n, bases_aslist);
1220
1221 result = Py_BuildValue("[O]", (PyObject *)type);
1222 if (result == NULL) {
1223 Py_DECREF(to_merge);
1224 return NULL;
1225 }
1226
1227 ok = pmerge(result, to_merge);
1228 Py_DECREF(to_merge);
1229 if (ok < 0) {
1230 Py_DECREF(result);
1231 return NULL;
1232 }
1233
Tim Peters6d6c1a32001-08-02 04:15:00 +00001234 return result;
1235}
1236
1237static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001238mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001239{
1240 PyTypeObject *type = (PyTypeObject *)self;
1241
Tim Peters6d6c1a32001-08-02 04:15:00 +00001242 return mro_implementation(type);
1243}
1244
1245static int
1246mro_internal(PyTypeObject *type)
1247{
1248 PyObject *mro, *result, *tuple;
1249
1250 if (type->ob_type == &PyType_Type) {
1251 result = mro_implementation(type);
1252 }
1253 else {
Guido van Rossum60718732001-08-28 17:47:51 +00001254 static PyObject *mro_str;
1255 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001256 if (mro == NULL)
1257 return -1;
1258 result = PyObject_CallObject(mro, NULL);
1259 Py_DECREF(mro);
1260 }
1261 if (result == NULL)
1262 return -1;
1263 tuple = PySequence_Tuple(result);
1264 Py_DECREF(result);
1265 type->tp_mro = tuple;
1266 return 0;
1267}
1268
1269
1270/* Calculate the best base amongst multiple base classes.
1271 This is the first one that's on the path to the "solid base". */
1272
1273static PyTypeObject *
1274best_base(PyObject *bases)
1275{
1276 int i, n;
1277 PyTypeObject *base, *winner, *candidate, *base_i;
Tim Petersa91e9642001-11-14 23:32:33 +00001278 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001279
1280 assert(PyTuple_Check(bases));
1281 n = PyTuple_GET_SIZE(bases);
1282 assert(n > 0);
Tim Petersa91e9642001-11-14 23:32:33 +00001283 base = NULL;
1284 winner = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001285 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001286 base_proto = PyTuple_GET_ITEM(bases, i);
1287 if (PyClass_Check(base_proto))
1288 continue;
1289 if (!PyType_Check(base_proto)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001290 PyErr_SetString(
1291 PyExc_TypeError,
1292 "bases must be types");
1293 return NULL;
1294 }
Tim Petersa91e9642001-11-14 23:32:33 +00001295 base_i = (PyTypeObject *)base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001296 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001297 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001298 return NULL;
1299 }
1300 candidate = solid_base(base_i);
Tim Petersa91e9642001-11-14 23:32:33 +00001301 if (winner == NULL) {
1302 winner = candidate;
1303 base = base_i;
1304 }
1305 else if (PyType_IsSubtype(winner, candidate))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001306 ;
1307 else if (PyType_IsSubtype(candidate, winner)) {
1308 winner = candidate;
1309 base = base_i;
1310 }
1311 else {
1312 PyErr_SetString(
1313 PyExc_TypeError,
1314 "multiple bases have "
1315 "instance lay-out conflict");
1316 return NULL;
1317 }
1318 }
Guido van Rossume54616c2001-12-14 04:19:56 +00001319 if (base == NULL)
1320 PyErr_SetString(PyExc_TypeError,
1321 "a new-style class can't have only classic bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001322 return base;
1323}
1324
1325static int
1326extra_ivars(PyTypeObject *type, PyTypeObject *base)
1327{
Neil Schemenauerc806c882001-08-29 23:54:54 +00001328 size_t t_size = type->tp_basicsize;
1329 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001330
Guido van Rossum9676b222001-08-17 20:32:36 +00001331 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001332 if (type->tp_itemsize || base->tp_itemsize) {
1333 /* If itemsize is involved, stricter rules */
1334 return t_size != b_size ||
1335 type->tp_itemsize != base->tp_itemsize;
1336 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001337 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
1338 type->tp_weaklistoffset + sizeof(PyObject *) == t_size)
1339 t_size -= sizeof(PyObject *);
1340 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
1341 type->tp_dictoffset + sizeof(PyObject *) == t_size)
1342 t_size -= sizeof(PyObject *);
1343
1344 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001345}
1346
1347static PyTypeObject *
1348solid_base(PyTypeObject *type)
1349{
1350 PyTypeObject *base;
1351
1352 if (type->tp_base)
1353 base = solid_base(type->tp_base);
1354 else
1355 base = &PyBaseObject_Type;
1356 if (extra_ivars(type, base))
1357 return type;
1358 else
1359 return base;
1360}
1361
Jeremy Hylton938ace62002-07-17 16:30:39 +00001362static void object_dealloc(PyObject *);
1363static int object_init(PyObject *, PyObject *, PyObject *);
1364static int update_slot(PyTypeObject *, PyObject *);
1365static void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001366
1367static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001368subtype_dict(PyObject *obj, void *context)
1369{
1370 PyObject **dictptr = _PyObject_GetDictPtr(obj);
1371 PyObject *dict;
1372
1373 if (dictptr == NULL) {
1374 PyErr_SetString(PyExc_AttributeError,
1375 "This object has no __dict__");
1376 return NULL;
1377 }
1378 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +00001379 if (dict == NULL)
1380 *dictptr = dict = PyDict_New();
1381 Py_XINCREF(dict);
1382 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001383}
1384
Guido van Rossum6661be32001-10-26 04:26:12 +00001385static int
1386subtype_setdict(PyObject *obj, PyObject *value, void *context)
1387{
1388 PyObject **dictptr = _PyObject_GetDictPtr(obj);
1389 PyObject *dict;
1390
1391 if (dictptr == NULL) {
1392 PyErr_SetString(PyExc_AttributeError,
1393 "This object has no __dict__");
1394 return -1;
1395 }
Guido van Rossumd331cb52001-12-05 19:46:42 +00001396 if (value != NULL && !PyDict_Check(value)) {
Guido van Rossum6661be32001-10-26 04:26:12 +00001397 PyErr_SetString(PyExc_TypeError,
1398 "__dict__ must be set to a dictionary");
1399 return -1;
1400 }
1401 dict = *dictptr;
Guido van Rossumd331cb52001-12-05 19:46:42 +00001402 Py_XINCREF(value);
Guido van Rossum6661be32001-10-26 04:26:12 +00001403 *dictptr = value;
1404 Py_XDECREF(dict);
1405 return 0;
1406}
1407
Guido van Rossumad47da02002-08-12 19:05:44 +00001408static PyObject *
1409subtype_getweakref(PyObject *obj, void *context)
1410{
1411 PyObject **weaklistptr;
1412 PyObject *result;
1413
1414 if (obj->ob_type->tp_weaklistoffset == 0) {
1415 PyErr_SetString(PyExc_AttributeError,
1416 "This object has no __weaklist__");
1417 return NULL;
1418 }
1419 assert(obj->ob_type->tp_weaklistoffset > 0);
1420 assert(obj->ob_type->tp_weaklistoffset + sizeof(PyObject *) <=
Guido van Rossum3747a0f2002-08-12 19:25:08 +00001421 (size_t)(obj->ob_type->tp_basicsize));
Guido van Rossumad47da02002-08-12 19:05:44 +00001422 weaklistptr = (PyObject **)
Guido van Rossum3747a0f2002-08-12 19:25:08 +00001423 ((char *)obj + obj->ob_type->tp_weaklistoffset);
Guido van Rossumad47da02002-08-12 19:05:44 +00001424 if (*weaklistptr == NULL)
1425 result = Py_None;
1426 else
1427 result = *weaklistptr;
1428 Py_INCREF(result);
1429 return result;
1430}
1431
Guido van Rossum373c7412003-01-07 13:41:37 +00001432/* Three variants on the subtype_getsets list. */
1433
1434static PyGetSetDef subtype_getsets_full[] = {
Guido van Rossumad47da02002-08-12 19:05:44 +00001435 {"__dict__", subtype_dict, subtype_setdict,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001436 PyDoc_STR("dictionary for instance variables (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001437 {"__weakref__", subtype_getweakref, NULL,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001438 PyDoc_STR("list of weak references to the object (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001439 {0}
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001440};
1441
Guido van Rossum373c7412003-01-07 13:41:37 +00001442static PyGetSetDef subtype_getsets_dict_only[] = {
1443 {"__dict__", subtype_dict, subtype_setdict,
1444 PyDoc_STR("dictionary for instance variables (if defined)")},
1445 {0}
1446};
1447
1448static PyGetSetDef subtype_getsets_weakref_only[] = {
1449 {"__weakref__", subtype_getweakref, NULL,
1450 PyDoc_STR("list of weak references to the object (if defined)")},
1451 {0}
1452};
1453
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001454static int
1455valid_identifier(PyObject *s)
1456{
Guido van Rossum03013a02002-07-16 14:30:28 +00001457 unsigned char *p;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001458 int i, n;
1459
1460 if (!PyString_Check(s)) {
1461 PyErr_SetString(PyExc_TypeError,
1462 "__slots__ must be strings");
1463 return 0;
1464 }
Guido van Rossum03013a02002-07-16 14:30:28 +00001465 p = (unsigned char *) PyString_AS_STRING(s);
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001466 n = PyString_GET_SIZE(s);
1467 /* We must reject an empty name. As a hack, we bump the
1468 length to 1 so that the loop will balk on the trailing \0. */
1469 if (n == 0)
1470 n = 1;
1471 for (i = 0; i < n; i++, p++) {
1472 if (!(i == 0 ? isalpha(*p) : isalnum(*p)) && *p != '_') {
1473 PyErr_SetString(PyExc_TypeError,
1474 "__slots__ must be identifiers");
1475 return 0;
1476 }
1477 }
1478 return 1;
1479}
1480
Martin v. Löwisd919a592002-10-14 21:07:28 +00001481#ifdef Py_USING_UNICODE
1482/* Replace Unicode objects in slots. */
1483
1484static PyObject *
1485_unicode_to_string(PyObject *slots, int nslots)
1486{
1487 PyObject *tmp = slots;
1488 PyObject *o, *o1;
1489 int i;
1490 intintargfunc copy = slots->ob_type->tp_as_sequence->sq_slice;
1491 for (i = 0; i < nslots; i++) {
1492 if (PyUnicode_Check(o = PyTuple_GET_ITEM(tmp, i))) {
1493 if (tmp == slots) {
1494 tmp = copy(slots, 0, PyTuple_GET_SIZE(slots));
1495 if (tmp == NULL)
1496 return NULL;
1497 }
1498 o1 = _PyUnicode_AsDefaultEncodedString
1499 (o, NULL);
1500 if (o1 == NULL) {
1501 Py_DECREF(tmp);
1502 return 0;
1503 }
1504 Py_INCREF(o1);
1505 Py_DECREF(o);
1506 PyTuple_SET_ITEM(tmp, i, o1);
1507 }
1508 }
1509 return tmp;
1510}
1511#endif
1512
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001513static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001514type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
1515{
1516 PyObject *name, *bases, *dict;
1517 static char *kwlist[] = {"name", "bases", "dict", 0};
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001518 PyObject *slots, *tmp, *newslots;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001519 PyTypeObject *type, *base, *tmptype, *winner;
Guido van Rossume5c691a2003-03-07 15:13:17 +00001520 PyHeapTypeObject *et;
Guido van Rossum6f799372001-09-20 20:46:19 +00001521 PyMemberDef *mp;
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001522 int i, nbases, nslots, slotoffset, add_dict, add_weak;
Guido van Rossumad47da02002-08-12 19:05:44 +00001523 int j, may_add_dict, may_add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001524
Tim Peters3abca122001-10-27 19:37:48 +00001525 assert(args != NULL && PyTuple_Check(args));
1526 assert(kwds == NULL || PyDict_Check(kwds));
1527
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001528 /* Special case: type(x) should return x->ob_type */
Tim Peters3abca122001-10-27 19:37:48 +00001529 {
1530 const int nargs = PyTuple_GET_SIZE(args);
1531 const int nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
1532
1533 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
1534 PyObject *x = PyTuple_GET_ITEM(args, 0);
1535 Py_INCREF(x->ob_type);
1536 return (PyObject *) x->ob_type;
1537 }
1538
1539 /* SF bug 475327 -- if that didn't trigger, we need 3
1540 arguments. but PyArg_ParseTupleAndKeywords below may give
1541 a msg saying type() needs exactly 3. */
1542 if (nargs + nkwds != 3) {
1543 PyErr_SetString(PyExc_TypeError,
1544 "type() takes 1 or 3 arguments");
1545 return NULL;
1546 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001547 }
1548
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001549 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001550 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
1551 &name,
1552 &PyTuple_Type, &bases,
1553 &PyDict_Type, &dict))
1554 return NULL;
1555
1556 /* Determine the proper metatype to deal with this,
1557 and check for metatype conflicts while we're at it.
1558 Note that if some other metatype wins to contract,
1559 it's possible that its instances are not types. */
1560 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001561 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001562 for (i = 0; i < nbases; i++) {
1563 tmp = PyTuple_GET_ITEM(bases, i);
1564 tmptype = tmp->ob_type;
Tim Petersa91e9642001-11-14 23:32:33 +00001565 if (tmptype == &PyClass_Type)
1566 continue; /* Special case classic classes */
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001567 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001568 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001569 if (PyType_IsSubtype(tmptype, winner)) {
1570 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001571 continue;
1572 }
1573 PyErr_SetString(PyExc_TypeError,
1574 "metatype conflict among bases");
1575 return NULL;
1576 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001577 if (winner != metatype) {
1578 if (winner->tp_new != type_new) /* Pass it to the winner */
1579 return winner->tp_new(winner, args, kwds);
1580 metatype = winner;
1581 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001582
1583 /* Adjust for empty tuple bases */
1584 if (nbases == 0) {
1585 bases = Py_BuildValue("(O)", &PyBaseObject_Type);
1586 if (bases == NULL)
1587 return NULL;
1588 nbases = 1;
1589 }
1590 else
1591 Py_INCREF(bases);
1592
1593 /* XXX From here until type is allocated, "return NULL" leaks bases! */
1594
1595 /* Calculate best base, and check that all bases are type objects */
1596 base = best_base(bases);
1597 if (base == NULL)
1598 return NULL;
1599 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
1600 PyErr_Format(PyExc_TypeError,
1601 "type '%.100s' is not an acceptable base type",
1602 base->tp_name);
1603 return NULL;
1604 }
1605
Tim Peters6d6c1a32001-08-02 04:15:00 +00001606 /* Check for a __slots__ sequence variable in dict, and count it */
1607 slots = PyDict_GetItemString(dict, "__slots__");
1608 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +00001609 add_dict = 0;
1610 add_weak = 0;
Guido van Rossumad47da02002-08-12 19:05:44 +00001611 may_add_dict = base->tp_dictoffset == 0;
1612 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
1613 if (slots == NULL) {
1614 if (may_add_dict) {
1615 add_dict++;
1616 }
1617 if (may_add_weak) {
1618 add_weak++;
1619 }
1620 }
1621 else {
1622 /* Have slots */
1623
Tim Peters6d6c1a32001-08-02 04:15:00 +00001624 /* Make it into a tuple */
1625 if (PyString_Check(slots))
1626 slots = Py_BuildValue("(O)", slots);
1627 else
1628 slots = PySequence_Tuple(slots);
1629 if (slots == NULL)
1630 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00001631 assert(PyTuple_Check(slots));
1632
1633 /* Are slots allowed? */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001634 nslots = PyTuple_GET_SIZE(slots);
Guido van Rossume5c691a2003-03-07 15:13:17 +00001635 if (nslots > 0 && base->tp_itemsize != 0 && !PyType_Check(base)) {
1636 /* for the special case of meta types, allow slots */
Guido van Rossumc4141872001-08-30 04:43:35 +00001637 PyErr_Format(PyExc_TypeError,
1638 "nonempty __slots__ "
1639 "not supported for subtype of '%s'",
1640 base->tp_name);
Guido van Rossumad47da02002-08-12 19:05:44 +00001641 bad_slots:
1642 Py_DECREF(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +00001643 return NULL;
1644 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001645
Martin v. Löwisd919a592002-10-14 21:07:28 +00001646#ifdef Py_USING_UNICODE
1647 tmp = _unicode_to_string(slots, nslots);
Martin v. Löwis13b1a5c2002-10-14 21:11:34 +00001648 if (tmp != slots) {
1649 Py_DECREF(slots);
1650 slots = tmp;
1651 }
Martin v. Löwisd919a592002-10-14 21:07:28 +00001652 if (!tmp)
1653 return NULL;
1654#endif
Guido van Rossumad47da02002-08-12 19:05:44 +00001655 /* Check for valid slot names and two special cases */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001656 for (i = 0; i < nslots; i++) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001657 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
1658 char *s;
1659 if (!valid_identifier(tmp))
1660 goto bad_slots;
1661 assert(PyString_Check(tmp));
1662 s = PyString_AS_STRING(tmp);
1663 if (strcmp(s, "__dict__") == 0) {
1664 if (!may_add_dict || add_dict) {
1665 PyErr_SetString(PyExc_TypeError,
1666 "__dict__ slot disallowed: "
1667 "we already got one");
1668 goto bad_slots;
1669 }
1670 add_dict++;
1671 }
1672 if (strcmp(s, "__weakref__") == 0) {
1673 if (!may_add_weak || add_weak) {
1674 PyErr_SetString(PyExc_TypeError,
1675 "__weakref__ slot disallowed: "
1676 "either we already got one, "
1677 "or __itemsize__ != 0");
1678 goto bad_slots;
1679 }
1680 add_weak++;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001681 }
1682 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001683
Guido van Rossumad47da02002-08-12 19:05:44 +00001684 /* Copy slots into yet another tuple, demangling names */
1685 newslots = PyTuple_New(nslots - add_dict - add_weak);
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001686 if (newslots == NULL)
Guido van Rossumad47da02002-08-12 19:05:44 +00001687 goto bad_slots;
1688 for (i = j = 0; i < nslots; i++) {
1689 char *s;
Guido van Rossum8e829202002-08-16 03:47:49 +00001690 char buffer[256];
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001691 tmp = PyTuple_GET_ITEM(slots, i);
Guido van Rossumad47da02002-08-12 19:05:44 +00001692 s = PyString_AS_STRING(tmp);
1693 if ((add_dict && strcmp(s, "__dict__") == 0) ||
1694 (add_weak && strcmp(s, "__weakref__") == 0))
1695 continue;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001696 if (_Py_Mangle(PyString_AS_STRING(name),
Guido van Rossumad47da02002-08-12 19:05:44 +00001697 PyString_AS_STRING(tmp),
1698 buffer, sizeof(buffer)))
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001699 {
1700 tmp = PyString_FromString(buffer);
1701 } else {
1702 Py_INCREF(tmp);
1703 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001704 PyTuple_SET_ITEM(newslots, j, tmp);
1705 j++;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001706 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001707 assert(j == nslots - add_dict - add_weak);
1708 nslots = j;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001709 Py_DECREF(slots);
1710 slots = newslots;
1711
Guido van Rossumad47da02002-08-12 19:05:44 +00001712 /* Secondary bases may provide weakrefs or dict */
1713 if (nbases > 1 &&
1714 ((may_add_dict && !add_dict) ||
1715 (may_add_weak && !add_weak))) {
1716 for (i = 0; i < nbases; i++) {
1717 tmp = PyTuple_GET_ITEM(bases, i);
1718 if (tmp == (PyObject *)base)
1719 continue; /* Skip primary base */
1720 if (PyClass_Check(tmp)) {
1721 /* Classic base class provides both */
1722 if (may_add_dict && !add_dict)
1723 add_dict++;
1724 if (may_add_weak && !add_weak)
1725 add_weak++;
1726 break;
1727 }
1728 assert(PyType_Check(tmp));
1729 tmptype = (PyTypeObject *)tmp;
1730 if (may_add_dict && !add_dict &&
1731 tmptype->tp_dictoffset != 0)
1732 add_dict++;
1733 if (may_add_weak && !add_weak &&
1734 tmptype->tp_weaklistoffset != 0)
1735 add_weak++;
1736 if (may_add_dict && !add_dict)
1737 continue;
1738 if (may_add_weak && !add_weak)
1739 continue;
1740 /* Nothing more to check */
1741 break;
1742 }
1743 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001744 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001745
1746 /* XXX From here until type is safely allocated,
1747 "return NULL" may leak slots! */
1748
1749 /* Allocate the type object */
1750 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
Guido van Rossumad47da02002-08-12 19:05:44 +00001751 if (type == NULL) {
1752 Py_XDECREF(slots);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001753 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00001754 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001755
1756 /* Keep name and slots alive in the extended type object */
Guido van Rossume5c691a2003-03-07 15:13:17 +00001757 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001758 Py_INCREF(name);
1759 et->name = name;
1760 et->slots = slots;
1761
Guido van Rossumdc91b992001-08-08 22:26:22 +00001762 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001763 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
1764 Py_TPFLAGS_BASETYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00001765 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
1766 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00001767
1768 /* It's a new-style number unless it specifically inherits any
1769 old-style numeric behavior */
1770 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
1771 (base->tp_as_number == NULL))
1772 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
1773
1774 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001775 type->tp_as_number = &et->as_number;
1776 type->tp_as_sequence = &et->as_sequence;
1777 type->tp_as_mapping = &et->as_mapping;
1778 type->tp_as_buffer = &et->as_buffer;
1779 type->tp_name = PyString_AS_STRING(name);
1780
1781 /* Set tp_base and tp_bases */
1782 type->tp_bases = bases;
1783 Py_INCREF(base);
1784 type->tp_base = base;
1785
Guido van Rossum687ae002001-10-15 22:03:32 +00001786 /* Initialize tp_dict from passed-in dict */
1787 type->tp_dict = dict = PyDict_Copy(dict);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001788 if (dict == NULL) {
1789 Py_DECREF(type);
1790 return NULL;
1791 }
1792
Guido van Rossumc3542212001-08-16 09:18:56 +00001793 /* Set __module__ in the dict */
1794 if (PyDict_GetItemString(dict, "__module__") == NULL) {
1795 tmp = PyEval_GetGlobals();
1796 if (tmp != NULL) {
1797 tmp = PyDict_GetItemString(tmp, "__name__");
1798 if (tmp != NULL) {
1799 if (PyDict_SetItemString(dict, "__module__",
1800 tmp) < 0)
1801 return NULL;
1802 }
1803 }
1804 }
1805
Tim Peters2f93e282001-10-04 05:27:00 +00001806 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
Tim Peters24008312002-03-17 18:56:20 +00001807 and is a string. The __doc__ accessor will first look for tp_doc;
1808 if that fails, it will still look into __dict__.
Tim Peters2f93e282001-10-04 05:27:00 +00001809 */
1810 {
1811 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
1812 if (doc != NULL && PyString_Check(doc)) {
1813 const size_t n = (size_t)PyString_GET_SIZE(doc);
Tim Peters59f809d2001-10-04 05:43:02 +00001814 type->tp_doc = (char *)PyObject_MALLOC(n+1);
Tim Peters2f93e282001-10-04 05:27:00 +00001815 if (type->tp_doc == NULL) {
1816 Py_DECREF(type);
1817 return NULL;
1818 }
1819 memcpy(type->tp_doc, PyString_AS_STRING(doc), n+1);
1820 }
1821 }
1822
Tim Peters6d6c1a32001-08-02 04:15:00 +00001823 /* Special-case __new__: if it's a plain function,
1824 make it a static function */
1825 tmp = PyDict_GetItemString(dict, "__new__");
1826 if (tmp != NULL && PyFunction_Check(tmp)) {
1827 tmp = PyStaticMethod_New(tmp);
1828 if (tmp == NULL) {
1829 Py_DECREF(type);
1830 return NULL;
1831 }
1832 PyDict_SetItemString(dict, "__new__", tmp);
1833 Py_DECREF(tmp);
1834 }
1835
1836 /* Add descriptors for custom slots from __slots__, or for __dict__ */
Guido van Rossume5c691a2003-03-07 15:13:17 +00001837 mp = PyHeapType_GET_MEMBERS(et);
Neil Schemenauerc806c882001-08-29 23:54:54 +00001838 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001839 if (slots != NULL) {
1840 for (i = 0; i < nslots; i++, mp++) {
1841 mp->name = PyString_AS_STRING(
1842 PyTuple_GET_ITEM(slots, i));
Guido van Rossum64b206c2001-12-04 17:13:22 +00001843 mp->type = T_OBJECT_EX;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001844 mp->offset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +00001845 if (base->tp_weaklistoffset == 0 &&
Guido van Rossum64b206c2001-12-04 17:13:22 +00001846 strcmp(mp->name, "__weakref__") == 0) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001847 add_weak++;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001848 mp->type = T_OBJECT;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001849 mp->flags = READONLY;
Guido van Rossum9676b222001-08-17 20:32:36 +00001850 type->tp_weaklistoffset = slotoffset;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001851 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001852 slotoffset += sizeof(PyObject *);
1853 }
1854 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001855 if (add_dict) {
1856 if (base->tp_itemsize)
1857 type->tp_dictoffset = -(long)sizeof(PyObject *);
1858 else
1859 type->tp_dictoffset = slotoffset;
1860 slotoffset += sizeof(PyObject *);
1861 }
1862 if (add_weak) {
1863 assert(!base->tp_itemsize);
1864 type->tp_weaklistoffset = slotoffset;
1865 slotoffset += sizeof(PyObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001866 }
1867 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001868 type->tp_itemsize = base->tp_itemsize;
Guido van Rossume5c691a2003-03-07 15:13:17 +00001869 type->tp_members = PyHeapType_GET_MEMBERS(et);
Guido van Rossum373c7412003-01-07 13:41:37 +00001870
1871 if (type->tp_weaklistoffset && type->tp_dictoffset)
1872 type->tp_getset = subtype_getsets_full;
1873 else if (type->tp_weaklistoffset && !type->tp_dictoffset)
1874 type->tp_getset = subtype_getsets_weakref_only;
1875 else if (!type->tp_weaklistoffset && type->tp_dictoffset)
1876 type->tp_getset = subtype_getsets_dict_only;
1877 else
1878 type->tp_getset = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001879
1880 /* Special case some slots */
1881 if (type->tp_dictoffset != 0 || nslots > 0) {
1882 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
1883 type->tp_getattro = PyObject_GenericGetAttr;
1884 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
1885 type->tp_setattro = PyObject_GenericSetAttr;
1886 }
1887 type->tp_dealloc = subtype_dealloc;
1888
Guido van Rossum9475a232001-10-05 20:51:39 +00001889 /* Enable GC unless there are really no instance variables possible */
1890 if (!(type->tp_basicsize == sizeof(PyObject) &&
1891 type->tp_itemsize == 0))
1892 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
1893
Tim Peters6d6c1a32001-08-02 04:15:00 +00001894 /* Always override allocation strategy to use regular heap */
1895 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00001896 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001897 type->tp_free = PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00001898 type->tp_traverse = subtype_traverse;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001899 type->tp_clear = subtype_clear;
Guido van Rossum048eb752001-10-02 21:24:57 +00001900 }
1901 else
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001902 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001903
1904 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001905 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001906 Py_DECREF(type);
1907 return NULL;
1908 }
1909
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001910 /* Put the proper slots in place */
1911 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00001912
Tim Peters6d6c1a32001-08-02 04:15:00 +00001913 return (PyObject *)type;
1914}
1915
1916/* Internal API to look for a name through the MRO.
1917 This returns a borrowed reference, and doesn't set an exception! */
1918PyObject *
1919_PyType_Lookup(PyTypeObject *type, PyObject *name)
1920{
1921 int i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00001922 PyObject *mro, *res, *base, *dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001923
Guido van Rossum687ae002001-10-15 22:03:32 +00001924 /* Look in tp_dict of types in MRO */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001925 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00001926
1927 /* If mro is NULL, the type is either not yet initialized
1928 by PyType_Ready(), or already cleared by type_clear().
1929 Either way the safest thing to do is to return NULL. */
1930 if (mro == NULL)
1931 return NULL;
1932
Tim Peters6d6c1a32001-08-02 04:15:00 +00001933 assert(PyTuple_Check(mro));
1934 n = PyTuple_GET_SIZE(mro);
1935 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001936 base = PyTuple_GET_ITEM(mro, i);
1937 if (PyClass_Check(base))
1938 dict = ((PyClassObject *)base)->cl_dict;
1939 else {
1940 assert(PyType_Check(base));
1941 dict = ((PyTypeObject *)base)->tp_dict;
1942 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001943 assert(dict && PyDict_Check(dict));
1944 res = PyDict_GetItem(dict, name);
1945 if (res != NULL)
1946 return res;
1947 }
1948 return NULL;
1949}
1950
1951/* This is similar to PyObject_GenericGetAttr(),
1952 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
1953static PyObject *
1954type_getattro(PyTypeObject *type, PyObject *name)
1955{
1956 PyTypeObject *metatype = type->ob_type;
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001957 PyObject *meta_attribute, *attribute;
1958 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001959
1960 /* Initialize this type (we'll assume the metatype is initialized) */
1961 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001962 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001963 return NULL;
1964 }
1965
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001966 /* No readable descriptor found yet */
1967 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00001968
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001969 /* Look for the attribute in the metatype */
1970 meta_attribute = _PyType_Lookup(metatype, name);
1971
1972 if (meta_attribute != NULL) {
1973 meta_get = meta_attribute->ob_type->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00001974
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001975 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
1976 /* Data descriptors implement tp_descr_set to intercept
1977 * writes. Assume the attribute is not overridden in
1978 * type's tp_dict (and bases): call the descriptor now.
1979 */
1980 return meta_get(meta_attribute, (PyObject *)type,
1981 (PyObject *)metatype);
1982 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001983 }
1984
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001985 /* No data descriptor found on metatype. Look in tp_dict of this
1986 * type and its bases */
1987 attribute = _PyType_Lookup(type, name);
1988 if (attribute != NULL) {
1989 /* Implement descriptor functionality, if any */
1990 descrgetfunc local_get = attribute->ob_type->tp_descr_get;
1991 if (local_get != NULL) {
1992 /* NULL 2nd argument indicates the descriptor was
1993 * found on the target object itself (or a base) */
1994 return local_get(attribute, (PyObject *)NULL,
1995 (PyObject *)type);
1996 }
Tim Peters34592512002-07-11 06:23:50 +00001997
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001998 Py_INCREF(attribute);
1999 return attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002000 }
2001
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002002 /* No attribute found in local __dict__ (or bases): use the
2003 * descriptor from the metatype, if any */
2004 if (meta_get != NULL)
2005 return meta_get(meta_attribute, (PyObject *)type,
2006 (PyObject *)metatype);
2007
2008 /* If an ordinary attribute was found on the metatype, return it now */
2009 if (meta_attribute != NULL) {
2010 Py_INCREF(meta_attribute);
2011 return meta_attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002012 }
2013
2014 /* Give up */
2015 PyErr_Format(PyExc_AttributeError,
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002016 "type object '%.50s' has no attribute '%.400s'",
2017 type->tp_name, PyString_AS_STRING(name));
Tim Peters6d6c1a32001-08-02 04:15:00 +00002018 return NULL;
2019}
2020
2021static int
2022type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
2023{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002024 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2025 PyErr_Format(
2026 PyExc_TypeError,
2027 "can't set attributes of built-in/extension type '%s'",
2028 type->tp_name);
2029 return -1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002030 }
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002031 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
2032 return -1;
2033 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002034}
2035
2036static void
2037type_dealloc(PyTypeObject *type)
2038{
Guido van Rossume5c691a2003-03-07 15:13:17 +00002039 PyHeapTypeObject *et;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002040
2041 /* Assert this is a heap-allocated type object */
2042 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002043 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00002044 PyObject_ClearWeakRefs((PyObject *)type);
Guido van Rossume5c691a2003-03-07 15:13:17 +00002045 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002046 Py_XDECREF(type->tp_base);
2047 Py_XDECREF(type->tp_dict);
2048 Py_XDECREF(type->tp_bases);
2049 Py_XDECREF(type->tp_mro);
Guido van Rossum687ae002001-10-15 22:03:32 +00002050 Py_XDECREF(type->tp_cache);
Guido van Rossum1c450732001-10-08 15:18:27 +00002051 Py_XDECREF(type->tp_subclasses);
Neal Norwitzcee5ca02002-07-30 00:42:06 +00002052 PyObject_Free(type->tp_doc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002053 Py_XDECREF(et->name);
2054 Py_XDECREF(et->slots);
2055 type->ob_type->tp_free((PyObject *)type);
2056}
2057
Guido van Rossum1c450732001-10-08 15:18:27 +00002058static PyObject *
2059type_subclasses(PyTypeObject *type, PyObject *args_ignored)
2060{
2061 PyObject *list, *raw, *ref;
2062 int i, n;
2063
2064 list = PyList_New(0);
2065 if (list == NULL)
2066 return NULL;
2067 raw = type->tp_subclasses;
2068 if (raw == NULL)
2069 return list;
2070 assert(PyList_Check(raw));
2071 n = PyList_GET_SIZE(raw);
2072 for (i = 0; i < n; i++) {
2073 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00002074 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00002075 ref = PyWeakref_GET_OBJECT(ref);
2076 if (ref != Py_None) {
2077 if (PyList_Append(list, ref) < 0) {
2078 Py_DECREF(list);
2079 return NULL;
2080 }
2081 }
2082 }
2083 return list;
2084}
2085
Tim Peters6d6c1a32001-08-02 04:15:00 +00002086static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002087 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002088 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
Guido van Rossum1c450732001-10-08 15:18:27 +00002089 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002090 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002091 {0}
2092};
2093
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002094PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002095"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002096"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002097
Guido van Rossum048eb752001-10-02 21:24:57 +00002098static int
2099type_traverse(PyTypeObject *type, visitproc visit, void *arg)
2100{
Guido van Rossum048eb752001-10-02 21:24:57 +00002101 int err;
2102
Guido van Rossuma3862092002-06-10 15:24:42 +00002103 /* Because of type_is_gc(), the collector only calls this
2104 for heaptypes. */
2105 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002106
2107#define VISIT(SLOT) \
2108 if (SLOT) { \
2109 err = visit((PyObject *)(SLOT), arg); \
2110 if (err) \
2111 return err; \
2112 }
2113
2114 VISIT(type->tp_dict);
Guido van Rossum687ae002001-10-15 22:03:32 +00002115 VISIT(type->tp_cache);
Guido van Rossum048eb752001-10-02 21:24:57 +00002116 VISIT(type->tp_mro);
2117 VISIT(type->tp_bases);
2118 VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00002119
2120 /* There's no need to visit type->tp_subclasses or
Guido van Rossume5c691a2003-03-07 15:13:17 +00002121 ((PyHeapTypeObject *)type)->slots, because they can't be involved
Guido van Rossuma3862092002-06-10 15:24:42 +00002122 in cycles; tp_subclasses is a list of weak references,
2123 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00002124
2125#undef VISIT
2126
2127 return 0;
2128}
2129
2130static int
2131type_clear(PyTypeObject *type)
2132{
Guido van Rossum048eb752001-10-02 21:24:57 +00002133 PyObject *tmp;
2134
Guido van Rossuma3862092002-06-10 15:24:42 +00002135 /* Because of type_is_gc(), the collector only calls this
2136 for heaptypes. */
2137 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002138
2139#define CLEAR(SLOT) \
2140 if (SLOT) { \
2141 tmp = (PyObject *)(SLOT); \
2142 SLOT = NULL; \
2143 Py_DECREF(tmp); \
2144 }
2145
Guido van Rossuma3862092002-06-10 15:24:42 +00002146 /* The only field we need to clear is tp_mro, which is part of a
2147 hard cycle (its first element is the class itself) that won't
2148 be broken otherwise (it's a tuple and tuples don't have a
2149 tp_clear handler). None of the other fields need to be
2150 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00002151
Guido van Rossuma3862092002-06-10 15:24:42 +00002152 tp_dict:
2153 It is a dict, so the collector will call its tp_clear.
2154
2155 tp_cache:
2156 Not used; if it were, it would be a dict.
2157
2158 tp_bases, tp_base:
2159 If these are involved in a cycle, there must be at least
2160 one other, mutable object in the cycle, e.g. a base
2161 class's dict; the cycle will be broken that way.
2162
2163 tp_subclasses:
2164 A list of weak references can't be part of a cycle; and
2165 lists have their own tp_clear.
2166
Guido van Rossume5c691a2003-03-07 15:13:17 +00002167 slots (in PyHeapTypeObject):
Guido van Rossuma3862092002-06-10 15:24:42 +00002168 A tuple of strings can't be part of a cycle.
2169 */
2170
2171 CLEAR(type->tp_mro);
Tim Peters2f93e282001-10-04 05:27:00 +00002172
Guido van Rossum048eb752001-10-02 21:24:57 +00002173#undef CLEAR
2174
2175 return 0;
2176}
2177
2178static int
2179type_is_gc(PyTypeObject *type)
2180{
2181 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
2182}
2183
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002184PyTypeObject PyType_Type = {
2185 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002186 0, /* ob_size */
2187 "type", /* tp_name */
Guido van Rossume5c691a2003-03-07 15:13:17 +00002188 sizeof(PyHeapTypeObject), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00002189 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002190 (destructor)type_dealloc, /* tp_dealloc */
2191 0, /* tp_print */
2192 0, /* tp_getattr */
2193 0, /* tp_setattr */
2194 type_compare, /* tp_compare */
2195 (reprfunc)type_repr, /* tp_repr */
2196 0, /* tp_as_number */
2197 0, /* tp_as_sequence */
2198 0, /* tp_as_mapping */
2199 (hashfunc)_Py_HashPointer, /* tp_hash */
2200 (ternaryfunc)type_call, /* tp_call */
2201 0, /* tp_str */
2202 (getattrofunc)type_getattro, /* tp_getattro */
2203 (setattrofunc)type_setattro, /* tp_setattro */
2204 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00002205 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2206 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002207 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00002208 (traverseproc)type_traverse, /* tp_traverse */
2209 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002210 0, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00002211 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002212 0, /* tp_iter */
2213 0, /* tp_iternext */
2214 type_methods, /* tp_methods */
2215 type_members, /* tp_members */
2216 type_getsets, /* tp_getset */
2217 0, /* tp_base */
2218 0, /* tp_dict */
2219 0, /* tp_descr_get */
2220 0, /* tp_descr_set */
2221 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
2222 0, /* tp_init */
2223 0, /* tp_alloc */
2224 type_new, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002225 PyObject_GC_Del, /* tp_free */
Guido van Rossum048eb752001-10-02 21:24:57 +00002226 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002227};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002228
2229
2230/* The base type of all types (eventually)... except itself. */
2231
2232static int
2233object_init(PyObject *self, PyObject *args, PyObject *kwds)
2234{
2235 return 0;
2236}
2237
Guido van Rossum298e4212003-02-13 16:30:16 +00002238/* If we don't have a tp_new for a new-style class, new will use this one.
2239 Therefore this should take no arguments/keywords. However, this new may
2240 also be inherited by objects that define a tp_init but no tp_new. These
2241 objects WILL pass argumets to tp_new, because it gets the same args as
2242 tp_init. So only allow arguments if we aren't using the default init, in
2243 which case we expect init to handle argument parsing. */
2244static PyObject *
2245object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2246{
2247 if (type->tp_init == object_init && (PyTuple_GET_SIZE(args) ||
2248 (kwds && PyDict_Check(kwds) && PyDict_Size(kwds)))) {
2249 PyErr_SetString(PyExc_TypeError,
2250 "default __new__ takes no parameters");
2251 return NULL;
2252 }
2253 return type->tp_alloc(type, 0);
2254}
2255
Tim Peters6d6c1a32001-08-02 04:15:00 +00002256static void
2257object_dealloc(PyObject *self)
2258{
2259 self->ob_type->tp_free(self);
2260}
2261
Guido van Rossum8e248182001-08-12 05:17:56 +00002262static PyObject *
2263object_repr(PyObject *self)
2264{
Guido van Rossum76e69632001-08-16 18:52:43 +00002265 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00002266 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002267
Guido van Rossum76e69632001-08-16 18:52:43 +00002268 type = self->ob_type;
2269 mod = type_module(type, NULL);
2270 if (mod == NULL)
2271 PyErr_Clear();
2272 else if (!PyString_Check(mod)) {
2273 Py_DECREF(mod);
2274 mod = NULL;
2275 }
2276 name = type_name(type, NULL);
2277 if (name == NULL)
2278 return NULL;
2279 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002280 rtn = PyString_FromFormat("<%s.%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002281 PyString_AS_STRING(mod),
2282 PyString_AS_STRING(name),
2283 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002284 else
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002285 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002286 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002287 Py_XDECREF(mod);
2288 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00002289 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002290}
2291
Guido van Rossumb8f63662001-08-15 23:57:02 +00002292static PyObject *
2293object_str(PyObject *self)
2294{
2295 unaryfunc f;
2296
2297 f = self->ob_type->tp_repr;
2298 if (f == NULL)
2299 f = object_repr;
2300 return f(self);
2301}
2302
Guido van Rossum8e248182001-08-12 05:17:56 +00002303static long
2304object_hash(PyObject *self)
2305{
2306 return _Py_HashPointer(self);
2307}
Guido van Rossum8e248182001-08-12 05:17:56 +00002308
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002309static PyObject *
2310object_get_class(PyObject *self, void *closure)
2311{
2312 Py_INCREF(self->ob_type);
2313 return (PyObject *)(self->ob_type);
2314}
2315
2316static int
2317equiv_structs(PyTypeObject *a, PyTypeObject *b)
2318{
2319 return a == b ||
2320 (a != NULL &&
2321 b != NULL &&
2322 a->tp_basicsize == b->tp_basicsize &&
2323 a->tp_itemsize == b->tp_itemsize &&
2324 a->tp_dictoffset == b->tp_dictoffset &&
2325 a->tp_weaklistoffset == b->tp_weaklistoffset &&
2326 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
2327 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
2328}
2329
2330static int
2331same_slots_added(PyTypeObject *a, PyTypeObject *b)
2332{
2333 PyTypeObject *base = a->tp_base;
2334 int size;
2335
2336 if (base != b->tp_base)
2337 return 0;
2338 if (equiv_structs(a, base) && equiv_structs(b, base))
2339 return 1;
2340 size = base->tp_basicsize;
2341 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
2342 size += sizeof(PyObject *);
2343 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
2344 size += sizeof(PyObject *);
2345 return size == a->tp_basicsize && size == b->tp_basicsize;
2346}
2347
2348static int
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002349compatible_for_assignment(PyTypeObject* old, PyTypeObject* new, char* attr)
2350{
2351 PyTypeObject *newbase, *oldbase;
2352
2353 if (new->tp_dealloc != old->tp_dealloc ||
2354 new->tp_free != old->tp_free)
2355 {
2356 PyErr_Format(PyExc_TypeError,
2357 "%s assignment: "
2358 "'%s' deallocator differs from '%s'",
2359 attr,
2360 new->tp_name,
2361 old->tp_name);
2362 return 0;
2363 }
2364 newbase = new;
2365 oldbase = old;
2366 while (equiv_structs(newbase, newbase->tp_base))
2367 newbase = newbase->tp_base;
2368 while (equiv_structs(oldbase, oldbase->tp_base))
2369 oldbase = oldbase->tp_base;
2370 if (newbase != oldbase &&
2371 (newbase->tp_base != oldbase->tp_base ||
2372 !same_slots_added(newbase, oldbase))) {
2373 PyErr_Format(PyExc_TypeError,
2374 "%s assignment: "
2375 "'%s' object layout differs from '%s'",
2376 attr,
2377 new->tp_name,
2378 old->tp_name);
2379 return 0;
2380 }
Tim Petersea7f75d2002-12-07 21:39:16 +00002381
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002382 return 1;
2383}
2384
2385static int
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002386object_set_class(PyObject *self, PyObject *value, void *closure)
2387{
2388 PyTypeObject *old = self->ob_type;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002389 PyTypeObject *new;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002390
Guido van Rossumb6b89422002-04-15 01:03:30 +00002391 if (value == NULL) {
2392 PyErr_SetString(PyExc_TypeError,
2393 "can't delete __class__ attribute");
2394 return -1;
2395 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002396 if (!PyType_Check(value)) {
2397 PyErr_Format(PyExc_TypeError,
2398 "__class__ must be set to new-style class, not '%s' object",
2399 value->ob_type->tp_name);
2400 return -1;
2401 }
2402 new = (PyTypeObject *)value;
Guido van Rossum40af8892002-08-10 05:42:07 +00002403 if (!(new->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
2404 !(old->tp_flags & Py_TPFLAGS_HEAPTYPE))
2405 {
2406 PyErr_Format(PyExc_TypeError,
2407 "__class__ assignment: only for heap types");
2408 return -1;
2409 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002410 if (compatible_for_assignment(new, old, "__class__")) {
2411 Py_INCREF(new);
2412 self->ob_type = new;
2413 Py_DECREF(old);
2414 return 0;
2415 }
2416 else {
Guido van Rossum9ee4b942002-05-24 18:47:47 +00002417 return -1;
2418 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002419}
2420
2421static PyGetSetDef object_getsets[] = {
2422 {"__class__", object_get_class, object_set_class,
Neal Norwitz858e34f2002-08-13 17:18:45 +00002423 PyDoc_STR("the object's class")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002424 {0}
2425};
2426
Guido van Rossumc53f0092003-02-18 22:05:12 +00002427
Guido van Rossum036f9992003-02-21 22:02:54 +00002428/* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
2429 We fall back to helpers in copy_reg for:
2430 - pickle protocols < 2
2431 - calculating the list of slot names (done only once per class)
2432 - the __newobj__ function (which is used as a token but never called)
2433*/
2434
2435static PyObject *
2436import_copy_reg(void)
2437{
2438 static PyObject *copy_reg_str;
Guido van Rossum3926a632001-09-25 16:25:58 +00002439
2440 if (!copy_reg_str) {
2441 copy_reg_str = PyString_InternFromString("copy_reg");
2442 if (copy_reg_str == NULL)
2443 return NULL;
2444 }
Guido van Rossum036f9992003-02-21 22:02:54 +00002445
2446 return PyImport_Import(copy_reg_str);
2447}
2448
2449static PyObject *
2450slotnames(PyObject *cls)
2451{
2452 PyObject *clsdict;
2453 PyObject *copy_reg;
2454 PyObject *slotnames;
2455
2456 if (!PyType_Check(cls)) {
2457 Py_INCREF(Py_None);
2458 return Py_None;
2459 }
2460
2461 clsdict = ((PyTypeObject *)cls)->tp_dict;
2462 slotnames = PyDict_GetItemString(clsdict, "__slotnames__");
2463 if (slotnames != NULL) {
2464 Py_INCREF(slotnames);
2465 return slotnames;
2466 }
2467
2468 copy_reg = import_copy_reg();
2469 if (copy_reg == NULL)
2470 return NULL;
2471
2472 slotnames = PyObject_CallMethod(copy_reg, "_slotnames", "O", cls);
2473 Py_DECREF(copy_reg);
2474 if (slotnames != NULL &&
2475 slotnames != Py_None &&
2476 !PyList_Check(slotnames))
2477 {
2478 PyErr_SetString(PyExc_TypeError,
2479 "copy_reg._slotnames didn't return a list or None");
2480 Py_DECREF(slotnames);
2481 slotnames = NULL;
2482 }
2483
2484 return slotnames;
2485}
2486
2487static PyObject *
2488reduce_2(PyObject *obj)
2489{
2490 PyObject *cls, *getnewargs;
2491 PyObject *args = NULL, *args2 = NULL;
2492 PyObject *getstate = NULL, *state = NULL, *names = NULL;
2493 PyObject *slots = NULL, *listitems = NULL, *dictitems = NULL;
2494 PyObject *copy_reg = NULL, *newobj = NULL, *res = NULL;
2495 int i, n;
2496
2497 cls = PyObject_GetAttrString(obj, "__class__");
2498 if (cls == NULL)
2499 return NULL;
2500
2501 getnewargs = PyObject_GetAttrString(obj, "__getnewargs__");
2502 if (getnewargs != NULL) {
2503 args = PyObject_CallObject(getnewargs, NULL);
2504 Py_DECREF(getnewargs);
2505 if (args != NULL && !PyTuple_Check(args)) {
2506 PyErr_SetString(PyExc_TypeError,
2507 "__getnewargs__ should return a tuple");
2508 goto end;
2509 }
2510 }
2511 else {
2512 PyErr_Clear();
2513 args = PyTuple_New(0);
2514 }
2515 if (args == NULL)
2516 goto end;
2517
2518 getstate = PyObject_GetAttrString(obj, "__getstate__");
2519 if (getstate != NULL) {
2520 state = PyObject_CallObject(getstate, NULL);
2521 Py_DECREF(getstate);
2522 }
2523 else {
2524 state = PyObject_GetAttrString(obj, "__dict__");
2525 if (state == NULL) {
2526 PyErr_Clear();
2527 state = Py_None;
2528 Py_INCREF(state);
2529 }
2530 names = slotnames(cls);
2531 if (names == NULL)
2532 goto end;
2533 if (names != Py_None) {
2534 assert(PyList_Check(names));
2535 slots = PyDict_New();
2536 if (slots == NULL)
2537 goto end;
2538 n = 0;
2539 /* Can't pre-compute the list size; the list
2540 is stored on the class so accessible to other
2541 threads, which may be run by DECREF */
2542 for (i = 0; i < PyList_GET_SIZE(names); i++) {
2543 PyObject *name, *value;
2544 name = PyList_GET_ITEM(names, i);
2545 value = PyObject_GetAttr(obj, name);
2546 if (value == NULL)
2547 PyErr_Clear();
2548 else {
2549 int err = PyDict_SetItem(slots, name,
2550 value);
2551 Py_DECREF(value);
2552 if (err)
2553 goto end;
2554 n++;
2555 }
2556 }
2557 if (n) {
2558 state = Py_BuildValue("(NO)", state, slots);
2559 if (state == NULL)
2560 goto end;
2561 }
2562 }
2563 }
2564
2565 if (!PyList_Check(obj)) {
2566 listitems = Py_None;
2567 Py_INCREF(listitems);
2568 }
2569 else {
2570 listitems = PyObject_GetIter(obj);
2571 if (listitems == NULL)
2572 goto end;
2573 }
2574
2575 if (!PyDict_Check(obj)) {
2576 dictitems = Py_None;
2577 Py_INCREF(dictitems);
2578 }
2579 else {
2580 dictitems = PyObject_CallMethod(obj, "iteritems", "");
2581 if (dictitems == NULL)
2582 goto end;
2583 }
2584
2585 copy_reg = import_copy_reg();
2586 if (copy_reg == NULL)
2587 goto end;
2588 newobj = PyObject_GetAttrString(copy_reg, "__newobj__");
2589 if (newobj == NULL)
2590 goto end;
2591
2592 n = PyTuple_GET_SIZE(args);
2593 args2 = PyTuple_New(n+1);
2594 if (args2 == NULL)
2595 goto end;
2596 PyTuple_SET_ITEM(args2, 0, cls);
2597 cls = NULL;
2598 for (i = 0; i < n; i++) {
2599 PyObject *v = PyTuple_GET_ITEM(args, i);
2600 Py_INCREF(v);
2601 PyTuple_SET_ITEM(args2, i+1, v);
2602 }
2603
2604 res = Py_BuildValue("(OOOOO)",
2605 newobj, args2, state, listitems, dictitems);
2606
2607 end:
2608 Py_XDECREF(cls);
2609 Py_XDECREF(args);
2610 Py_XDECREF(args2);
2611 Py_XDECREF(state);
2612 Py_XDECREF(names);
2613 Py_XDECREF(listitems);
2614 Py_XDECREF(dictitems);
2615 Py_XDECREF(copy_reg);
2616 Py_XDECREF(newobj);
2617 return res;
2618}
2619
2620static PyObject *
2621object_reduce_ex(PyObject *self, PyObject *args)
2622{
2623 /* Call copy_reg._reduce_ex(self, proto) */
2624 PyObject *reduce, *copy_reg, *res;
2625 int proto = 0;
2626
2627 if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
2628 return NULL;
2629
2630 reduce = PyObject_GetAttrString(self, "__reduce__");
2631 if (reduce == NULL)
2632 PyErr_Clear();
2633 else {
2634 PyObject *cls, *clsreduce, *objreduce;
2635 int override;
2636 cls = PyObject_GetAttrString(self, "__class__");
2637 if (cls == NULL) {
2638 Py_DECREF(reduce);
2639 return NULL;
2640 }
2641 clsreduce = PyObject_GetAttrString(cls, "__reduce__");
2642 Py_DECREF(cls);
2643 if (clsreduce == NULL) {
2644 Py_DECREF(reduce);
2645 return NULL;
2646 }
2647 objreduce = PyDict_GetItemString(PyBaseObject_Type.tp_dict,
2648 "__reduce__");
2649 override = (clsreduce != objreduce);
2650 Py_DECREF(clsreduce);
2651 if (override) {
2652 res = PyObject_CallObject(reduce, NULL);
2653 Py_DECREF(reduce);
2654 return res;
2655 }
2656 else
2657 Py_DECREF(reduce);
2658 }
2659
2660 if (proto >= 2)
2661 return reduce_2(self);
2662
2663 copy_reg = import_copy_reg();
Guido van Rossum3926a632001-09-25 16:25:58 +00002664 if (!copy_reg)
2665 return NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00002666
Guido van Rossumc53f0092003-02-18 22:05:12 +00002667 res = PyEval_CallMethod(copy_reg, "_reduce_ex", "(Oi)", self, proto);
Guido van Rossum3926a632001-09-25 16:25:58 +00002668 Py_DECREF(copy_reg);
Guido van Rossum036f9992003-02-21 22:02:54 +00002669
Guido van Rossum3926a632001-09-25 16:25:58 +00002670 return res;
2671}
2672
2673static PyMethodDef object_methods[] = {
Guido van Rossumc53f0092003-02-18 22:05:12 +00002674 {"__reduce_ex__", object_reduce_ex, METH_VARARGS,
2675 PyDoc_STR("helper for pickle")},
2676 {"__reduce__", object_reduce_ex, METH_VARARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002677 PyDoc_STR("helper for pickle")},
Guido van Rossum3926a632001-09-25 16:25:58 +00002678 {0}
2679};
2680
Guido van Rossum036f9992003-02-21 22:02:54 +00002681
Tim Peters6d6c1a32001-08-02 04:15:00 +00002682PyTypeObject PyBaseObject_Type = {
2683 PyObject_HEAD_INIT(&PyType_Type)
2684 0, /* ob_size */
2685 "object", /* tp_name */
2686 sizeof(PyObject), /* tp_basicsize */
2687 0, /* tp_itemsize */
2688 (destructor)object_dealloc, /* tp_dealloc */
2689 0, /* tp_print */
2690 0, /* tp_getattr */
2691 0, /* tp_setattr */
2692 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002693 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002694 0, /* tp_as_number */
2695 0, /* tp_as_sequence */
2696 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002697 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002698 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002699 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002700 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002701 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002702 0, /* tp_as_buffer */
2703 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002704 PyDoc_STR("The most base type"), /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002705 0, /* tp_traverse */
2706 0, /* tp_clear */
2707 0, /* tp_richcompare */
2708 0, /* tp_weaklistoffset */
2709 0, /* tp_iter */
2710 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00002711 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002712 0, /* tp_members */
2713 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002714 0, /* tp_base */
2715 0, /* tp_dict */
2716 0, /* tp_descr_get */
2717 0, /* tp_descr_set */
2718 0, /* tp_dictoffset */
2719 object_init, /* tp_init */
2720 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossum298e4212003-02-13 16:30:16 +00002721 object_new, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002722 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002723};
2724
2725
2726/* Initialize the __dict__ in a type object */
2727
2728static int
2729add_methods(PyTypeObject *type, PyMethodDef *meth)
2730{
Guido van Rossum687ae002001-10-15 22:03:32 +00002731 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002732
2733 for (; meth->ml_name != NULL; meth++) {
2734 PyObject *descr;
2735 if (PyDict_GetItemString(dict, meth->ml_name))
2736 continue;
Fred Drake7bf97152002-03-28 05:33:33 +00002737 if (meth->ml_flags & METH_CLASS) {
2738 if (meth->ml_flags & METH_STATIC) {
2739 PyErr_SetString(PyExc_ValueError,
2740 "method cannot be both class and static");
2741 return -1;
2742 }
Tim Petersbca1cbc2002-12-09 22:56:13 +00002743 descr = PyDescr_NewClassMethod(type, meth);
Fred Drake7bf97152002-03-28 05:33:33 +00002744 }
2745 else if (meth->ml_flags & METH_STATIC) {
Guido van Rossum9af48ff2003-02-11 17:12:46 +00002746 PyObject *cfunc = PyCFunction_New(meth, NULL);
2747 if (cfunc == NULL)
2748 return -1;
2749 descr = PyStaticMethod_New(cfunc);
2750 Py_DECREF(cfunc);
Fred Drake7bf97152002-03-28 05:33:33 +00002751 }
2752 else {
2753 descr = PyDescr_NewMethod(type, meth);
2754 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002755 if (descr == NULL)
2756 return -1;
Fred Drake7bf97152002-03-28 05:33:33 +00002757 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002758 return -1;
2759 Py_DECREF(descr);
2760 }
2761 return 0;
2762}
2763
2764static int
Guido van Rossum6f799372001-09-20 20:46:19 +00002765add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002766{
Guido van Rossum687ae002001-10-15 22:03:32 +00002767 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002768
2769 for (; memb->name != NULL; memb++) {
2770 PyObject *descr;
2771 if (PyDict_GetItemString(dict, memb->name))
2772 continue;
2773 descr = PyDescr_NewMember(type, memb);
2774 if (descr == NULL)
2775 return -1;
2776 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
2777 return -1;
2778 Py_DECREF(descr);
2779 }
2780 return 0;
2781}
2782
2783static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00002784add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002785{
Guido van Rossum687ae002001-10-15 22:03:32 +00002786 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002787
2788 for (; gsp->name != NULL; gsp++) {
2789 PyObject *descr;
2790 if (PyDict_GetItemString(dict, gsp->name))
2791 continue;
2792 descr = PyDescr_NewGetSet(type, gsp);
2793
2794 if (descr == NULL)
2795 return -1;
2796 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
2797 return -1;
2798 Py_DECREF(descr);
2799 }
2800 return 0;
2801}
2802
Guido van Rossum13d52f02001-08-10 21:24:08 +00002803static void
2804inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002805{
2806 int oldsize, newsize;
2807
Guido van Rossum13d52f02001-08-10 21:24:08 +00002808 /* Special flag magic */
2809 if (!type->tp_as_buffer && base->tp_as_buffer) {
2810 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
2811 type->tp_flags |=
2812 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
2813 }
2814 if (!type->tp_as_sequence && base->tp_as_sequence) {
2815 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
2816 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
2817 }
2818 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
2819 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
2820 if ((!type->tp_as_number && base->tp_as_number) ||
2821 (!type->tp_as_sequence && base->tp_as_sequence)) {
2822 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
2823 if (!type->tp_as_number && !type->tp_as_sequence) {
2824 type->tp_flags |= base->tp_flags &
2825 Py_TPFLAGS_HAVE_INPLACEOPS;
2826 }
2827 }
2828 /* Wow */
2829 }
2830 if (!type->tp_as_number && base->tp_as_number) {
2831 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
2832 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
2833 }
2834
2835 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00002836 oldsize = base->tp_basicsize;
2837 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
2838 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
2839 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00002840 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
2841 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00002842 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00002843 if (type->tp_traverse == NULL)
2844 type->tp_traverse = base->tp_traverse;
2845 if (type->tp_clear == NULL)
2846 type->tp_clear = base->tp_clear;
2847 }
2848 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
Guido van Rossumf884b742001-12-17 17:14:22 +00002849 /* The condition below could use some explanation.
2850 It appears that tp_new is not inherited for static types
2851 whose base class is 'object'; this seems to be a precaution
2852 so that old extension types don't suddenly become
2853 callable (object.__new__ wouldn't insure the invariants
2854 that the extension type's own factory function ensures).
2855 Heap types, of course, are under our control, so they do
2856 inherit tp_new; static extension types that specify some
2857 other built-in type as the default are considered
2858 new-style-aware so they also inherit object.__new__. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002859 if (base != &PyBaseObject_Type ||
2860 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2861 if (type->tp_new == NULL)
2862 type->tp_new = base->tp_new;
2863 }
2864 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00002865 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00002866
2867 /* Copy other non-function slots */
2868
2869#undef COPYVAL
2870#define COPYVAL(SLOT) \
2871 if (type->SLOT == 0) type->SLOT = base->SLOT
2872
2873 COPYVAL(tp_itemsize);
2874 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
2875 COPYVAL(tp_weaklistoffset);
2876 }
2877 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2878 COPYVAL(tp_dictoffset);
2879 }
Guido van Rossum13d52f02001-08-10 21:24:08 +00002880}
2881
2882static void
2883inherit_slots(PyTypeObject *type, PyTypeObject *base)
2884{
2885 PyTypeObject *basebase;
2886
2887#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00002888#undef COPYSLOT
2889#undef COPYNUM
2890#undef COPYSEQ
2891#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00002892#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00002893
2894#define SLOTDEFINED(SLOT) \
2895 (base->SLOT != 0 && \
2896 (basebase == NULL || base->SLOT != basebase->SLOT))
2897
Tim Peters6d6c1a32001-08-02 04:15:00 +00002898#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00002899 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00002900
2901#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
2902#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
2903#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00002904#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002905
Guido van Rossum13d52f02001-08-10 21:24:08 +00002906 /* This won't inherit indirect slots (from tp_as_number etc.)
2907 if type doesn't provide the space. */
2908
2909 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
2910 basebase = base->tp_base;
2911 if (basebase->tp_as_number == NULL)
2912 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002913 COPYNUM(nb_add);
2914 COPYNUM(nb_subtract);
2915 COPYNUM(nb_multiply);
2916 COPYNUM(nb_divide);
2917 COPYNUM(nb_remainder);
2918 COPYNUM(nb_divmod);
2919 COPYNUM(nb_power);
2920 COPYNUM(nb_negative);
2921 COPYNUM(nb_positive);
2922 COPYNUM(nb_absolute);
2923 COPYNUM(nb_nonzero);
2924 COPYNUM(nb_invert);
2925 COPYNUM(nb_lshift);
2926 COPYNUM(nb_rshift);
2927 COPYNUM(nb_and);
2928 COPYNUM(nb_xor);
2929 COPYNUM(nb_or);
2930 COPYNUM(nb_coerce);
2931 COPYNUM(nb_int);
2932 COPYNUM(nb_long);
2933 COPYNUM(nb_float);
2934 COPYNUM(nb_oct);
2935 COPYNUM(nb_hex);
2936 COPYNUM(nb_inplace_add);
2937 COPYNUM(nb_inplace_subtract);
2938 COPYNUM(nb_inplace_multiply);
2939 COPYNUM(nb_inplace_divide);
2940 COPYNUM(nb_inplace_remainder);
2941 COPYNUM(nb_inplace_power);
2942 COPYNUM(nb_inplace_lshift);
2943 COPYNUM(nb_inplace_rshift);
2944 COPYNUM(nb_inplace_and);
2945 COPYNUM(nb_inplace_xor);
2946 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00002947 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
2948 COPYNUM(nb_true_divide);
2949 COPYNUM(nb_floor_divide);
2950 COPYNUM(nb_inplace_true_divide);
2951 COPYNUM(nb_inplace_floor_divide);
2952 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002953 }
2954
Guido van Rossum13d52f02001-08-10 21:24:08 +00002955 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
2956 basebase = base->tp_base;
2957 if (basebase->tp_as_sequence == NULL)
2958 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002959 COPYSEQ(sq_length);
2960 COPYSEQ(sq_concat);
2961 COPYSEQ(sq_repeat);
2962 COPYSEQ(sq_item);
2963 COPYSEQ(sq_slice);
2964 COPYSEQ(sq_ass_item);
2965 COPYSEQ(sq_ass_slice);
2966 COPYSEQ(sq_contains);
2967 COPYSEQ(sq_inplace_concat);
2968 COPYSEQ(sq_inplace_repeat);
2969 }
2970
Guido van Rossum13d52f02001-08-10 21:24:08 +00002971 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
2972 basebase = base->tp_base;
2973 if (basebase->tp_as_mapping == NULL)
2974 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002975 COPYMAP(mp_length);
2976 COPYMAP(mp_subscript);
2977 COPYMAP(mp_ass_subscript);
2978 }
2979
Tim Petersfc57ccb2001-10-12 02:38:24 +00002980 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
2981 basebase = base->tp_base;
2982 if (basebase->tp_as_buffer == NULL)
2983 basebase = NULL;
2984 COPYBUF(bf_getreadbuffer);
2985 COPYBUF(bf_getwritebuffer);
2986 COPYBUF(bf_getsegcount);
2987 COPYBUF(bf_getcharbuffer);
2988 }
2989
Guido van Rossum13d52f02001-08-10 21:24:08 +00002990 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002991
Tim Peters6d6c1a32001-08-02 04:15:00 +00002992 COPYSLOT(tp_dealloc);
2993 COPYSLOT(tp_print);
2994 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
2995 type->tp_getattr = base->tp_getattr;
2996 type->tp_getattro = base->tp_getattro;
2997 }
2998 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
2999 type->tp_setattr = base->tp_setattr;
3000 type->tp_setattro = base->tp_setattro;
3001 }
3002 /* tp_compare see tp_richcompare */
3003 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003004 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003005 COPYSLOT(tp_call);
3006 COPYSLOT(tp_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003007 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003008 if (type->tp_compare == NULL &&
3009 type->tp_richcompare == NULL &&
3010 type->tp_hash == NULL)
3011 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003012 type->tp_compare = base->tp_compare;
3013 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003014 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003015 }
3016 }
3017 else {
3018 COPYSLOT(tp_compare);
3019 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003020 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
3021 COPYSLOT(tp_iter);
3022 COPYSLOT(tp_iternext);
3023 }
3024 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
3025 COPYSLOT(tp_descr_get);
3026 COPYSLOT(tp_descr_set);
3027 COPYSLOT(tp_dictoffset);
3028 COPYSLOT(tp_init);
3029 COPYSLOT(tp_alloc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003030 COPYSLOT(tp_free);
Guido van Rossumcc8fe042002-04-05 17:10:16 +00003031 COPYSLOT(tp_is_gc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003032 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003033}
3034
Jeremy Hylton938ace62002-07-17 16:30:39 +00003035static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00003036
Tim Peters6d6c1a32001-08-02 04:15:00 +00003037int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00003038PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003039{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003040 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003041 PyTypeObject *base;
3042 int i, n;
3043
Guido van Rossumcab05802002-06-10 15:29:03 +00003044 if (type->tp_flags & Py_TPFLAGS_READY) {
3045 assert(type->tp_dict != NULL);
Guido van Rossumd614f972001-08-10 17:39:49 +00003046 return 0;
Guido van Rossumcab05802002-06-10 15:29:03 +00003047 }
Guido van Rossumd614f972001-08-10 17:39:49 +00003048 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00003049
3050 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003051
3052 /* Initialize tp_base (defaults to BaseObject unless that's us) */
3053 base = type->tp_base;
3054 if (base == NULL && type != &PyBaseObject_Type)
3055 base = type->tp_base = &PyBaseObject_Type;
3056
Guido van Rossum323a9cf2002-08-14 17:26:30 +00003057 /* Initialize the base class */
3058 if (base && base->tp_dict == NULL) {
3059 if (PyType_Ready(base) < 0)
3060 goto error;
3061 }
3062
Guido van Rossum0986d822002-04-08 01:38:42 +00003063 /* Initialize ob_type if NULL. This means extensions that want to be
3064 compilable separately on Windows can call PyType_Ready() instead of
3065 initializing the ob_type field of their type objects. */
3066 if (type->ob_type == NULL)
3067 type->ob_type = base->ob_type;
3068
Tim Peters6d6c1a32001-08-02 04:15:00 +00003069 /* Initialize tp_bases */
3070 bases = type->tp_bases;
3071 if (bases == NULL) {
3072 if (base == NULL)
3073 bases = PyTuple_New(0);
3074 else
3075 bases = Py_BuildValue("(O)", base);
3076 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003077 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003078 type->tp_bases = bases;
3079 }
3080
Guido van Rossum687ae002001-10-15 22:03:32 +00003081 /* Initialize tp_dict */
3082 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003083 if (dict == NULL) {
3084 dict = PyDict_New();
3085 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003086 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00003087 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003088 }
3089
Guido van Rossum687ae002001-10-15 22:03:32 +00003090 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003091 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003092 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003093 if (type->tp_methods != NULL) {
3094 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003095 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003096 }
3097 if (type->tp_members != NULL) {
3098 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003099 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003100 }
3101 if (type->tp_getset != NULL) {
3102 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003103 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003104 }
3105
Tim Peters6d6c1a32001-08-02 04:15:00 +00003106 /* Calculate method resolution order */
3107 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00003108 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003109 }
3110
Guido van Rossum13d52f02001-08-10 21:24:08 +00003111 /* Inherit special flags from dominant base */
3112 if (type->tp_base != NULL)
3113 inherit_special(type, type->tp_base);
3114
Tim Peters6d6c1a32001-08-02 04:15:00 +00003115 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003116 bases = type->tp_mro;
3117 assert(bases != NULL);
3118 assert(PyTuple_Check(bases));
3119 n = PyTuple_GET_SIZE(bases);
3120 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003121 PyObject *b = PyTuple_GET_ITEM(bases, i);
3122 if (PyType_Check(b))
3123 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003124 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003125
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003126 /* if the type dictionary doesn't contain a __doc__, set it from
3127 the tp_doc slot.
3128 */
3129 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
3130 if (type->tp_doc != NULL) {
3131 PyObject *doc = PyString_FromString(type->tp_doc);
3132 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
3133 Py_DECREF(doc);
3134 } else {
Guido van Rossumd4641072002-04-03 02:13:37 +00003135 PyDict_SetItemString(type->tp_dict,
3136 "__doc__", Py_None);
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003137 }
3138 }
3139
Guido van Rossum13d52f02001-08-10 21:24:08 +00003140 /* Some more special stuff */
3141 base = type->tp_base;
3142 if (base != NULL) {
3143 if (type->tp_as_number == NULL)
3144 type->tp_as_number = base->tp_as_number;
3145 if (type->tp_as_sequence == NULL)
3146 type->tp_as_sequence = base->tp_as_sequence;
3147 if (type->tp_as_mapping == NULL)
3148 type->tp_as_mapping = base->tp_as_mapping;
Guido van Rossumeea47182003-02-11 20:39:59 +00003149 if (type->tp_as_buffer == NULL)
3150 type->tp_as_buffer = base->tp_as_buffer;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003151 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003152
Guido van Rossum1c450732001-10-08 15:18:27 +00003153 /* Link into each base class's list of subclasses */
3154 bases = type->tp_bases;
3155 n = PyTuple_GET_SIZE(bases);
3156 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003157 PyObject *b = PyTuple_GET_ITEM(bases, i);
3158 if (PyType_Check(b) &&
3159 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00003160 goto error;
3161 }
3162
Guido van Rossum13d52f02001-08-10 21:24:08 +00003163 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00003164 assert(type->tp_dict != NULL);
3165 type->tp_flags =
3166 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003167 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00003168
3169 error:
3170 type->tp_flags &= ~Py_TPFLAGS_READYING;
3171 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003172}
3173
Guido van Rossum1c450732001-10-08 15:18:27 +00003174static int
3175add_subclass(PyTypeObject *base, PyTypeObject *type)
3176{
3177 int i;
3178 PyObject *list, *ref, *new;
3179
3180 list = base->tp_subclasses;
3181 if (list == NULL) {
3182 base->tp_subclasses = list = PyList_New(0);
3183 if (list == NULL)
3184 return -1;
3185 }
3186 assert(PyList_Check(list));
3187 new = PyWeakref_NewRef((PyObject *)type, NULL);
3188 i = PyList_GET_SIZE(list);
3189 while (--i >= 0) {
3190 ref = PyList_GET_ITEM(list, i);
3191 assert(PyWeakref_CheckRef(ref));
Guido van Rossum3930bc32002-10-18 13:51:49 +00003192 if (PyWeakref_GET_OBJECT(ref) == Py_None)
3193 return PyList_SetItem(list, i, new);
Guido van Rossum1c450732001-10-08 15:18:27 +00003194 }
3195 i = PyList_Append(list, new);
3196 Py_DECREF(new);
3197 return i;
3198}
3199
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003200static void
3201remove_subclass(PyTypeObject *base, PyTypeObject *type)
3202{
3203 int i;
3204 PyObject *list, *ref;
3205
3206 list = base->tp_subclasses;
3207 if (list == NULL) {
3208 return;
3209 }
3210 assert(PyList_Check(list));
3211 i = PyList_GET_SIZE(list);
3212 while (--i >= 0) {
3213 ref = PyList_GET_ITEM(list, i);
3214 assert(PyWeakref_CheckRef(ref));
3215 if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
3216 /* this can't fail, right? */
3217 PySequence_DelItem(list, i);
3218 return;
3219 }
3220 }
3221}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003222
3223/* Generic wrappers for overloadable 'operators' such as __getitem__ */
3224
3225/* There's a wrapper *function* for each distinct function typedef used
3226 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
3227 wrapper *table* for each distinct operation (e.g. __len__, __add__).
3228 Most tables have only one entry; the tables for binary operators have two
3229 entries, one regular and one with reversed arguments. */
3230
3231static PyObject *
3232wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
3233{
3234 inquiry func = (inquiry)wrapped;
3235 int res;
3236
3237 if (!PyArg_ParseTuple(args, ""))
3238 return NULL;
3239 res = (*func)(self);
3240 if (res == -1 && PyErr_Occurred())
3241 return NULL;
3242 return PyInt_FromLong((long)res);
3243}
3244
Tim Peters6d6c1a32001-08-02 04:15:00 +00003245static PyObject *
3246wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
3247{
3248 binaryfunc func = (binaryfunc)wrapped;
3249 PyObject *other;
3250
3251 if (!PyArg_ParseTuple(args, "O", &other))
3252 return NULL;
3253 return (*func)(self, other);
3254}
3255
3256static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003257wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
3258{
3259 binaryfunc func = (binaryfunc)wrapped;
3260 PyObject *other;
3261
3262 if (!PyArg_ParseTuple(args, "O", &other))
3263 return NULL;
3264 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003265 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003266 Py_INCREF(Py_NotImplemented);
3267 return Py_NotImplemented;
3268 }
3269 return (*func)(self, other);
3270}
3271
3272static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003273wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3274{
3275 binaryfunc func = (binaryfunc)wrapped;
3276 PyObject *other;
3277
3278 if (!PyArg_ParseTuple(args, "O", &other))
3279 return NULL;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003280 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003281 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003282 Py_INCREF(Py_NotImplemented);
3283 return Py_NotImplemented;
3284 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003285 return (*func)(other, self);
3286}
3287
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003288static PyObject *
3289wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
3290{
3291 coercion func = (coercion)wrapped;
3292 PyObject *other, *res;
3293 int ok;
3294
3295 if (!PyArg_ParseTuple(args, "O", &other))
3296 return NULL;
3297 ok = func(&self, &other);
3298 if (ok < 0)
3299 return NULL;
3300 if (ok > 0) {
3301 Py_INCREF(Py_NotImplemented);
3302 return Py_NotImplemented;
3303 }
3304 res = PyTuple_New(2);
3305 if (res == NULL) {
3306 Py_DECREF(self);
3307 Py_DECREF(other);
3308 return NULL;
3309 }
3310 PyTuple_SET_ITEM(res, 0, self);
3311 PyTuple_SET_ITEM(res, 1, other);
3312 return res;
3313}
3314
Tim Peters6d6c1a32001-08-02 04:15:00 +00003315static PyObject *
3316wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
3317{
3318 ternaryfunc func = (ternaryfunc)wrapped;
3319 PyObject *other;
3320 PyObject *third = Py_None;
3321
3322 /* Note: This wrapper only works for __pow__() */
3323
3324 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
3325 return NULL;
3326 return (*func)(self, other, third);
3327}
3328
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00003329static PyObject *
3330wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3331{
3332 ternaryfunc func = (ternaryfunc)wrapped;
3333 PyObject *other;
3334 PyObject *third = Py_None;
3335
3336 /* Note: This wrapper only works for __pow__() */
3337
3338 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
3339 return NULL;
3340 return (*func)(other, self, third);
3341}
3342
Tim Peters6d6c1a32001-08-02 04:15:00 +00003343static PyObject *
3344wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
3345{
3346 unaryfunc func = (unaryfunc)wrapped;
3347
3348 if (!PyArg_ParseTuple(args, ""))
3349 return NULL;
3350 return (*func)(self);
3351}
3352
Tim Peters6d6c1a32001-08-02 04:15:00 +00003353static PyObject *
3354wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
3355{
3356 intargfunc func = (intargfunc)wrapped;
3357 int i;
3358
3359 if (!PyArg_ParseTuple(args, "i", &i))
3360 return NULL;
3361 return (*func)(self, i);
3362}
3363
Guido van Rossum5d815f32001-08-17 21:57:47 +00003364static int
3365getindex(PyObject *self, PyObject *arg)
3366{
3367 int i;
3368
3369 i = PyInt_AsLong(arg);
3370 if (i == -1 && PyErr_Occurred())
3371 return -1;
3372 if (i < 0) {
3373 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
3374 if (sq && sq->sq_length) {
3375 int n = (*sq->sq_length)(self);
3376 if (n < 0)
3377 return -1;
3378 i += n;
3379 }
3380 }
3381 return i;
3382}
3383
3384static PyObject *
3385wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
3386{
3387 intargfunc func = (intargfunc)wrapped;
3388 PyObject *arg;
3389 int i;
3390
Guido van Rossumf4593e02001-10-03 12:09:30 +00003391 if (PyTuple_GET_SIZE(args) == 1) {
3392 arg = PyTuple_GET_ITEM(args, 0);
3393 i = getindex(self, arg);
3394 if (i == -1 && PyErr_Occurred())
3395 return NULL;
3396 return (*func)(self, i);
3397 }
3398 PyArg_ParseTuple(args, "O", &arg);
3399 assert(PyErr_Occurred());
3400 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003401}
3402
Tim Peters6d6c1a32001-08-02 04:15:00 +00003403static PyObject *
3404wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
3405{
3406 intintargfunc func = (intintargfunc)wrapped;
3407 int i, j;
3408
3409 if (!PyArg_ParseTuple(args, "ii", &i, &j))
3410 return NULL;
3411 return (*func)(self, i, j);
3412}
3413
Tim Peters6d6c1a32001-08-02 04:15:00 +00003414static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003415wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003416{
3417 intobjargproc func = (intobjargproc)wrapped;
3418 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003419 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003420
Guido van Rossum5d815f32001-08-17 21:57:47 +00003421 if (!PyArg_ParseTuple(args, "OO", &arg, &value))
3422 return NULL;
3423 i = getindex(self, arg);
3424 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00003425 return NULL;
3426 res = (*func)(self, i, value);
3427 if (res == -1 && PyErr_Occurred())
3428 return NULL;
3429 Py_INCREF(Py_None);
3430 return Py_None;
3431}
3432
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003433static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003434wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003435{
3436 intobjargproc func = (intobjargproc)wrapped;
3437 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003438 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003439
Guido van Rossum5d815f32001-08-17 21:57:47 +00003440 if (!PyArg_ParseTuple(args, "O", &arg))
3441 return NULL;
3442 i = getindex(self, arg);
3443 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003444 return NULL;
3445 res = (*func)(self, i, NULL);
3446 if (res == -1 && PyErr_Occurred())
3447 return NULL;
3448 Py_INCREF(Py_None);
3449 return Py_None;
3450}
3451
Tim Peters6d6c1a32001-08-02 04:15:00 +00003452static PyObject *
3453wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
3454{
3455 intintobjargproc func = (intintobjargproc)wrapped;
3456 int i, j, res;
3457 PyObject *value;
3458
3459 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
3460 return NULL;
3461 res = (*func)(self, i, j, value);
3462 if (res == -1 && PyErr_Occurred())
3463 return NULL;
3464 Py_INCREF(Py_None);
3465 return Py_None;
3466}
3467
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003468static PyObject *
3469wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
3470{
3471 intintobjargproc func = (intintobjargproc)wrapped;
3472 int i, j, res;
3473
3474 if (!PyArg_ParseTuple(args, "ii", &i, &j))
3475 return NULL;
3476 res = (*func)(self, i, j, NULL);
3477 if (res == -1 && PyErr_Occurred())
3478 return NULL;
3479 Py_INCREF(Py_None);
3480 return Py_None;
3481}
3482
Tim Peters6d6c1a32001-08-02 04:15:00 +00003483/* XXX objobjproc is a misnomer; should be objargpred */
3484static PyObject *
3485wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
3486{
3487 objobjproc func = (objobjproc)wrapped;
3488 int res;
3489 PyObject *value;
3490
3491 if (!PyArg_ParseTuple(args, "O", &value))
3492 return NULL;
3493 res = (*func)(self, value);
3494 if (res == -1 && PyErr_Occurred())
3495 return NULL;
3496 return PyInt_FromLong((long)res);
3497}
3498
Tim Peters6d6c1a32001-08-02 04:15:00 +00003499static PyObject *
3500wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
3501{
3502 objobjargproc func = (objobjargproc)wrapped;
3503 int res;
3504 PyObject *key, *value;
3505
3506 if (!PyArg_ParseTuple(args, "OO", &key, &value))
3507 return NULL;
3508 res = (*func)(self, key, value);
3509 if (res == -1 && PyErr_Occurred())
3510 return NULL;
3511 Py_INCREF(Py_None);
3512 return Py_None;
3513}
3514
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003515static PyObject *
3516wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
3517{
3518 objobjargproc func = (objobjargproc)wrapped;
3519 int res;
3520 PyObject *key;
3521
3522 if (!PyArg_ParseTuple(args, "O", &key))
3523 return NULL;
3524 res = (*func)(self, key, NULL);
3525 if (res == -1 && PyErr_Occurred())
3526 return NULL;
3527 Py_INCREF(Py_None);
3528 return Py_None;
3529}
3530
Tim Peters6d6c1a32001-08-02 04:15:00 +00003531static PyObject *
3532wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
3533{
3534 cmpfunc func = (cmpfunc)wrapped;
3535 int res;
3536 PyObject *other;
3537
3538 if (!PyArg_ParseTuple(args, "O", &other))
3539 return NULL;
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00003540 if (other->ob_type->tp_compare != func &&
3541 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00003542 PyErr_Format(
3543 PyExc_TypeError,
3544 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
3545 self->ob_type->tp_name,
3546 self->ob_type->tp_name,
3547 other->ob_type->tp_name);
3548 return NULL;
3549 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003550 res = (*func)(self, other);
3551 if (PyErr_Occurred())
3552 return NULL;
3553 return PyInt_FromLong((long)res);
3554}
3555
Tim Peters6d6c1a32001-08-02 04:15:00 +00003556static PyObject *
3557wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
3558{
3559 setattrofunc func = (setattrofunc)wrapped;
3560 int res;
3561 PyObject *name, *value;
3562
3563 if (!PyArg_ParseTuple(args, "OO", &name, &value))
3564 return NULL;
3565 res = (*func)(self, name, value);
3566 if (res < 0)
3567 return NULL;
3568 Py_INCREF(Py_None);
3569 return Py_None;
3570}
3571
3572static PyObject *
3573wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
3574{
3575 setattrofunc func = (setattrofunc)wrapped;
3576 int res;
3577 PyObject *name;
3578
3579 if (!PyArg_ParseTuple(args, "O", &name))
3580 return NULL;
3581 res = (*func)(self, name, NULL);
3582 if (res < 0)
3583 return NULL;
3584 Py_INCREF(Py_None);
3585 return Py_None;
3586}
3587
Tim Peters6d6c1a32001-08-02 04:15:00 +00003588static PyObject *
3589wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
3590{
3591 hashfunc func = (hashfunc)wrapped;
3592 long res;
3593
3594 if (!PyArg_ParseTuple(args, ""))
3595 return NULL;
3596 res = (*func)(self);
3597 if (res == -1 && PyErr_Occurred())
3598 return NULL;
3599 return PyInt_FromLong(res);
3600}
3601
Tim Peters6d6c1a32001-08-02 04:15:00 +00003602static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00003603wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003604{
3605 ternaryfunc func = (ternaryfunc)wrapped;
3606
Guido van Rossumc8e56452001-10-22 00:43:43 +00003607 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003608}
3609
Tim Peters6d6c1a32001-08-02 04:15:00 +00003610static PyObject *
3611wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
3612{
3613 richcmpfunc func = (richcmpfunc)wrapped;
3614 PyObject *other;
3615
3616 if (!PyArg_ParseTuple(args, "O", &other))
3617 return NULL;
3618 return (*func)(self, other, op);
3619}
3620
3621#undef RICHCMP_WRAPPER
3622#define RICHCMP_WRAPPER(NAME, OP) \
3623static PyObject * \
3624richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
3625{ \
3626 return wrap_richcmpfunc(self, args, wrapped, OP); \
3627}
3628
Jack Jansen8e938b42001-08-08 15:29:49 +00003629RICHCMP_WRAPPER(lt, Py_LT)
3630RICHCMP_WRAPPER(le, Py_LE)
3631RICHCMP_WRAPPER(eq, Py_EQ)
3632RICHCMP_WRAPPER(ne, Py_NE)
3633RICHCMP_WRAPPER(gt, Py_GT)
3634RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003635
Tim Peters6d6c1a32001-08-02 04:15:00 +00003636static PyObject *
3637wrap_next(PyObject *self, PyObject *args, void *wrapped)
3638{
3639 unaryfunc func = (unaryfunc)wrapped;
3640 PyObject *res;
3641
3642 if (!PyArg_ParseTuple(args, ""))
3643 return NULL;
3644 res = (*func)(self);
3645 if (res == NULL && !PyErr_Occurred())
3646 PyErr_SetNone(PyExc_StopIteration);
3647 return res;
3648}
3649
Tim Peters6d6c1a32001-08-02 04:15:00 +00003650static PyObject *
3651wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
3652{
3653 descrgetfunc func = (descrgetfunc)wrapped;
3654 PyObject *obj;
3655 PyObject *type = NULL;
3656
3657 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
3658 return NULL;
Guido van Rossum82ed25c2003-02-11 16:25:43 +00003659 if (obj == Py_None)
3660 obj = NULL;
3661 if (type == Py_None)
3662 type = NULL;
3663 if (type == NULL &&obj == NULL) {
3664 PyErr_SetString(PyExc_TypeError,
3665 "__get__(None, None) is invalid");
3666 return NULL;
3667 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003668 return (*func)(self, obj, type);
3669}
3670
Tim Peters6d6c1a32001-08-02 04:15:00 +00003671static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003672wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003673{
3674 descrsetfunc func = (descrsetfunc)wrapped;
3675 PyObject *obj, *value;
3676 int ret;
3677
3678 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
3679 return NULL;
3680 ret = (*func)(self, obj, value);
3681 if (ret < 0)
3682 return NULL;
3683 Py_INCREF(Py_None);
3684 return Py_None;
3685}
Guido van Rossum22b13872002-08-06 21:41:44 +00003686
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00003687static PyObject *
3688wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
3689{
3690 descrsetfunc func = (descrsetfunc)wrapped;
3691 PyObject *obj;
3692 int ret;
3693
3694 if (!PyArg_ParseTuple(args, "O", &obj))
3695 return NULL;
3696 ret = (*func)(self, obj, NULL);
3697 if (ret < 0)
3698 return NULL;
3699 Py_INCREF(Py_None);
3700 return Py_None;
3701}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003702
Tim Peters6d6c1a32001-08-02 04:15:00 +00003703static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00003704wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003705{
3706 initproc func = (initproc)wrapped;
3707
Guido van Rossumc8e56452001-10-22 00:43:43 +00003708 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003709 return NULL;
3710 Py_INCREF(Py_None);
3711 return Py_None;
3712}
3713
Tim Peters6d6c1a32001-08-02 04:15:00 +00003714static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003715tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003716{
Barry Warsaw60f01882001-08-22 19:24:42 +00003717 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003718 PyObject *arg0, *res;
3719
3720 if (self == NULL || !PyType_Check(self))
3721 Py_FatalError("__new__() called with non-type 'self'");
3722 type = (PyTypeObject *)self;
3723 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003724 PyErr_Format(PyExc_TypeError,
3725 "%s.__new__(): not enough arguments",
3726 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003727 return NULL;
3728 }
3729 arg0 = PyTuple_GET_ITEM(args, 0);
3730 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003731 PyErr_Format(PyExc_TypeError,
3732 "%s.__new__(X): X is not a type object (%s)",
3733 type->tp_name,
3734 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003735 return NULL;
3736 }
3737 subtype = (PyTypeObject *)arg0;
3738 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003739 PyErr_Format(PyExc_TypeError,
3740 "%s.__new__(%s): %s is not a subtype of %s",
3741 type->tp_name,
3742 subtype->tp_name,
3743 subtype->tp_name,
3744 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003745 return NULL;
3746 }
Barry Warsaw60f01882001-08-22 19:24:42 +00003747
3748 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00003749 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00003750 most derived base that's not a heap type is this type. */
3751 staticbase = subtype;
3752 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
3753 staticbase = staticbase->tp_base;
Guido van Rossuma8c60f42001-09-14 19:43:36 +00003754 if (staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003755 PyErr_Format(PyExc_TypeError,
3756 "%s.__new__(%s) is not safe, use %s.__new__()",
3757 type->tp_name,
3758 subtype->tp_name,
3759 staticbase == NULL ? "?" : staticbase->tp_name);
3760 return NULL;
3761 }
3762
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003763 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
3764 if (args == NULL)
3765 return NULL;
3766 res = type->tp_new(subtype, args, kwds);
3767 Py_DECREF(args);
3768 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003769}
3770
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003771static struct PyMethodDef tp_new_methoddef[] = {
3772 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00003773 PyDoc_STR("T.__new__(S, ...) -> "
3774 "a new object with type S, a subtype of T")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00003775 {0}
3776};
3777
3778static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003779add_tp_new_wrapper(PyTypeObject *type)
3780{
Guido van Rossumf040ede2001-08-07 16:40:56 +00003781 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003782
Guido van Rossum687ae002001-10-15 22:03:32 +00003783 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00003784 return 0;
3785 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003786 if (func == NULL)
3787 return -1;
Guido van Rossum687ae002001-10-15 22:03:32 +00003788 return PyDict_SetItemString(type->tp_dict, "__new__", func);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003789}
3790
Guido van Rossumf040ede2001-08-07 16:40:56 +00003791/* Slot wrappers that call the corresponding __foo__ slot. See comments
3792 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003793
Guido van Rossumdc91b992001-08-08 22:26:22 +00003794#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003795static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003796FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003797{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00003798 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003799 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003800}
3801
Guido van Rossumdc91b992001-08-08 22:26:22 +00003802#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003803static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003804FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003805{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003806 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003807 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003808}
3809
Guido van Rossumcd118802003-01-06 22:57:47 +00003810/* Boolean helper for SLOT1BINFULL().
3811 right.__class__ is a nontrivial subclass of left.__class__. */
3812static int
3813method_is_overloaded(PyObject *left, PyObject *right, char *name)
3814{
3815 PyObject *a, *b;
3816 int ok;
3817
3818 b = PyObject_GetAttrString((PyObject *)(right->ob_type), name);
3819 if (b == NULL) {
3820 PyErr_Clear();
3821 /* If right doesn't have it, it's not overloaded */
3822 return 0;
3823 }
3824
3825 a = PyObject_GetAttrString((PyObject *)(left->ob_type), name);
3826 if (a == NULL) {
3827 PyErr_Clear();
3828 Py_DECREF(b);
3829 /* If right has it but left doesn't, it's overloaded */
3830 return 1;
3831 }
3832
3833 ok = PyObject_RichCompareBool(a, b, Py_NE);
3834 Py_DECREF(a);
3835 Py_DECREF(b);
3836 if (ok < 0) {
3837 PyErr_Clear();
3838 return 0;
3839 }
3840
3841 return ok;
3842}
3843
Guido van Rossumdc91b992001-08-08 22:26:22 +00003844
3845#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003846static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003847FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003848{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003849 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00003850 int do_other = self->ob_type != other->ob_type && \
3851 other->ob_type->tp_as_number != NULL && \
3852 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003853 if (self->ob_type->tp_as_number != NULL && \
3854 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
3855 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00003856 if (do_other && \
Guido van Rossumcd118802003-01-06 22:57:47 +00003857 PyType_IsSubtype(other->ob_type, self->ob_type) && \
3858 method_is_overloaded(self, other, ROPSTR)) { \
Guido van Rossum55f20992001-10-01 17:18:22 +00003859 r = call_maybe( \
3860 other, ROPSTR, &rcache_str, "(O)", self); \
3861 if (r != Py_NotImplemented) \
3862 return r; \
3863 Py_DECREF(r); \
3864 do_other = 0; \
3865 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00003866 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00003867 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003868 if (r != Py_NotImplemented || \
3869 other->ob_type == self->ob_type) \
3870 return r; \
3871 Py_DECREF(r); \
3872 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00003873 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00003874 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00003875 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003876 } \
3877 Py_INCREF(Py_NotImplemented); \
3878 return Py_NotImplemented; \
3879}
3880
3881#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
3882 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
3883
3884#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
3885static PyObject * \
3886FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
3887{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003888 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003889 return call_method(self, OPSTR, &cache_str, \
3890 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003891}
3892
3893static int
3894slot_sq_length(PyObject *self)
3895{
Guido van Rossum2730b132001-08-28 18:22:14 +00003896 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00003897 PyObject *res = call_method(self, "__len__", &len_str, "()");
Guido van Rossum26111622001-10-01 16:42:49 +00003898 int len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003899
3900 if (res == NULL)
3901 return -1;
Guido van Rossum26111622001-10-01 16:42:49 +00003902 len = (int)PyInt_AsLong(res);
3903 Py_DECREF(res);
Jeremy Hylton73a088e2002-07-25 16:43:29 +00003904 if (len == -1 && PyErr_Occurred())
3905 return -1;
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00003906 if (len < 0) {
Guido van Rossum22b13872002-08-06 21:41:44 +00003907 PyErr_SetString(PyExc_ValueError,
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00003908 "__len__() should return >= 0");
3909 return -1;
3910 }
Guido van Rossum26111622001-10-01 16:42:49 +00003911 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003912}
3913
Guido van Rossumdc91b992001-08-08 22:26:22 +00003914SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
3915SLOT1(slot_sq_repeat, "__mul__", int, "i")
Guido van Rossumf4593e02001-10-03 12:09:30 +00003916
3917/* Super-optimized version of slot_sq_item.
3918 Other slots could do the same... */
3919static PyObject *
3920slot_sq_item(PyObject *self, int i)
3921{
3922 static PyObject *getitem_str;
3923 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
3924 descrgetfunc f;
3925
3926 if (getitem_str == NULL) {
3927 getitem_str = PyString_InternFromString("__getitem__");
3928 if (getitem_str == NULL)
3929 return NULL;
3930 }
3931 func = _PyType_Lookup(self->ob_type, getitem_str);
3932 if (func != NULL) {
Guido van Rossumf4593e02001-10-03 12:09:30 +00003933 if ((f = func->ob_type->tp_descr_get) == NULL)
3934 Py_INCREF(func);
Neal Norwitz673cd822002-10-18 16:33:13 +00003935 else {
Guido van Rossumf4593e02001-10-03 12:09:30 +00003936 func = f(func, self, (PyObject *)(self->ob_type));
Neal Norwitz673cd822002-10-18 16:33:13 +00003937 if (func == NULL) {
3938 return NULL;
3939 }
3940 }
Guido van Rossumf4593e02001-10-03 12:09:30 +00003941 ival = PyInt_FromLong(i);
3942 if (ival != NULL) {
3943 args = PyTuple_New(1);
3944 if (args != NULL) {
3945 PyTuple_SET_ITEM(args, 0, ival);
3946 retval = PyObject_Call(func, args, NULL);
3947 Py_XDECREF(args);
3948 Py_XDECREF(func);
3949 return retval;
3950 }
3951 }
3952 }
3953 else {
3954 PyErr_SetObject(PyExc_AttributeError, getitem_str);
3955 }
3956 Py_XDECREF(args);
3957 Py_XDECREF(ival);
3958 Py_XDECREF(func);
3959 return NULL;
3960}
3961
Guido van Rossumdc91b992001-08-08 22:26:22 +00003962SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003963
3964static int
3965slot_sq_ass_item(PyObject *self, int index, PyObject *value)
3966{
3967 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003968 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003969
3970 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003971 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003972 "(i)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003973 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003974 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003975 "(iO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003976 if (res == NULL)
3977 return -1;
3978 Py_DECREF(res);
3979 return 0;
3980}
3981
3982static int
3983slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
3984{
3985 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003986 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003987
3988 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003989 res = call_method(self, "__delslice__", &delslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003990 "(ii)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003991 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003992 res = call_method(self, "__setslice__", &setslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003993 "(iiO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003994 if (res == NULL)
3995 return -1;
3996 Py_DECREF(res);
3997 return 0;
3998}
3999
4000static int
4001slot_sq_contains(PyObject *self, PyObject *value)
4002{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004003 PyObject *func, *res, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00004004 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004005
Guido van Rossum55f20992001-10-01 17:18:22 +00004006 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004007
4008 if (func != NULL) {
4009 args = Py_BuildValue("(O)", value);
4010 if (args == NULL)
4011 res = NULL;
4012 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004013 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004014 Py_DECREF(args);
4015 }
4016 Py_DECREF(func);
4017 if (res == NULL)
4018 return -1;
4019 return PyObject_IsTrue(res);
4020 }
Guido van Rossum55f20992001-10-01 17:18:22 +00004021 else if (PyErr_Occurred())
4022 return -1;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004023 else {
Tim Peters16a77ad2001-09-08 04:00:12 +00004024 return _PySequence_IterSearch(self, value,
4025 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004026 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004027}
4028
Guido van Rossumdc91b992001-08-08 22:26:22 +00004029SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
4030SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004031
4032#define slot_mp_length slot_sq_length
4033
Guido van Rossumdc91b992001-08-08 22:26:22 +00004034SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004035
4036static int
4037slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
4038{
4039 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004040 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004041
4042 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004043 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004044 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004045 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004046 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004047 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004048 if (res == NULL)
4049 return -1;
4050 Py_DECREF(res);
4051 return 0;
4052}
4053
Guido van Rossumdc91b992001-08-08 22:26:22 +00004054SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
4055SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
4056SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
4057SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
4058SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
4059SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
4060
Jeremy Hylton938ace62002-07-17 16:30:39 +00004061static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00004062
4063SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
4064 nb_power, "__pow__", "__rpow__")
4065
4066static PyObject *
4067slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
4068{
Guido van Rossum2730b132001-08-28 18:22:14 +00004069 static PyObject *pow_str;
4070
Guido van Rossumdc91b992001-08-08 22:26:22 +00004071 if (modulus == Py_None)
4072 return slot_nb_power_binary(self, other);
Guido van Rossum23094982002-06-10 14:30:43 +00004073 /* Three-arg power doesn't use __rpow__. But ternary_op
4074 can call this when the second argument's type uses
4075 slot_nb_power, so check before calling self.__pow__. */
4076 if (self->ob_type->tp_as_number != NULL &&
4077 self->ob_type->tp_as_number->nb_power == slot_nb_power) {
4078 return call_method(self, "__pow__", &pow_str,
4079 "(OO)", other, modulus);
4080 }
4081 Py_INCREF(Py_NotImplemented);
4082 return Py_NotImplemented;
Guido van Rossumdc91b992001-08-08 22:26:22 +00004083}
4084
4085SLOT0(slot_nb_negative, "__neg__")
4086SLOT0(slot_nb_positive, "__pos__")
4087SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004088
4089static int
4090slot_nb_nonzero(PyObject *self)
4091{
Tim Petersea7f75d2002-12-07 21:39:16 +00004092 PyObject *func, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00004093 static PyObject *nonzero_str, *len_str;
Tim Petersea7f75d2002-12-07 21:39:16 +00004094 int result = -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004095
Guido van Rossum55f20992001-10-01 17:18:22 +00004096 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004097 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00004098 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00004099 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00004100 func = lookup_maybe(self, "__len__", &len_str);
Tim Petersea7f75d2002-12-07 21:39:16 +00004101 if (func == NULL)
4102 return PyErr_Occurred() ? -1 : 1;
4103 }
4104 args = PyTuple_New(0);
4105 if (args != NULL) {
4106 PyObject *temp = PyObject_Call(func, args, NULL);
4107 Py_DECREF(args);
4108 if (temp != NULL) {
4109 result = PyObject_IsTrue(temp);
4110 Py_DECREF(temp);
Guido van Rossum55f20992001-10-01 17:18:22 +00004111 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004112 }
Guido van Rossum55f20992001-10-01 17:18:22 +00004113 Py_DECREF(func);
Tim Petersea7f75d2002-12-07 21:39:16 +00004114 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004115}
4116
Guido van Rossumdc91b992001-08-08 22:26:22 +00004117SLOT0(slot_nb_invert, "__invert__")
4118SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
4119SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
4120SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
4121SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
4122SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004123
4124static int
4125slot_nb_coerce(PyObject **a, PyObject **b)
4126{
4127 static PyObject *coerce_str;
4128 PyObject *self = *a, *other = *b;
4129
4130 if (self->ob_type->tp_as_number != NULL &&
4131 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
4132 PyObject *r;
4133 r = call_maybe(
4134 self, "__coerce__", &coerce_str, "(O)", other);
4135 if (r == NULL)
4136 return -1;
4137 if (r == Py_NotImplemented) {
4138 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004139 }
Guido van Rossum55f20992001-10-01 17:18:22 +00004140 else {
4141 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
4142 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004143 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00004144 Py_DECREF(r);
4145 return -1;
4146 }
4147 *a = PyTuple_GET_ITEM(r, 0);
4148 Py_INCREF(*a);
4149 *b = PyTuple_GET_ITEM(r, 1);
4150 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004151 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00004152 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004153 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004154 }
4155 if (other->ob_type->tp_as_number != NULL &&
4156 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
4157 PyObject *r;
4158 r = call_maybe(
4159 other, "__coerce__", &coerce_str, "(O)", self);
4160 if (r == NULL)
4161 return -1;
4162 if (r == Py_NotImplemented) {
4163 Py_DECREF(r);
4164 return 1;
4165 }
4166 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
4167 PyErr_SetString(PyExc_TypeError,
4168 "__coerce__ didn't return a 2-tuple");
4169 Py_DECREF(r);
4170 return -1;
4171 }
4172 *a = PyTuple_GET_ITEM(r, 1);
4173 Py_INCREF(*a);
4174 *b = PyTuple_GET_ITEM(r, 0);
4175 Py_INCREF(*b);
4176 Py_DECREF(r);
4177 return 0;
4178 }
4179 return 1;
4180}
4181
Guido van Rossumdc91b992001-08-08 22:26:22 +00004182SLOT0(slot_nb_int, "__int__")
4183SLOT0(slot_nb_long, "__long__")
4184SLOT0(slot_nb_float, "__float__")
4185SLOT0(slot_nb_oct, "__oct__")
4186SLOT0(slot_nb_hex, "__hex__")
4187SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
4188SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
4189SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
4190SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
4191SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Guido van Rossum6e5680f2002-10-15 01:01:53 +00004192SLOT1(slot_nb_inplace_power, "__ipow__", PyObject *, "O")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004193SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
4194SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
4195SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
4196SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
4197SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
4198SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
4199 "__floordiv__", "__rfloordiv__")
4200SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
4201SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
4202SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004203
4204static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00004205half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004206{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004207 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004208 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004209 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004210
Guido van Rossum60718732001-08-28 17:47:51 +00004211 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004212 if (func == NULL) {
4213 PyErr_Clear();
4214 }
4215 else {
4216 args = Py_BuildValue("(O)", other);
4217 if (args == NULL)
4218 res = NULL;
4219 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004220 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004221 Py_DECREF(args);
4222 }
Raymond Hettingerab5dae32002-06-24 13:08:16 +00004223 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004224 if (res != Py_NotImplemented) {
4225 if (res == NULL)
4226 return -2;
4227 c = PyInt_AsLong(res);
4228 Py_DECREF(res);
4229 if (c == -1 && PyErr_Occurred())
4230 return -2;
4231 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
4232 }
4233 Py_DECREF(res);
4234 }
4235 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004236}
4237
Guido van Rossumab3b0342001-09-18 20:38:53 +00004238/* This slot is published for the benefit of try_3way_compare in object.c */
4239int
4240_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00004241{
4242 int c;
4243
Guido van Rossumab3b0342001-09-18 20:38:53 +00004244 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004245 c = half_compare(self, other);
4246 if (c <= 1)
4247 return c;
4248 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00004249 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004250 c = half_compare(other, self);
4251 if (c < -1)
4252 return -2;
4253 if (c <= 1)
4254 return -c;
4255 }
4256 return (void *)self < (void *)other ? -1 :
4257 (void *)self > (void *)other ? 1 : 0;
4258}
4259
4260static PyObject *
4261slot_tp_repr(PyObject *self)
4262{
4263 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004264 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004265
Guido van Rossum60718732001-08-28 17:47:51 +00004266 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004267 if (func != NULL) {
4268 res = PyEval_CallObject(func, NULL);
4269 Py_DECREF(func);
4270 return res;
4271 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00004272 PyErr_Clear();
4273 return PyString_FromFormat("<%s object at %p>",
4274 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004275}
4276
4277static PyObject *
4278slot_tp_str(PyObject *self)
4279{
4280 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004281 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004282
Guido van Rossum60718732001-08-28 17:47:51 +00004283 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004284 if (func != NULL) {
4285 res = PyEval_CallObject(func, NULL);
4286 Py_DECREF(func);
4287 return res;
4288 }
4289 else {
4290 PyErr_Clear();
4291 return slot_tp_repr(self);
4292 }
4293}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004294
4295static long
4296slot_tp_hash(PyObject *self)
4297{
Tim Peters61ce0a92002-12-06 23:38:02 +00004298 PyObject *func;
Guido van Rossum60718732001-08-28 17:47:51 +00004299 static PyObject *hash_str, *eq_str, *cmp_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004300 long h;
4301
Guido van Rossum60718732001-08-28 17:47:51 +00004302 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004303
4304 if (func != NULL) {
Tim Peters61ce0a92002-12-06 23:38:02 +00004305 PyObject *res = PyEval_CallObject(func, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004306 Py_DECREF(func);
4307 if (res == NULL)
4308 return -1;
4309 h = PyInt_AsLong(res);
Tim Peters61ce0a92002-12-06 23:38:02 +00004310 Py_DECREF(res);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004311 }
4312 else {
4313 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004314 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004315 if (func == NULL) {
4316 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004317 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004318 }
4319 if (func != NULL) {
4320 Py_DECREF(func);
4321 PyErr_SetString(PyExc_TypeError, "unhashable type");
4322 return -1;
4323 }
4324 PyErr_Clear();
4325 h = _Py_HashPointer((void *)self);
4326 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004327 if (h == -1 && !PyErr_Occurred())
4328 h = -2;
4329 return h;
4330}
4331
4332static PyObject *
4333slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
4334{
Guido van Rossum60718732001-08-28 17:47:51 +00004335 static PyObject *call_str;
4336 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004337 PyObject *res;
4338
4339 if (meth == NULL)
4340 return NULL;
4341 res = PyObject_Call(meth, args, kwds);
4342 Py_DECREF(meth);
4343 return res;
4344}
4345
Guido van Rossum14a6f832001-10-17 13:59:09 +00004346/* There are two slot dispatch functions for tp_getattro.
4347
4348 - slot_tp_getattro() is used when __getattribute__ is overridden
4349 but no __getattr__ hook is present;
4350
4351 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
4352
Guido van Rossumc334df52002-04-04 23:44:47 +00004353 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
4354 detects the absence of __getattr__ and then installs the simpler slot if
4355 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00004356
Tim Peters6d6c1a32001-08-02 04:15:00 +00004357static PyObject *
4358slot_tp_getattro(PyObject *self, PyObject *name)
4359{
Guido van Rossum14a6f832001-10-17 13:59:09 +00004360 static PyObject *getattribute_str = NULL;
4361 return call_method(self, "__getattribute__", &getattribute_str,
4362 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004363}
4364
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004365static PyObject *
4366slot_tp_getattr_hook(PyObject *self, PyObject *name)
4367{
4368 PyTypeObject *tp = self->ob_type;
4369 PyObject *getattr, *getattribute, *res;
4370 static PyObject *getattribute_str = NULL;
4371 static PyObject *getattr_str = NULL;
4372
4373 if (getattr_str == NULL) {
4374 getattr_str = PyString_InternFromString("__getattr__");
4375 if (getattr_str == NULL)
4376 return NULL;
4377 }
4378 if (getattribute_str == NULL) {
4379 getattribute_str =
4380 PyString_InternFromString("__getattribute__");
4381 if (getattribute_str == NULL)
4382 return NULL;
4383 }
4384 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004385 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004386 /* No __getattr__ hook: use a simpler dispatcher */
4387 tp->tp_getattro = slot_tp_getattro;
4388 return slot_tp_getattro(self, name);
4389 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004390 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004391 if (getattribute == NULL ||
4392 (getattribute->ob_type == &PyWrapperDescr_Type &&
4393 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
4394 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004395 res = PyObject_GenericGetAttr(self, name);
4396 else
4397 res = PyObject_CallFunction(getattribute, "OO", self, name);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004398 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004399 PyErr_Clear();
4400 res = PyObject_CallFunction(getattr, "OO", self, name);
4401 }
4402 return res;
4403}
4404
Tim Peters6d6c1a32001-08-02 04:15:00 +00004405static int
4406slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
4407{
4408 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004409 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004410
4411 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004412 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004413 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004414 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004415 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004416 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004417 if (res == NULL)
4418 return -1;
4419 Py_DECREF(res);
4420 return 0;
4421}
4422
4423/* Map rich comparison operators to their __xx__ namesakes */
4424static char *name_op[] = {
4425 "__lt__",
4426 "__le__",
4427 "__eq__",
4428 "__ne__",
4429 "__gt__",
4430 "__ge__",
4431};
4432
4433static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00004434half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004435{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004436 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004437 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00004438
Guido van Rossum60718732001-08-28 17:47:51 +00004439 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004440 if (func == NULL) {
4441 PyErr_Clear();
4442 Py_INCREF(Py_NotImplemented);
4443 return Py_NotImplemented;
4444 }
4445 args = Py_BuildValue("(O)", other);
4446 if (args == NULL)
4447 res = NULL;
4448 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004449 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004450 Py_DECREF(args);
4451 }
4452 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004453 return res;
4454}
4455
Guido van Rossumb8f63662001-08-15 23:57:02 +00004456/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
4457static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
4458
4459static PyObject *
4460slot_tp_richcompare(PyObject *self, PyObject *other, int op)
4461{
4462 PyObject *res;
4463
4464 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
4465 res = half_richcompare(self, other, op);
4466 if (res != Py_NotImplemented)
4467 return res;
4468 Py_DECREF(res);
4469 }
4470 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
4471 res = half_richcompare(other, self, swapped_op[op]);
4472 if (res != Py_NotImplemented) {
4473 return res;
4474 }
4475 Py_DECREF(res);
4476 }
4477 Py_INCREF(Py_NotImplemented);
4478 return Py_NotImplemented;
4479}
4480
4481static PyObject *
4482slot_tp_iter(PyObject *self)
4483{
4484 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004485 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004486
Guido van Rossum60718732001-08-28 17:47:51 +00004487 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004488 if (func != NULL) {
Guido van Rossum84b2bed2002-08-16 17:01:09 +00004489 PyObject *args;
4490 args = res = PyTuple_New(0);
4491 if (args != NULL) {
4492 res = PyObject_Call(func, args, NULL);
4493 Py_DECREF(args);
4494 }
4495 Py_DECREF(func);
4496 return res;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004497 }
4498 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004499 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004500 if (func == NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00004501 PyErr_SetString(PyExc_TypeError,
4502 "iteration over non-sequence");
Guido van Rossumb8f63662001-08-15 23:57:02 +00004503 return NULL;
4504 }
4505 Py_DECREF(func);
4506 return PySeqIter_New(self);
4507}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004508
4509static PyObject *
4510slot_tp_iternext(PyObject *self)
4511{
Guido van Rossum2730b132001-08-28 18:22:14 +00004512 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00004513 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004514}
4515
Guido van Rossum1a493502001-08-17 16:47:50 +00004516static PyObject *
4517slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4518{
4519 PyTypeObject *tp = self->ob_type;
4520 PyObject *get;
4521 static PyObject *get_str = NULL;
4522
4523 if (get_str == NULL) {
4524 get_str = PyString_InternFromString("__get__");
4525 if (get_str == NULL)
4526 return NULL;
4527 }
4528 get = _PyType_Lookup(tp, get_str);
4529 if (get == NULL) {
4530 /* Avoid further slowdowns */
4531 if (tp->tp_descr_get == slot_tp_descr_get)
4532 tp->tp_descr_get = NULL;
4533 Py_INCREF(self);
4534 return self;
4535 }
Guido van Rossum2c252392001-08-24 10:13:31 +00004536 if (obj == NULL)
4537 obj = Py_None;
4538 if (type == NULL)
4539 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00004540 return PyObject_CallFunction(get, "OOO", self, obj, type);
4541}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004542
4543static int
4544slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
4545{
Guido van Rossum2c252392001-08-24 10:13:31 +00004546 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004547 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00004548
4549 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00004550 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004551 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00004552 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004553 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004554 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004555 if (res == NULL)
4556 return -1;
4557 Py_DECREF(res);
4558 return 0;
4559}
4560
4561static int
4562slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
4563{
Guido van Rossum60718732001-08-28 17:47:51 +00004564 static PyObject *init_str;
4565 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004566 PyObject *res;
4567
4568 if (meth == NULL)
4569 return -1;
4570 res = PyObject_Call(meth, args, kwds);
4571 Py_DECREF(meth);
4572 if (res == NULL)
4573 return -1;
4574 Py_DECREF(res);
4575 return 0;
4576}
4577
4578static PyObject *
4579slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4580{
Guido van Rossum7bed2132002-08-08 21:57:53 +00004581 static PyObject *new_str;
4582 PyObject *func;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004583 PyObject *newargs, *x;
4584 int i, n;
4585
Guido van Rossum7bed2132002-08-08 21:57:53 +00004586 if (new_str == NULL) {
4587 new_str = PyString_InternFromString("__new__");
4588 if (new_str == NULL)
4589 return NULL;
4590 }
4591 func = PyObject_GetAttr((PyObject *)type, new_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004592 if (func == NULL)
4593 return NULL;
4594 assert(PyTuple_Check(args));
4595 n = PyTuple_GET_SIZE(args);
4596 newargs = PyTuple_New(n+1);
4597 if (newargs == NULL)
4598 return NULL;
4599 Py_INCREF(type);
4600 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
4601 for (i = 0; i < n; i++) {
4602 x = PyTuple_GET_ITEM(args, i);
4603 Py_INCREF(x);
4604 PyTuple_SET_ITEM(newargs, i+1, x);
4605 }
4606 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00004607 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004608 Py_DECREF(func);
4609 return x;
4610}
4611
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004612static void
4613slot_tp_del(PyObject *self)
4614{
4615 static PyObject *del_str = NULL;
4616 PyObject *del, *res;
4617 PyObject *error_type, *error_value, *error_traceback;
4618
4619 /* Temporarily resurrect the object. */
4620 assert(self->ob_refcnt == 0);
4621 self->ob_refcnt = 1;
4622
4623 /* Save the current exception, if any. */
4624 PyErr_Fetch(&error_type, &error_value, &error_traceback);
4625
4626 /* Execute __del__ method, if any. */
4627 del = lookup_maybe(self, "__del__", &del_str);
4628 if (del != NULL) {
4629 res = PyEval_CallObject(del, NULL);
4630 if (res == NULL)
4631 PyErr_WriteUnraisable(del);
4632 else
4633 Py_DECREF(res);
4634 Py_DECREF(del);
4635 }
4636
4637 /* Restore the saved exception. */
4638 PyErr_Restore(error_type, error_value, error_traceback);
4639
4640 /* Undo the temporary resurrection; can't use DECREF here, it would
4641 * cause a recursive call.
4642 */
4643 assert(self->ob_refcnt > 0);
4644 if (--self->ob_refcnt == 0)
4645 return; /* this is the normal path out */
4646
4647 /* __del__ resurrected it! Make it look like the original Py_DECREF
4648 * never happened.
4649 */
4650 {
4651 int refcnt = self->ob_refcnt;
4652 _Py_NewReference(self);
4653 self->ob_refcnt = refcnt;
4654 }
4655 assert(!PyType_IS_GC(self->ob_type) ||
4656 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
4657 /* If Py_REF_DEBUG, the original decref dropped _Py_RefTotal, but
4658 * _Py_NewReference bumped it again, so that's a wash.
4659 * If Py_TRACE_REFS, _Py_NewReference re-added self to the object
4660 * chain, so no more to do there either.
4661 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
4662 * _Py_NewReference bumped tp_allocs: both of those need to be
4663 * undone.
4664 */
4665#ifdef COUNT_ALLOCS
4666 --self->ob_type->tp_frees;
4667 --self->ob_type->tp_allocs;
4668#endif
4669}
4670
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004671
4672/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
Guido van Rossume5c691a2003-03-07 15:13:17 +00004673 functions. The offsets here are relative to the 'PyHeapTypeObject'
4674 structure, which incorporates the additional structures used for numbers,
4675 sequences and mappings.
4676 Note that multiple names may map to the same slot (e.g. __eq__,
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004677 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00004678 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
4679 terminated with an all-zero entry. (This table is further initialized and
4680 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004681
Guido van Rossum6d204072001-10-21 00:44:31 +00004682typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004683
4684#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00004685#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004686#undef ETSLOT
4687#undef SQSLOT
4688#undef MPSLOT
4689#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00004690#undef UNSLOT
4691#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004692#undef BINSLOT
4693#undef RBINSLOT
4694
Guido van Rossum6d204072001-10-21 00:44:31 +00004695#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004696 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
4697 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00004698#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
4699 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004700 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00004701#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Guido van Rossume5c691a2003-03-07 15:13:17 +00004702 {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004703 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00004704#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4705 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
4706#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4707 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
4708#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4709 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
4710#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4711 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
4712 "x." NAME "() <==> " DOC)
4713#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4714 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
4715 "x." NAME "(y) <==> x" DOC "y")
4716#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
4717 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
4718 "x." NAME "(y) <==> x" DOC "y")
4719#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
4720 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
4721 "x." NAME "(y) <==> y" DOC "x")
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004722
4723static slotdef slotdefs[] = {
Guido van Rossum6d204072001-10-21 00:44:31 +00004724 SQSLOT("__len__", sq_length, slot_sq_length, wrap_inquiry,
4725 "x.__len__() <==> len(x)"),
4726 SQSLOT("__add__", sq_concat, slot_sq_concat, wrap_binaryfunc,
4727 "x.__add__(y) <==> x+y"),
4728 SQSLOT("__mul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
4729 "x.__mul__(n) <==> x*n"),
4730 SQSLOT("__rmul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
4731 "x.__rmul__(n) <==> n*x"),
4732 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
4733 "x.__getitem__(y) <==> x[y]"),
4734 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_intintargfunc,
4735 "x.__getslice__(i, j) <==> x[i:j]"),
4736 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
4737 "x.__setitem__(i, y) <==> x[i]=y"),
4738 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
4739 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004740 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Guido van Rossum6d204072001-10-21 00:44:31 +00004741 wrap_intintobjargproc,
4742 "x.__setslice__(i, j, y) <==> x[i:j]=y"),
4743 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
4744 "x.__delslice__(i, j) <==> del x[i:j]"),
4745 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
4746 "x.__contains__(y) <==> y in x"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004747 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat,
Guido van Rossum6d204072001-10-21 00:44:31 +00004748 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004749 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat,
Guido van Rossum6d204072001-10-21 00:44:31 +00004750 wrap_intargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004751
Guido van Rossum6d204072001-10-21 00:44:31 +00004752 MPSLOT("__len__", mp_length, slot_mp_length, wrap_inquiry,
4753 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00004754 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004755 wrap_binaryfunc,
4756 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004757 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004758 wrap_objobjargproc,
4759 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004760 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004761 wrap_delitem,
4762 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004763
Guido van Rossum6d204072001-10-21 00:44:31 +00004764 BINSLOT("__add__", nb_add, slot_nb_add,
4765 "+"),
4766 RBINSLOT("__radd__", nb_add, slot_nb_add,
4767 "+"),
4768 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
4769 "-"),
4770 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
4771 "-"),
4772 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
4773 "*"),
4774 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
4775 "*"),
4776 BINSLOT("__div__", nb_divide, slot_nb_divide,
4777 "/"),
4778 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
4779 "/"),
4780 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
4781 "%"),
4782 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
4783 "%"),
4784 BINSLOT("__divmod__", nb_divmod, slot_nb_divmod,
4785 "divmod(x, y)"),
4786 RBINSLOT("__rdivmod__", nb_divmod, slot_nb_divmod,
4787 "divmod(y, x)"),
4788 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
4789 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
4790 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
4791 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
4792 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
4793 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
4794 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
4795 "abs(x)"),
Guido van Rossumdfce3bf2002-03-10 14:11:16 +00004796 UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquiry,
Guido van Rossum6d204072001-10-21 00:44:31 +00004797 "x != 0"),
4798 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
4799 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
4800 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
4801 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
4802 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
4803 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
4804 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
4805 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
4806 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
4807 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
4808 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
4809 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
4810 "x.__coerce__(y) <==> coerce(x, y)"),
4811 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
4812 "int(x)"),
4813 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
4814 "long(x)"),
4815 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
4816 "float(x)"),
4817 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
4818 "oct(x)"),
4819 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
4820 "hex(x)"),
4821 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
4822 wrap_binaryfunc, "+"),
4823 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
4824 wrap_binaryfunc, "-"),
4825 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
4826 wrap_binaryfunc, "*"),
4827 IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
4828 wrap_binaryfunc, "/"),
4829 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
4830 wrap_binaryfunc, "%"),
4831 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
Guido van Rossum6e5680f2002-10-15 01:01:53 +00004832 wrap_binaryfunc, "**"),
Guido van Rossum6d204072001-10-21 00:44:31 +00004833 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
4834 wrap_binaryfunc, "<<"),
4835 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
4836 wrap_binaryfunc, ">>"),
4837 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
4838 wrap_binaryfunc, "&"),
4839 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
4840 wrap_binaryfunc, "^"),
4841 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
4842 wrap_binaryfunc, "|"),
4843 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
4844 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
4845 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
4846 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
4847 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
4848 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
4849 IBSLOT("__itruediv__", nb_inplace_true_divide,
4850 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004851
Guido van Rossum6d204072001-10-21 00:44:31 +00004852 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
4853 "x.__str__() <==> str(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00004854 TPSLOT("__str__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00004855 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
4856 "x.__repr__() <==> repr(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00004857 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00004858 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
4859 "x.__cmp__(y) <==> cmp(x,y)"),
4860 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
4861 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00004862 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
4863 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004864 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00004865 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
4866 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
4867 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
4868 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
4869 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
4870 "x.__setattr__('name', value) <==> x.name = value"),
4871 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
4872 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
4873 "x.__delattr__('name') <==> del x.name"),
4874 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
4875 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
4876 "x.__lt__(y) <==> x<y"),
4877 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
4878 "x.__le__(y) <==> x<=y"),
4879 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
4880 "x.__eq__(y) <==> x==y"),
4881 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
4882 "x.__ne__(y) <==> x!=y"),
4883 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
4884 "x.__gt__(y) <==> x>y"),
4885 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
4886 "x.__ge__(y) <==> x>=y"),
4887 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
4888 "x.__iter__() <==> iter(x)"),
4889 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
4890 "x.next() -> the next value, or raise StopIteration"),
4891 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
4892 "descr.__get__(obj[, type]) -> value"),
4893 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
4894 "descr.__set__(obj, value)"),
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004895 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
4896 wrap_descr_delete, "descr.__delete__(obj)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00004897 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00004898 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00004899 "see x.__class__.__doc__ for signature",
4900 PyWrapperFlag_KEYWORDS),
4901 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004902 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004903 {NULL}
4904};
4905
Guido van Rossumc334df52002-04-04 23:44:47 +00004906/* Given a type pointer and an offset gotten from a slotdef entry, return a
4907 pointer to the actual slot. This is not quite the same as simply adding
4908 the offset to the type pointer, since it takes care to indirect through the
4909 proper indirection pointer (as_buffer, etc.); it returns NULL if the
4910 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004911static void **
4912slotptr(PyTypeObject *type, int offset)
4913{
4914 char *ptr;
4915
Guido van Rossume5c691a2003-03-07 15:13:17 +00004916 /* Note: this depends on the order of the members of PyHeapTypeObject! */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004917 assert(offset >= 0);
Guido van Rossume5c691a2003-03-07 15:13:17 +00004918 assert(offset < offsetof(PyHeapTypeObject, as_buffer));
4919 if (offset >= offsetof(PyHeapTypeObject, as_sequence)) {
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004920 ptr = (void *)type->tp_as_sequence;
Guido van Rossume5c691a2003-03-07 15:13:17 +00004921 offset -= offsetof(PyHeapTypeObject, as_sequence);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004922 }
Guido van Rossume5c691a2003-03-07 15:13:17 +00004923 else if (offset >= offsetof(PyHeapTypeObject, as_mapping)) {
Guido van Rossum09638c12002-06-13 19:17:46 +00004924 ptr = (void *)type->tp_as_mapping;
Guido van Rossume5c691a2003-03-07 15:13:17 +00004925 offset -= offsetof(PyHeapTypeObject, as_mapping);
Guido van Rossum09638c12002-06-13 19:17:46 +00004926 }
Guido van Rossume5c691a2003-03-07 15:13:17 +00004927 else if (offset >= offsetof(PyHeapTypeObject, as_number)) {
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004928 ptr = (void *)type->tp_as_number;
Guido van Rossume5c691a2003-03-07 15:13:17 +00004929 offset -= offsetof(PyHeapTypeObject, as_number);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004930 }
4931 else {
4932 ptr = (void *)type;
4933 }
4934 if (ptr != NULL)
4935 ptr += offset;
4936 return (void **)ptr;
4937}
Guido van Rossumf040ede2001-08-07 16:40:56 +00004938
Guido van Rossumc334df52002-04-04 23:44:47 +00004939/* Length of array of slotdef pointers used to store slots with the
4940 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
4941 the same __name__, for any __name__. Since that's a static property, it is
4942 appropriate to declare fixed-size arrays for this. */
4943#define MAX_EQUIV 10
4944
4945/* Return a slot pointer for a given name, but ONLY if the attribute has
4946 exactly one slot function. The name must be an interned string. */
4947static void **
4948resolve_slotdups(PyTypeObject *type, PyObject *name)
4949{
4950 /* XXX Maybe this could be optimized more -- but is it worth it? */
4951
4952 /* pname and ptrs act as a little cache */
4953 static PyObject *pname;
4954 static slotdef *ptrs[MAX_EQUIV];
4955 slotdef *p, **pp;
4956 void **res, **ptr;
4957
4958 if (pname != name) {
4959 /* Collect all slotdefs that match name into ptrs. */
4960 pname = name;
4961 pp = ptrs;
4962 for (p = slotdefs; p->name_strobj; p++) {
4963 if (p->name_strobj == name)
4964 *pp++ = p;
4965 }
4966 *pp = NULL;
4967 }
4968
4969 /* Look in all matching slots of the type; if exactly one of these has
4970 a filled-in slot, return its value. Otherwise return NULL. */
4971 res = NULL;
4972 for (pp = ptrs; *pp; pp++) {
4973 ptr = slotptr(type, (*pp)->offset);
4974 if (ptr == NULL || *ptr == NULL)
4975 continue;
4976 if (res != NULL)
4977 return NULL;
4978 res = ptr;
4979 }
4980 return res;
4981}
4982
4983/* Common code for update_these_slots() and fixup_slot_dispatchers(). This
4984 does some incredibly complex thinking and then sticks something into the
4985 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
4986 interests, and then stores a generic wrapper or a specific function into
4987 the slot.) Return a pointer to the next slotdef with a different offset,
4988 because that's convenient for fixup_slot_dispatchers(). */
4989static slotdef *
4990update_one_slot(PyTypeObject *type, slotdef *p)
4991{
4992 PyObject *descr;
4993 PyWrapperDescrObject *d;
4994 void *generic = NULL, *specific = NULL;
4995 int use_generic = 0;
4996 int offset = p->offset;
4997 void **ptr = slotptr(type, offset);
4998
4999 if (ptr == NULL) {
5000 do {
5001 ++p;
5002 } while (p->offset == offset);
5003 return p;
5004 }
5005 do {
5006 descr = _PyType_Lookup(type, p->name_strobj);
5007 if (descr == NULL)
5008 continue;
5009 if (descr->ob_type == &PyWrapperDescr_Type) {
5010 void **tptr = resolve_slotdups(type, p->name_strobj);
5011 if (tptr == NULL || tptr == ptr)
5012 generic = p->function;
5013 d = (PyWrapperDescrObject *)descr;
5014 if (d->d_base->wrapper == p->wrapper &&
5015 PyType_IsSubtype(type, d->d_type))
5016 {
5017 if (specific == NULL ||
5018 specific == d->d_wrapped)
5019 specific = d->d_wrapped;
5020 else
5021 use_generic = 1;
5022 }
5023 }
Guido van Rossum721f62e2002-08-09 02:14:34 +00005024 else if (descr->ob_type == &PyCFunction_Type &&
5025 PyCFunction_GET_FUNCTION(descr) ==
5026 (PyCFunction)tp_new_wrapper &&
5027 strcmp(p->name, "__new__") == 0)
5028 {
5029 /* The __new__ wrapper is not a wrapper descriptor,
5030 so must be special-cased differently.
5031 If we don't do this, creating an instance will
5032 always use slot_tp_new which will look up
5033 __new__ in the MRO which will call tp_new_wrapper
5034 which will look through the base classes looking
5035 for a static base and call its tp_new (usually
5036 PyType_GenericNew), after performing various
5037 sanity checks and constructing a new argument
5038 list. Cut all that nonsense short -- this speeds
5039 up instance creation tremendously. */
5040 specific = type->tp_new;
5041 /* XXX I'm not 100% sure that there isn't a hole
5042 in this reasoning that requires additional
5043 sanity checks. I'll buy the first person to
5044 point out a bug in this reasoning a beer. */
5045 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005046 else {
5047 use_generic = 1;
5048 generic = p->function;
5049 }
5050 } while ((++p)->offset == offset);
5051 if (specific && !use_generic)
5052 *ptr = specific;
5053 else
5054 *ptr = generic;
5055 return p;
5056}
5057
Guido van Rossum22b13872002-08-06 21:41:44 +00005058static int recurse_down_subclasses(PyTypeObject *type, slotdef **pp,
Jeremy Hylton938ace62002-07-17 16:30:39 +00005059 PyObject *name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005060
Guido van Rossumc334df52002-04-04 23:44:47 +00005061/* In the type, update the slots whose slotdefs are gathered in the pp0 array,
5062 and then do the same for all this type's subtypes. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005063static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005064update_these_slots(PyTypeObject *type, slotdef **pp0, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005065{
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005066 slotdef **pp;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005067
Guido van Rossumc334df52002-04-04 23:44:47 +00005068 for (pp = pp0; *pp; pp++)
5069 update_one_slot(type, *pp);
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005070 return recurse_down_subclasses(type, pp0, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005071}
5072
Guido van Rossumc334df52002-04-04 23:44:47 +00005073/* Update the slots whose slotdefs are gathered in the pp array in all (direct
5074 or indirect) subclasses of type. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005075static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005076recurse_down_subclasses(PyTypeObject *type, slotdef **pp, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005077{
5078 PyTypeObject *subclass;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005079 PyObject *ref, *subclasses, *dict;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005080 int i, n;
5081
5082 subclasses = type->tp_subclasses;
5083 if (subclasses == NULL)
5084 return 0;
5085 assert(PyList_Check(subclasses));
5086 n = PyList_GET_SIZE(subclasses);
5087 for (i = 0; i < n; i++) {
5088 ref = PyList_GET_ITEM(subclasses, i);
5089 assert(PyWeakref_CheckRef(ref));
5090 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
Guido van Rossum59e6c532002-06-14 02:27:07 +00005091 assert(subclass != NULL);
5092 if ((PyObject *)subclass == Py_None)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005093 continue;
5094 assert(PyType_Check(subclass));
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005095 /* Avoid recursing down into unaffected classes */
5096 dict = subclass->tp_dict;
5097 if (dict != NULL && PyDict_Check(dict) &&
5098 PyDict_GetItem(dict, name) != NULL)
5099 continue;
5100 if (update_these_slots(subclass, pp, name) < 0)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005101 return -1;
5102 }
5103 return 0;
5104}
5105
Guido van Rossumc334df52002-04-04 23:44:47 +00005106/* Comparison function for qsort() to compare slotdefs by their offset, and
5107 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005108static int
5109slotdef_cmp(const void *aa, const void *bb)
5110{
5111 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
5112 int c = a->offset - b->offset;
5113 if (c != 0)
5114 return c;
5115 else
5116 return a - b;
5117}
5118
Guido van Rossumc334df52002-04-04 23:44:47 +00005119/* Initialize the slotdefs table by adding interned string objects for the
5120 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005121static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005122init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005123{
5124 slotdef *p;
5125 static int initialized = 0;
5126
5127 if (initialized)
5128 return;
5129 for (p = slotdefs; p->name; p++) {
5130 p->name_strobj = PyString_InternFromString(p->name);
5131 if (!p->name_strobj)
Guido van Rossumc334df52002-04-04 23:44:47 +00005132 Py_FatalError("Out of memory interning slotdef names");
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005133 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005134 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
5135 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005136 initialized = 1;
5137}
5138
Guido van Rossumc334df52002-04-04 23:44:47 +00005139/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005140static int
5141update_slot(PyTypeObject *type, PyObject *name)
5142{
Guido van Rossumc334df52002-04-04 23:44:47 +00005143 slotdef *ptrs[MAX_EQUIV];
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005144 slotdef *p;
5145 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005146 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005147
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005148 init_slotdefs();
5149 pp = ptrs;
5150 for (p = slotdefs; p->name; p++) {
5151 /* XXX assume name is interned! */
5152 if (p->name_strobj == name)
5153 *pp++ = p;
5154 }
5155 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005156 for (pp = ptrs; *pp; pp++) {
5157 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005158 offset = p->offset;
5159 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005160 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005161 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005162 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005163 if (ptrs[0] == NULL)
5164 return 0; /* Not an attribute that affects any slots */
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005165 return update_these_slots(type, ptrs, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005166}
5167
Guido van Rossumc334df52002-04-04 23:44:47 +00005168/* Store the proper functions in the slot dispatches at class (type)
5169 definition time, based upon which operations the class overrides in its
5170 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00005171static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005172fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005173{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005174 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005175
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005176 init_slotdefs();
Guido van Rossumc334df52002-04-04 23:44:47 +00005177 for (p = slotdefs; p->name; )
5178 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005179}
Guido van Rossum705f0f52001-08-24 16:47:00 +00005180
Michael W. Hudson98bbc492002-11-26 14:47:27 +00005181static void
5182update_all_slots(PyTypeObject* type)
5183{
5184 slotdef *p;
5185
5186 init_slotdefs();
5187 for (p = slotdefs; p->name; p++) {
5188 /* update_slot returns int but can't actually fail */
5189 update_slot(type, p->name_strobj);
5190 }
5191}
5192
Guido van Rossum6d204072001-10-21 00:44:31 +00005193/* This function is called by PyType_Ready() to populate the type's
5194 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00005195 function slot (like tp_repr) that's defined in the type, one or more
5196 corresponding descriptors are added in the type's tp_dict dictionary
5197 under the appropriate name (like __repr__). Some function slots
5198 cause more than one descriptor to be added (for example, the nb_add
5199 slot adds both __add__ and __radd__ descriptors) and some function
5200 slots compete for the same descriptor (for example both sq_item and
5201 mp_subscript generate a __getitem__ descriptor).
5202
5203 In the latter case, the first slotdef entry encoutered wins. Since
Guido van Rossume5c691a2003-03-07 15:13:17 +00005204 slotdef entries are sorted by the offset of the slot in the
5205 PyHeapTypeObject, this gives us some control over disambiguating
5206 between competing slots: the members of PyHeapTypeObject are listed from most
Guido van Rossum09638c12002-06-13 19:17:46 +00005207 general to least general, so the most general slot is preferred. In
5208 particular, because as_mapping comes before as_sequence, for a type
5209 that defines both mp_subscript and sq_item, mp_subscript wins.
5210
5211 This only adds new descriptors and doesn't overwrite entries in
5212 tp_dict that were previously defined. The descriptors contain a
5213 reference to the C function they must call, so that it's safe if they
5214 are copied into a subtype's __dict__ and the subtype has a different
5215 C function in its slot -- calling the method defined by the
5216 descriptor will call the C function that was used to create it,
5217 rather than the C function present in the slot when it is called.
5218 (This is important because a subtype may have a C function in the
5219 slot that calls the method from the dictionary, and we want to avoid
5220 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00005221
5222static int
5223add_operators(PyTypeObject *type)
5224{
5225 PyObject *dict = type->tp_dict;
5226 slotdef *p;
5227 PyObject *descr;
5228 void **ptr;
5229
5230 init_slotdefs();
5231 for (p = slotdefs; p->name; p++) {
5232 if (p->wrapper == NULL)
5233 continue;
5234 ptr = slotptr(type, p->offset);
5235 if (!ptr || !*ptr)
5236 continue;
5237 if (PyDict_GetItem(dict, p->name_strobj))
5238 continue;
5239 descr = PyDescr_NewWrapper(type, p, *ptr);
5240 if (descr == NULL)
5241 return -1;
5242 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
5243 return -1;
5244 Py_DECREF(descr);
5245 }
5246 if (type->tp_new != NULL) {
5247 if (add_tp_new_wrapper(type) < 0)
5248 return -1;
5249 }
5250 return 0;
5251}
5252
Guido van Rossum705f0f52001-08-24 16:47:00 +00005253
5254/* Cooperative 'super' */
5255
5256typedef struct {
5257 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00005258 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005259 PyObject *obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005260 PyTypeObject *obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005261} superobject;
5262
Guido van Rossum6f799372001-09-20 20:46:19 +00005263static PyMemberDef super_members[] = {
5264 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
5265 "the class invoking super()"},
5266 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
5267 "the instance invoking super(); may be None"},
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005268 {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
5269 "the type of the the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005270 {0}
5271};
5272
Guido van Rossum705f0f52001-08-24 16:47:00 +00005273static void
5274super_dealloc(PyObject *self)
5275{
5276 superobject *su = (superobject *)self;
5277
Guido van Rossum048eb752001-10-02 21:24:57 +00005278 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005279 Py_XDECREF(su->obj);
5280 Py_XDECREF(su->type);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005281 Py_XDECREF(su->obj_type);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005282 self->ob_type->tp_free(self);
5283}
5284
5285static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005286super_repr(PyObject *self)
5287{
5288 superobject *su = (superobject *)self;
5289
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005290 if (su->obj_type)
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005291 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005292 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005293 su->type ? su->type->tp_name : "NULL",
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005294 su->obj_type->tp_name);
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005295 else
5296 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005297 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005298 su->type ? su->type->tp_name : "NULL");
5299}
5300
5301static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00005302super_getattro(PyObject *self, PyObject *name)
5303{
5304 superobject *su = (superobject *)self;
5305
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005306 if (su->obj_type != NULL) {
Tim Petersa91e9642001-11-14 23:32:33 +00005307 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005308 PyTypeObject *starttype;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005309 descrgetfunc f;
5310 int i, n;
5311
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005312 starttype = su->obj_type;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005313 mro = starttype->tp_mro;
5314
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005315 if (mro == NULL)
5316 n = 0;
5317 else {
5318 assert(PyTuple_Check(mro));
5319 n = PyTuple_GET_SIZE(mro);
5320 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005321 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00005322 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00005323 break;
5324 }
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005325#if 0
Guido van Rossume705ef12001-08-29 15:47:06 +00005326 if (i >= n && PyType_Check(su->obj)) {
Guido van Rossum155db9a2002-04-02 17:53:47 +00005327 starttype = (PyTypeObject *)(su->obj);
5328 mro = starttype->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005329 if (mro == NULL)
5330 n = 0;
5331 else {
5332 assert(PyTuple_Check(mro));
5333 n = PyTuple_GET_SIZE(mro);
5334 }
Guido van Rossume705ef12001-08-29 15:47:06 +00005335 for (i = 0; i < n; i++) {
5336 if ((PyObject *)(su->type) ==
5337 PyTuple_GET_ITEM(mro, i))
5338 break;
5339 }
Guido van Rossume705ef12001-08-29 15:47:06 +00005340 }
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005341#endif
Guido van Rossum705f0f52001-08-24 16:47:00 +00005342 i++;
5343 res = NULL;
5344 for (; i < n; i++) {
5345 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00005346 if (PyType_Check(tmp))
5347 dict = ((PyTypeObject *)tmp)->tp_dict;
5348 else if (PyClass_Check(tmp))
5349 dict = ((PyClassObject *)tmp)->cl_dict;
5350 else
5351 continue;
5352 res = PyDict_GetItem(dict, name);
Guido van Rossum5b443c62001-12-03 15:38:28 +00005353 if (res != NULL && !PyDescr_IsData(res)) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00005354 Py_INCREF(res);
5355 f = res->ob_type->tp_descr_get;
5356 if (f != NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00005357 tmp = f(res, su->obj,
5358 (PyObject *)starttype);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005359 Py_DECREF(res);
5360 res = tmp;
5361 }
5362 return res;
5363 }
5364 }
5365 }
5366 return PyObject_GenericGetAttr(self, name);
5367}
5368
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005369static PyTypeObject *
Guido van Rossum5b443c62001-12-03 15:38:28 +00005370supercheck(PyTypeObject *type, PyObject *obj)
5371{
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005372 /* Check that a super() call makes sense. Return a type object.
5373
5374 obj can be a new-style class, or an instance of one:
5375
5376 - If it is a class, it must be a subclass of 'type'. This case is
5377 used for class methods; the return value is obj.
5378
5379 - If it is an instance, it must be an instance of 'type'. This is
5380 the normal case; the return value is obj.__class__.
5381
5382 But... when obj is an instance, we want to allow for the case where
5383 obj->ob_type is not a subclass of type, but obj.__class__ is!
5384 This will allow using super() with a proxy for obj.
5385 */
5386
Guido van Rossum8e80a722003-02-18 19:22:22 +00005387 /* Check for first bullet above (special case) */
5388 if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
5389 Py_INCREF(obj);
5390 return (PyTypeObject *)obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005391 }
Guido van Rossum8e80a722003-02-18 19:22:22 +00005392
5393 /* Normal case */
5394 if (PyType_IsSubtype(obj->ob_type, type)) {
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005395 Py_INCREF(obj->ob_type);
5396 return obj->ob_type;
5397 }
5398 else {
5399 /* Try the slow way */
5400 static PyObject *class_str = NULL;
5401 PyObject *class_attr;
5402
5403 if (class_str == NULL) {
5404 class_str = PyString_FromString("__class__");
5405 if (class_str == NULL)
5406 return NULL;
5407 }
5408
5409 class_attr = PyObject_GetAttr(obj, class_str);
5410
5411 if (class_attr != NULL &&
5412 PyType_Check(class_attr) &&
5413 (PyTypeObject *)class_attr != obj->ob_type)
5414 {
5415 int ok = PyType_IsSubtype(
5416 (PyTypeObject *)class_attr, type);
5417 if (ok)
5418 return (PyTypeObject *)class_attr;
5419 }
5420
5421 if (class_attr == NULL)
5422 PyErr_Clear();
5423 else
5424 Py_DECREF(class_attr);
5425 }
5426
Tim Peters97e5ff52003-02-18 19:32:50 +00005427 PyErr_SetString(PyExc_TypeError,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005428 "super(type, obj): "
5429 "obj must be an instance or subtype of type");
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005430 return NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005431}
5432
Guido van Rossum705f0f52001-08-24 16:47:00 +00005433static PyObject *
5434super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5435{
5436 superobject *su = (superobject *)self;
5437 superobject *new;
5438
5439 if (obj == NULL || obj == Py_None || su->obj != NULL) {
5440 /* Not binding to an object, or already bound */
5441 Py_INCREF(self);
5442 return self;
5443 }
Guido van Rossum5b443c62001-12-03 15:38:28 +00005444 if (su->ob_type != &PySuper_Type)
5445 /* If su is an instance of a subclass of super,
5446 call its type */
5447 return PyObject_CallFunction((PyObject *)su->ob_type,
5448 "OO", su->type, obj);
5449 else {
5450 /* Inline the common case */
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005451 PyTypeObject *obj_type = supercheck(su->type, obj);
5452 if (obj_type == NULL)
Guido van Rossum5b443c62001-12-03 15:38:28 +00005453 return NULL;
5454 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
5455 NULL, NULL);
5456 if (new == NULL)
5457 return NULL;
5458 Py_INCREF(su->type);
5459 Py_INCREF(obj);
5460 new->type = su->type;
5461 new->obj = obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005462 new->obj_type = obj_type;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005463 return (PyObject *)new;
5464 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005465}
5466
5467static int
5468super_init(PyObject *self, PyObject *args, PyObject *kwds)
5469{
5470 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00005471 PyTypeObject *type;
5472 PyObject *obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005473 PyTypeObject *obj_type = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005474
5475 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
5476 return -1;
5477 if (obj == Py_None)
5478 obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005479 if (obj != NULL) {
5480 obj_type = supercheck(type, obj);
5481 if (obj_type == NULL)
5482 return -1;
5483 Py_INCREF(obj);
5484 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005485 Py_INCREF(type);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005486 su->type = type;
5487 su->obj = obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005488 su->obj_type = obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005489 return 0;
5490}
5491
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005492PyDoc_STRVAR(super_doc,
Guido van Rossum705f0f52001-08-24 16:47:00 +00005493"super(type) -> unbound super object\n"
5494"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00005495"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00005496"Typical use to call a cooperative superclass method:\n"
5497"class C(B):\n"
5498" def meth(self, arg):\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005499" super(C, self).meth(arg)");
Guido van Rossum705f0f52001-08-24 16:47:00 +00005500
Guido van Rossum048eb752001-10-02 21:24:57 +00005501static int
5502super_traverse(PyObject *self, visitproc visit, void *arg)
5503{
5504 superobject *su = (superobject *)self;
5505 int err;
5506
5507#define VISIT(SLOT) \
5508 if (SLOT) { \
5509 err = visit((PyObject *)(SLOT), arg); \
5510 if (err) \
5511 return err; \
5512 }
5513
5514 VISIT(su->obj);
5515 VISIT(su->type);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005516 VISIT(su->obj_type);
Guido van Rossum048eb752001-10-02 21:24:57 +00005517
5518#undef VISIT
5519
5520 return 0;
5521}
5522
Guido van Rossum705f0f52001-08-24 16:47:00 +00005523PyTypeObject PySuper_Type = {
5524 PyObject_HEAD_INIT(&PyType_Type)
5525 0, /* ob_size */
5526 "super", /* tp_name */
5527 sizeof(superobject), /* tp_basicsize */
5528 0, /* tp_itemsize */
5529 /* methods */
5530 super_dealloc, /* tp_dealloc */
5531 0, /* tp_print */
5532 0, /* tp_getattr */
5533 0, /* tp_setattr */
5534 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005535 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005536 0, /* tp_as_number */
5537 0, /* tp_as_sequence */
5538 0, /* tp_as_mapping */
5539 0, /* tp_hash */
5540 0, /* tp_call */
5541 0, /* tp_str */
5542 super_getattro, /* tp_getattro */
5543 0, /* tp_setattro */
5544 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00005545 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
5546 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005547 super_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00005548 super_traverse, /* tp_traverse */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005549 0, /* tp_clear */
5550 0, /* tp_richcompare */
5551 0, /* tp_weaklistoffset */
5552 0, /* tp_iter */
5553 0, /* tp_iternext */
5554 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005555 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005556 0, /* tp_getset */
5557 0, /* tp_base */
5558 0, /* tp_dict */
5559 super_descr_get, /* tp_descr_get */
5560 0, /* tp_descr_set */
5561 0, /* tp_dictoffset */
5562 super_init, /* tp_init */
5563 PyType_GenericAlloc, /* tp_alloc */
5564 PyType_GenericNew, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00005565 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005566};