blob: c2ed180499e60e5cb6a69ac9f651e32a4657d7e6 [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* Type object implementation */
2
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003#include "Python.h"
Tim Peters6d6c1a32001-08-02 04:15:00 +00004#include "structmember.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00005
Guido van Rossum9923ffe2002-06-04 19:52:53 +00006#include <ctype.h>
7
Guido van Rossum6f799372001-09-20 20:46:19 +00008static PyMemberDef type_members[] = {
Tim Peters6d6c1a32001-08-02 04:15:00 +00009 {"__basicsize__", T_INT, offsetof(PyTypeObject,tp_basicsize),READONLY},
10 {"__itemsize__", T_INT, offsetof(PyTypeObject, tp_itemsize), READONLY},
11 {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY},
Guido van Rossum9676b222001-08-17 20:32:36 +000012 {"__weakrefoffset__", T_LONG,
Tim Peters6d6c1a32001-08-02 04:15:00 +000013 offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
14 {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY},
15 {"__dictoffset__", T_LONG,
16 offsetof(PyTypeObject, tp_dictoffset), READONLY},
Tim Peters6d6c1a32001-08-02 04:15:00 +000017 {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY},
18 {0}
19};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000020
Guido van Rossumc0b618a1997-05-02 03:12:38 +000021static PyObject *
Guido van Rossumc3542212001-08-16 09:18:56 +000022type_name(PyTypeObject *type, void *context)
23{
24 char *s;
25
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +000026 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
Guido van Rossume5c691a2003-03-07 15:13:17 +000027 PyHeapTypeObject* et = (PyHeapTypeObject*)type;
Tim Petersea7f75d2002-12-07 21:39:16 +000028
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +000029 Py_INCREF(et->name);
30 return et->name;
31 }
32 else {
33 s = strrchr(type->tp_name, '.');
34 if (s == NULL)
35 s = type->tp_name;
36 else
37 s++;
38 return PyString_FromString(s);
39 }
Guido van Rossumc3542212001-08-16 09:18:56 +000040}
41
Michael W. Hudson98bbc492002-11-26 14:47:27 +000042static int
43type_set_name(PyTypeObject *type, PyObject *value, void *context)
44{
Guido van Rossume5c691a2003-03-07 15:13:17 +000045 PyHeapTypeObject* et;
Michael W. Hudson98bbc492002-11-26 14:47:27 +000046
47 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
48 PyErr_Format(PyExc_TypeError,
49 "can't set %s.__name__", type->tp_name);
50 return -1;
51 }
52 if (!value) {
53 PyErr_Format(PyExc_TypeError,
54 "can't delete %s.__name__", type->tp_name);
55 return -1;
56 }
57 if (!PyString_Check(value)) {
58 PyErr_Format(PyExc_TypeError,
59 "can only assign string to %s.__name__, not '%s'",
60 type->tp_name, value->ob_type->tp_name);
61 return -1;
62 }
Tim Petersea7f75d2002-12-07 21:39:16 +000063 if (strlen(PyString_AS_STRING(value))
Michael W. Hudson98bbc492002-11-26 14:47:27 +000064 != (size_t)PyString_GET_SIZE(value)) {
65 PyErr_Format(PyExc_ValueError,
66 "__name__ must not contain null bytes");
67 return -1;
68 }
69
Guido van Rossume5c691a2003-03-07 15:13:17 +000070 et = (PyHeapTypeObject*)type;
Michael W. Hudson98bbc492002-11-26 14:47:27 +000071
72 Py_INCREF(value);
73
74 Py_DECREF(et->name);
75 et->name = value;
76
77 type->tp_name = PyString_AS_STRING(value);
78
79 return 0;
80}
81
Guido van Rossumc3542212001-08-16 09:18:56 +000082static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +000083type_module(PyTypeObject *type, void *context)
Guido van Rossum29ca26e1995-01-07 11:58:15 +000084{
Guido van Rossumc3542212001-08-16 09:18:56 +000085 PyObject *mod;
86 char *s;
87
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +000088 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
89 mod = PyDict_GetItemString(type->tp_dict, "__module__");
90 Py_XINCREF(mod);
Guido van Rossumc3542212001-08-16 09:18:56 +000091 return mod;
92 }
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +000093 else {
94 s = strrchr(type->tp_name, '.');
95 if (s != NULL)
96 return PyString_FromStringAndSize(
97 type->tp_name, (int)(s - type->tp_name));
98 return PyString_FromString("__builtin__");
99 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000100}
101
Guido van Rossum3926a632001-09-25 16:25:58 +0000102static int
103type_set_module(PyTypeObject *type, PyObject *value, void *context)
104{
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000105 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
Guido van Rossum3926a632001-09-25 16:25:58 +0000106 PyErr_Format(PyExc_TypeError,
107 "can't set %s.__module__", type->tp_name);
108 return -1;
109 }
110 if (!value) {
111 PyErr_Format(PyExc_TypeError,
112 "can't delete %s.__module__", type->tp_name);
113 return -1;
114 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000115
Guido van Rossum3926a632001-09-25 16:25:58 +0000116 return PyDict_SetItemString(type->tp_dict, "__module__", value);
117}
118
Tim Peters6d6c1a32001-08-02 04:15:00 +0000119static PyObject *
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000120type_get_bases(PyTypeObject *type, void *context)
121{
122 Py_INCREF(type->tp_bases);
123 return type->tp_bases;
124}
125
126static PyTypeObject *best_base(PyObject *);
127static int mro_internal(PyTypeObject *);
128static int compatible_for_assignment(PyTypeObject *, PyTypeObject *, char *);
129static int add_subclass(PyTypeObject*, PyTypeObject*);
130static void remove_subclass(PyTypeObject *, PyTypeObject *);
131static void update_all_slots(PyTypeObject *);
132
133static int
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000134mro_subclasses(PyTypeObject *type, PyObject* temp)
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000135{
136 PyTypeObject *subclass;
137 PyObject *ref, *subclasses, *old_mro;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000138 int i, n;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000139
140 subclasses = type->tp_subclasses;
141 if (subclasses == NULL)
142 return 0;
143 assert(PyList_Check(subclasses));
144 n = PyList_GET_SIZE(subclasses);
145 for (i = 0; i < n; i++) {
146 ref = PyList_GET_ITEM(subclasses, i);
147 assert(PyWeakref_CheckRef(ref));
148 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
149 assert(subclass != NULL);
150 if ((PyObject *)subclass == Py_None)
151 continue;
152 assert(PyType_Check(subclass));
153 old_mro = subclass->tp_mro;
154 if (mro_internal(subclass) < 0) {
155 subclass->tp_mro = old_mro;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000156 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000157 }
158 else {
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000159 PyObject* tuple;
160 tuple = Py_BuildValue("OO", subclass, old_mro);
161 if (!tuple)
162 return -1;
163 if (PyList_Append(temp, tuple) < 0)
164 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000165 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000166 if (mro_subclasses(subclass, temp) < 0)
167 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000168 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000169 return 0;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000170}
171
172static int
173type_set_bases(PyTypeObject *type, PyObject *value, void *context)
174{
175 int i, r = 0;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000176 PyObject *ob, *temp;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000177 PyTypeObject *new_base, *old_base;
178 PyObject *old_bases, *old_mro;
179
180 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
181 PyErr_Format(PyExc_TypeError,
182 "can't set %s.__bases__", type->tp_name);
183 return -1;
184 }
185 if (!value) {
186 PyErr_Format(PyExc_TypeError,
187 "can't delete %s.__bases__", type->tp_name);
188 return -1;
189 }
190 if (!PyTuple_Check(value)) {
191 PyErr_Format(PyExc_TypeError,
192 "can only assign tuple to %s.__bases__, not %s",
193 type->tp_name, value->ob_type->tp_name);
194 return -1;
195 }
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +0000196 if (PyTuple_GET_SIZE(value) == 0) {
197 PyErr_Format(PyExc_TypeError,
198 "can only assign non-empty tuple to %s.__bases__, not ()",
199 type->tp_name);
200 return -1;
201 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000202 for (i = 0; i < PyTuple_GET_SIZE(value); i++) {
203 ob = PyTuple_GET_ITEM(value, i);
204 if (!PyClass_Check(ob) && !PyType_Check(ob)) {
205 PyErr_Format(
206 PyExc_TypeError,
207 "%s.__bases__ must be tuple of old- or new-style classes, not '%s'",
208 type->tp_name, ob->ob_type->tp_name);
209 return -1;
210 }
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +0000211 if (PyType_Check(ob)) {
212 if (PyType_IsSubtype((PyTypeObject*)ob, type)) {
213 PyErr_SetString(PyExc_TypeError,
214 "a __bases__ item causes an inheritance cycle");
215 return -1;
216 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000217 }
218 }
219
220 new_base = best_base(value);
221
222 if (!new_base) {
223 return -1;
224 }
225
226 if (!compatible_for_assignment(type->tp_base, new_base, "__bases__"))
227 return -1;
228
229 Py_INCREF(new_base);
230 Py_INCREF(value);
231
232 old_bases = type->tp_bases;
233 old_base = type->tp_base;
234 old_mro = type->tp_mro;
235
236 type->tp_bases = value;
237 type->tp_base = new_base;
238
239 if (mro_internal(type) < 0) {
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000240 goto bail;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000241 }
242
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000243 temp = PyList_New(0);
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000244 if (!temp)
245 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000246
247 r = mro_subclasses(type, temp);
248
249 if (r < 0) {
250 for (i = 0; i < PyList_Size(temp); i++) {
251 PyTypeObject* cls;
252 PyObject* mro;
253 PyArg_ParseTuple(PyList_GetItem(temp, i),
254 "OO", &cls, &mro);
255 Py_DECREF(cls->tp_mro);
256 cls->tp_mro = mro;
257 Py_INCREF(cls->tp_mro);
258 }
259 Py_DECREF(temp);
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000260 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000261 }
262
263 Py_DECREF(temp);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000264
265 /* any base that was in __bases__ but now isn't, we
Raymond Hettingera8285862002-12-14 17:17:56 +0000266 need to remove |type| from its tp_subclasses.
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000267 conversely, any class now in __bases__ that wasn't
Raymond Hettingera8285862002-12-14 17:17:56 +0000268 needs to have |type| added to its subclasses. */
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000269
270 /* for now, sod that: just remove from all old_bases,
271 add to all new_bases */
272
273 for (i = PyTuple_GET_SIZE(old_bases) - 1; i >= 0; i--) {
274 ob = PyTuple_GET_ITEM(old_bases, i);
275 if (PyType_Check(ob)) {
276 remove_subclass(
277 (PyTypeObject*)ob, type);
278 }
279 }
280
281 for (i = PyTuple_GET_SIZE(value) - 1; i >= 0; i--) {
282 ob = PyTuple_GET_ITEM(value, i);
283 if (PyType_Check(ob)) {
284 if (add_subclass((PyTypeObject*)ob, type) < 0)
285 r = -1;
286 }
287 }
288
289 update_all_slots(type);
290
291 Py_DECREF(old_bases);
292 Py_DECREF(old_base);
293 Py_DECREF(old_mro);
294
295 return r;
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000296
297 bail:
298 type->tp_bases = old_bases;
299 type->tp_base = old_base;
300 type->tp_mro = old_mro;
Tim Petersea7f75d2002-12-07 21:39:16 +0000301
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000302 Py_DECREF(value);
303 Py_DECREF(new_base);
Tim Petersea7f75d2002-12-07 21:39:16 +0000304
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000305 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000306}
307
308static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000309type_dict(PyTypeObject *type, void *context)
310{
311 if (type->tp_dict == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000312 Py_INCREF(Py_None);
313 return Py_None;
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000314 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000315 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000316}
317
Tim Peters24008312002-03-17 18:56:20 +0000318static PyObject *
319type_get_doc(PyTypeObject *type, void *context)
320{
321 PyObject *result;
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000322 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL)
Tim Peters24008312002-03-17 18:56:20 +0000323 return PyString_FromString(type->tp_doc);
Tim Peters24008312002-03-17 18:56:20 +0000324 result = PyDict_GetItemString(type->tp_dict, "__doc__");
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000325 if (result == NULL) {
326 result = Py_None;
327 Py_INCREF(result);
328 }
329 else if (result->ob_type->tp_descr_get) {
Tim Peters2b858972002-04-18 04:12:28 +0000330 result = result->ob_type->tp_descr_get(result, NULL,
331 (PyObject *)type);
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000332 }
333 else {
334 Py_INCREF(result);
335 }
Tim Peters24008312002-03-17 18:56:20 +0000336 return result;
337}
338
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000339static PyGetSetDef type_getsets[] = {
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000340 {"__name__", (getter)type_name, (setter)type_set_name, NULL},
341 {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL},
Guido van Rossum3926a632001-09-25 16:25:58 +0000342 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000343 {"__dict__", (getter)type_dict, NULL, NULL},
Tim Peters24008312002-03-17 18:56:20 +0000344 {"__doc__", (getter)type_get_doc, NULL, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000345 {0}
346};
347
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000348static int
349type_compare(PyObject *v, PyObject *w)
350{
351 /* This is called with type objects only. So we
352 can just compare the addresses. */
353 Py_uintptr_t vv = (Py_uintptr_t)v;
354 Py_uintptr_t ww = (Py_uintptr_t)w;
355 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
356}
357
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000358static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000359type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000360{
Barry Warsaw7ce36942001-08-24 18:34:26 +0000361 PyObject *mod, *name, *rtn;
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000362 char *kind;
Guido van Rossumc3542212001-08-16 09:18:56 +0000363
364 mod = type_module(type, NULL);
365 if (mod == NULL)
366 PyErr_Clear();
367 else if (!PyString_Check(mod)) {
368 Py_DECREF(mod);
369 mod = NULL;
370 }
371 name = type_name(type, NULL);
372 if (name == NULL)
373 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000374
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000375 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
376 kind = "class";
377 else
378 kind = "type";
379
Barry Warsaw7ce36942001-08-24 18:34:26 +0000380 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__")) {
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000381 rtn = PyString_FromFormat("<%s '%s.%s'>",
382 kind,
Barry Warsaw7ce36942001-08-24 18:34:26 +0000383 PyString_AS_STRING(mod),
384 PyString_AS_STRING(name));
385 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000386 else
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000387 rtn = PyString_FromFormat("<%s '%s'>", kind, type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000388
Guido van Rossumc3542212001-08-16 09:18:56 +0000389 Py_XDECREF(mod);
390 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000391 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000392}
393
Tim Peters6d6c1a32001-08-02 04:15:00 +0000394static PyObject *
395type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
396{
397 PyObject *obj;
398
399 if (type->tp_new == NULL) {
400 PyErr_Format(PyExc_TypeError,
401 "cannot create '%.100s' instances",
402 type->tp_name);
403 return NULL;
404 }
405
Tim Peters3f996e72001-09-13 19:18:27 +0000406 obj = type->tp_new(type, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000407 if (obj != NULL) {
Guido van Rossumf76de622001-10-18 15:49:21 +0000408 /* Ugly exception: when the call was type(something),
409 don't call tp_init on the result. */
410 if (type == &PyType_Type &&
411 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
412 (kwds == NULL ||
413 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
414 return obj;
Guido van Rossum8ace1ab2002-04-06 01:05:01 +0000415 /* If the returned object is not an instance of type,
416 it won't be initialized. */
417 if (!PyType_IsSubtype(obj->ob_type, type))
418 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000419 type = obj->ob_type;
Jeremy Hylton719841e2002-07-16 19:39:38 +0000420 if (PyType_HasFeature(type, Py_TPFLAGS_HAVE_CLASS) &&
421 type->tp_init != NULL &&
Tim Peters6d6c1a32001-08-02 04:15:00 +0000422 type->tp_init(obj, args, kwds) < 0) {
423 Py_DECREF(obj);
424 obj = NULL;
425 }
426 }
427 return obj;
428}
429
430PyObject *
431PyType_GenericAlloc(PyTypeObject *type, int nitems)
432{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000433 PyObject *obj;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000434 const size_t size = _PyObject_VAR_SIZE(type, nitems+1);
435 /* note that we need to add one, for the sentinel */
Tim Peters406fe3b2001-10-06 19:04:01 +0000436
437 if (PyType_IS_GC(type))
Neil Schemenauer09a2ae52002-04-12 03:06:53 +0000438 obj = _PyObject_GC_Malloc(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000439 else
Neil Schemenauerc806c882001-08-29 23:54:54 +0000440 obj = PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000441
Neil Schemenauerc806c882001-08-29 23:54:54 +0000442 if (obj == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000443 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000444
Neil Schemenauerc806c882001-08-29 23:54:54 +0000445 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000446
Tim Peters6d6c1a32001-08-02 04:15:00 +0000447 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
448 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000449
Tim Peters6d6c1a32001-08-02 04:15:00 +0000450 if (type->tp_itemsize == 0)
451 PyObject_INIT(obj, type);
452 else
453 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000454
Tim Peters6d6c1a32001-08-02 04:15:00 +0000455 if (PyType_IS_GC(type))
Neil Schemenauerc806c882001-08-29 23:54:54 +0000456 _PyObject_GC_TRACK(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000457 return obj;
458}
459
460PyObject *
461PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
462{
463 return type->tp_alloc(type, 0);
464}
465
Guido van Rossum9475a232001-10-05 20:51:39 +0000466/* Helpers for subtyping */
467
468static int
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000469traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
470{
471 int i, n;
472 PyMemberDef *mp;
473
474 n = type->ob_size;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000475 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000476 for (i = 0; i < n; i++, mp++) {
477 if (mp->type == T_OBJECT_EX) {
478 char *addr = (char *)self + mp->offset;
479 PyObject *obj = *(PyObject **)addr;
480 if (obj != NULL) {
481 int err = visit(obj, arg);
482 if (err)
483 return err;
484 }
485 }
486 }
487 return 0;
488}
489
490static int
Guido van Rossum9475a232001-10-05 20:51:39 +0000491subtype_traverse(PyObject *self, visitproc visit, void *arg)
492{
493 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000494 traverseproc basetraverse;
Guido van Rossum9475a232001-10-05 20:51:39 +0000495
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000496 /* Find the nearest base with a different tp_traverse,
497 and traverse slots while we're at it */
Guido van Rossum9475a232001-10-05 20:51:39 +0000498 type = self->ob_type;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000499 base = type;
500 while ((basetraverse = base->tp_traverse) == subtype_traverse) {
501 if (base->ob_size) {
502 int err = traverse_slots(base, self, visit, arg);
503 if (err)
504 return err;
505 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000506 base = base->tp_base;
507 assert(base);
508 }
509
510 if (type->tp_dictoffset != base->tp_dictoffset) {
511 PyObject **dictptr = _PyObject_GetDictPtr(self);
512 if (dictptr && *dictptr) {
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000513 int err = visit(*dictptr, arg);
Guido van Rossum9475a232001-10-05 20:51:39 +0000514 if (err)
515 return err;
516 }
517 }
518
Guido van Rossuma3862092002-06-10 15:24:42 +0000519 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
520 /* For a heaptype, the instances count as references
521 to the type. Traverse the type so the collector
522 can find cycles involving this link. */
523 int err = visit((PyObject *)type, arg);
524 if (err)
525 return err;
526 }
527
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000528 if (basetraverse)
529 return basetraverse(self, visit, arg);
530 return 0;
531}
532
533static void
534clear_slots(PyTypeObject *type, PyObject *self)
535{
536 int i, n;
537 PyMemberDef *mp;
538
539 n = type->ob_size;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000540 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000541 for (i = 0; i < n; i++, mp++) {
542 if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
543 char *addr = (char *)self + mp->offset;
544 PyObject *obj = *(PyObject **)addr;
545 if (obj != NULL) {
546 Py_DECREF(obj);
547 *(PyObject **)addr = NULL;
548 }
549 }
550 }
551}
552
553static int
554subtype_clear(PyObject *self)
555{
556 PyTypeObject *type, *base;
557 inquiry baseclear;
558
559 /* Find the nearest base with a different tp_clear
560 and clear slots while we're at it */
561 type = self->ob_type;
562 base = type;
563 while ((baseclear = base->tp_clear) == subtype_clear) {
564 if (base->ob_size)
565 clear_slots(base, self);
566 base = base->tp_base;
567 assert(base);
568 }
569
Guido van Rossuma3862092002-06-10 15:24:42 +0000570 /* There's no need to clear the instance dict (if any);
571 the collector will call its tp_clear handler. */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000572
573 if (baseclear)
574 return baseclear(self);
Guido van Rossum9475a232001-10-05 20:51:39 +0000575 return 0;
576}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000577
578static void
579subtype_dealloc(PyObject *self)
580{
Guido van Rossum14227b42001-12-06 02:35:58 +0000581 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000582 destructor basedealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000583
Guido van Rossum22b13872002-08-06 21:41:44 +0000584 /* Extract the type; we expect it to be a heap type */
585 type = self->ob_type;
586 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000587
Guido van Rossum22b13872002-08-06 21:41:44 +0000588 /* Test whether the type has GC exactly once */
589
590 if (!PyType_IS_GC(type)) {
591 /* It's really rare to find a dynamic type that doesn't have
592 GC; it can only happen when deriving from 'object' and not
593 adding any slots or instance variables. This allows
594 certain simplifications: there's no need to call
595 clear_slots(), or DECREF the dict, or clear weakrefs. */
596
597 /* Maybe call finalizer; exit early if resurrected */
Guido van Rossumfebd61d2002-08-08 20:55:20 +0000598 if (type->tp_del) {
599 type->tp_del(self);
600 if (self->ob_refcnt > 0)
601 return;
602 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000603
604 /* Find the nearest base with a different tp_dealloc */
605 base = type;
606 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
607 assert(base->ob_size == 0);
608 base = base->tp_base;
609 assert(base);
610 }
611
612 /* Call the base tp_dealloc() */
613 assert(basedealloc);
614 basedealloc(self);
615
616 /* Can't reference self beyond this point */
617 Py_DECREF(type);
618
619 /* Done */
620 return;
621 }
622
623 /* We get here only if the type has GC */
624
625 /* UnTrack and re-Track around the trashcan macro, alas */
Andrew M. Kuchlingc9172d32003-02-06 15:22:49 +0000626 /* See explanation at end of function for full disclosure */
Guido van Rossum0906e072002-08-07 20:42:09 +0000627 PyObject_GC_UnTrack(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000628 ++_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000629 Py_TRASHCAN_SAFE_BEGIN(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000630 --_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000631 _PyObject_GC_TRACK(self); /* We'll untrack for real later */
632
633 /* Maybe call finalizer; exit early if resurrected */
Guido van Rossumfebd61d2002-08-08 20:55:20 +0000634 if (type->tp_del) {
635 type->tp_del(self);
636 if (self->ob_refcnt > 0)
637 goto endlabel;
638 }
Guido van Rossum7ad2d1e2001-10-29 22:11:00 +0000639
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000640 /* Find the nearest base with a different tp_dealloc
641 and clear slots while we're at it */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000642 base = type;
643 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
644 if (base->ob_size)
645 clear_slots(base, self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000646 base = base->tp_base;
647 assert(base);
Guido van Rossum14227b42001-12-06 02:35:58 +0000648 }
649
Tim Peters6d6c1a32001-08-02 04:15:00 +0000650 /* If we added a dict, DECREF it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000651 if (type->tp_dictoffset && !base->tp_dictoffset) {
652 PyObject **dictptr = _PyObject_GetDictPtr(self);
653 if (dictptr != NULL) {
654 PyObject *dict = *dictptr;
655 if (dict != NULL) {
656 Py_DECREF(dict);
657 *dictptr = NULL;
658 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000659 }
660 }
661
Guido van Rossum9676b222001-08-17 20:32:36 +0000662 /* If we added weaklist, we clear it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000663 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
Guido van Rossum9676b222001-08-17 20:32:36 +0000664 PyObject_ClearWeakRefs(self);
665
Tim Peters6d6c1a32001-08-02 04:15:00 +0000666 /* Finalize GC if the base doesn't do GC and we do */
Guido van Rossum22b13872002-08-06 21:41:44 +0000667 if (!PyType_IS_GC(base))
Guido van Rossum048eb752001-10-02 21:24:57 +0000668 _PyObject_GC_UNTRACK(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000669
670 /* Call the base tp_dealloc() */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000671 assert(basedealloc);
672 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000673
674 /* Can't reference self beyond this point */
Guido van Rossum22b13872002-08-06 21:41:44 +0000675 Py_DECREF(type);
676
Guido van Rossum0906e072002-08-07 20:42:09 +0000677 endlabel:
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000678 ++_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000679 Py_TRASHCAN_SAFE_END(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000680 --_PyTrash_delete_nesting;
681
682 /* Explanation of the weirdness around the trashcan macros:
683
684 Q. What do the trashcan macros do?
685
686 A. Read the comment titled "Trashcan mechanism" in object.h.
687 For one, this explains why there must be a call to GC-untrack
688 before the trashcan begin macro. Without understanding the
689 trashcan code, the answers to the following questions don't make
690 sense.
691
692 Q. Why do we GC-untrack before the trashcan and then immediately
693 GC-track again afterward?
694
695 A. In the case that the base class is GC-aware, the base class
696 probably GC-untracks the object. If it does that using the
697 UNTRACK macro, this will crash when the object is already
698 untracked. Because we don't know what the base class does, the
699 only safe thing is to make sure the object is tracked when we
700 call the base class dealloc. But... The trashcan begin macro
701 requires that the object is *untracked* before it is called. So
702 the dance becomes:
703
704 GC untrack
705 trashcan begin
706 GC track
707
708 Q. Why the bizarre (net-zero) manipulation of
709 _PyTrash_delete_nesting around the trashcan macros?
710
711 A. Some base classes (e.g. list) also use the trashcan mechanism.
712 The following scenario used to be possible:
713
714 - suppose the trashcan level is one below the trashcan limit
715
716 - subtype_dealloc() is called
717
718 - the trashcan limit is not yet reached, so the trashcan level
719 is incremented and the code between trashcan begin and end is
720 executed
721
722 - this destroys much of the object's contents, including its
723 slots and __dict__
724
725 - basedealloc() is called; this is really list_dealloc(), or
726 some other type which also uses the trashcan macros
727
728 - the trashcan limit is now reached, so the object is put on the
729 trashcan's to-be-deleted-later list
730
731 - basedealloc() returns
732
733 - subtype_dealloc() decrefs the object's type
734
735 - subtype_dealloc() returns
736
737 - later, the trashcan code starts deleting the objects from its
738 to-be-deleted-later list
739
740 - subtype_dealloc() is called *AGAIN* for the same object
741
742 - at the very least (if the destroyed slots and __dict__ don't
743 cause problems) the object's type gets decref'ed a second
744 time, which is *BAD*!!!
745
746 The remedy is to make sure that if the code between trashcan
747 begin and end in subtype_dealloc() is called, the code between
748 trashcan begin and end in basedealloc() will also be called.
749 This is done by decrementing the level after passing into the
750 trashcan block, and incrementing it just before leaving the
751 block.
752
753 But now it's possible that a chain of objects consisting solely
754 of objects whose deallocator is subtype_dealloc() will defeat
755 the trashcan mechanism completely: the decremented level means
756 that the effective level never reaches the limit. Therefore, we
757 *increment* the level *before* entering the trashcan block, and
758 matchingly decrement it after leaving. This means the trashcan
759 code will trigger a little early, but that's no big deal.
760
761 Q. Are there any live examples of code in need of all this
762 complexity?
763
764 A. Yes. See SF bug 668433 for code that crashed (when Python was
765 compiled in debug mode) before the trashcan level manipulations
766 were added. For more discussion, see SF patches 581742, 575073
767 and bug 574207.
768 */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000769}
770
Jeremy Hylton938ace62002-07-17 16:30:39 +0000771static PyTypeObject *solid_base(PyTypeObject *type);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000772
Tim Peters6d6c1a32001-08-02 04:15:00 +0000773/* type test with subclassing support */
774
775int
776PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
777{
778 PyObject *mro;
779
Guido van Rossum9478d072001-09-07 18:52:13 +0000780 if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
781 return b == a || b == &PyBaseObject_Type;
782
Tim Peters6d6c1a32001-08-02 04:15:00 +0000783 mro = a->tp_mro;
784 if (mro != NULL) {
785 /* Deal with multiple inheritance without recursion
786 by walking the MRO tuple */
787 int i, n;
788 assert(PyTuple_Check(mro));
789 n = PyTuple_GET_SIZE(mro);
790 for (i = 0; i < n; i++) {
791 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
792 return 1;
793 }
794 return 0;
795 }
796 else {
797 /* a is not completely initilized yet; follow tp_base */
798 do {
799 if (a == b)
800 return 1;
801 a = a->tp_base;
802 } while (a != NULL);
803 return b == &PyBaseObject_Type;
804 }
805}
806
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000807/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +0000808 without looking in the instance dictionary
809 (so we can't use PyObject_GetAttr) but still binding
810 it to the instance. The arguments are the object,
811 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000812 static variable used to cache the interned Python string.
813
814 Two variants:
815
816 - lookup_maybe() returns NULL without raising an exception
817 when the _PyType_Lookup() call fails;
818
819 - lookup_method() always raises an exception upon errors.
820*/
Guido van Rossum60718732001-08-28 17:47:51 +0000821
822static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000823lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +0000824{
825 PyObject *res;
826
827 if (*attrobj == NULL) {
828 *attrobj = PyString_InternFromString(attrstr);
829 if (*attrobj == NULL)
830 return NULL;
831 }
832 res = _PyType_Lookup(self->ob_type, *attrobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000833 if (res != NULL) {
Guido van Rossum60718732001-08-28 17:47:51 +0000834 descrgetfunc f;
835 if ((f = res->ob_type->tp_descr_get) == NULL)
836 Py_INCREF(res);
837 else
838 res = f(res, self, (PyObject *)(self->ob_type));
839 }
840 return res;
841}
842
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000843static PyObject *
844lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
845{
846 PyObject *res = lookup_maybe(self, attrstr, attrobj);
847 if (res == NULL && !PyErr_Occurred())
848 PyErr_SetObject(PyExc_AttributeError, *attrobj);
849 return res;
850}
851
Guido van Rossum2730b132001-08-28 18:22:14 +0000852/* A variation of PyObject_CallMethod that uses lookup_method()
853 instead of PyObject_GetAttrString(). This uses the same convention
854 as lookup_method to cache the interned name string object. */
855
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000856static PyObject *
Guido van Rossum2730b132001-08-28 18:22:14 +0000857call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
858{
859 va_list va;
860 PyObject *args, *func = 0, *retval;
Guido van Rossum2730b132001-08-28 18:22:14 +0000861 va_start(va, format);
862
Guido van Rossumda21c012001-10-03 00:50:18 +0000863 func = lookup_maybe(o, name, nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000864 if (func == NULL) {
865 va_end(va);
866 if (!PyErr_Occurred())
Guido van Rossumda21c012001-10-03 00:50:18 +0000867 PyErr_SetObject(PyExc_AttributeError, *nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000868 return NULL;
869 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000870
871 if (format && *format)
872 args = Py_VaBuildValue(format, va);
873 else
874 args = PyTuple_New(0);
875
876 va_end(va);
877
878 if (args == NULL)
879 return NULL;
880
881 assert(PyTuple_Check(args));
882 retval = PyObject_Call(func, args, NULL);
883
884 Py_DECREF(args);
885 Py_DECREF(func);
886
887 return retval;
888}
889
890/* Clone of call_method() that returns NotImplemented when the lookup fails. */
891
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000892static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000893call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
894{
895 va_list va;
896 PyObject *args, *func = 0, *retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000897 va_start(va, format);
898
Guido van Rossumda21c012001-10-03 00:50:18 +0000899 func = lookup_maybe(o, name, nameobj);
Guido van Rossum2730b132001-08-28 18:22:14 +0000900 if (func == NULL) {
901 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000902 if (!PyErr_Occurred()) {
903 Py_INCREF(Py_NotImplemented);
904 return Py_NotImplemented;
905 }
Guido van Rossum717ce002001-09-14 16:58:08 +0000906 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +0000907 }
908
909 if (format && *format)
910 args = Py_VaBuildValue(format, va);
911 else
912 args = PyTuple_New(0);
913
914 va_end(va);
915
Guido van Rossum717ce002001-09-14 16:58:08 +0000916 if (args == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +0000917 return NULL;
918
Guido van Rossum717ce002001-09-14 16:58:08 +0000919 assert(PyTuple_Check(args));
920 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +0000921
922 Py_DECREF(args);
923 Py_DECREF(func);
924
925 return retval;
926}
927
Tim Petersa91e9642001-11-14 23:32:33 +0000928static int
929fill_classic_mro(PyObject *mro, PyObject *cls)
930{
931 PyObject *bases, *base;
932 int i, n;
933
934 assert(PyList_Check(mro));
935 assert(PyClass_Check(cls));
936 i = PySequence_Contains(mro, cls);
937 if (i < 0)
938 return -1;
939 if (!i) {
940 if (PyList_Append(mro, cls) < 0)
941 return -1;
942 }
943 bases = ((PyClassObject *)cls)->cl_bases;
944 assert(bases && PyTuple_Check(bases));
945 n = PyTuple_GET_SIZE(bases);
946 for (i = 0; i < n; i++) {
947 base = PyTuple_GET_ITEM(bases, i);
948 if (fill_classic_mro(mro, base) < 0)
949 return -1;
950 }
951 return 0;
952}
953
954static PyObject *
955classic_mro(PyObject *cls)
956{
957 PyObject *mro;
958
959 assert(PyClass_Check(cls));
960 mro = PyList_New(0);
961 if (mro != NULL) {
962 if (fill_classic_mro(mro, cls) == 0)
963 return mro;
964 Py_DECREF(mro);
965 }
966 return NULL;
967}
968
Tim Petersea7f75d2002-12-07 21:39:16 +0000969/*
Guido van Rossum1f121312002-11-14 19:49:16 +0000970 Method resolution order algorithm C3 described in
971 "A Monotonic Superclass Linearization for Dylan",
972 by Kim Barrett, Bob Cassel, Paul Haahr,
Tim Petersea7f75d2002-12-07 21:39:16 +0000973 David A. Moon, Keith Playford, and P. Tucker Withington.
Guido van Rossum1f121312002-11-14 19:49:16 +0000974 (OOPSLA 1996)
975
Guido van Rossum98f33732002-11-25 21:36:54 +0000976 Some notes about the rules implied by C3:
977
Tim Petersea7f75d2002-12-07 21:39:16 +0000978 No duplicate bases.
Guido van Rossum98f33732002-11-25 21:36:54 +0000979 It isn't legal to repeat a class in a list of base classes.
980
981 The next three properties are the 3 constraints in "C3".
982
Tim Petersea7f75d2002-12-07 21:39:16 +0000983 Local precendece order.
Guido van Rossum98f33732002-11-25 21:36:54 +0000984 If A precedes B in C's MRO, then A will precede B in the MRO of all
985 subclasses of C.
986
987 Monotonicity.
988 The MRO of a class must be an extension without reordering of the
989 MRO of each of its superclasses.
990
991 Extended Precedence Graph (EPG).
992 Linearization is consistent if there is a path in the EPG from
993 each class to all its successors in the linearization. See
994 the paper for definition of EPG.
Guido van Rossum1f121312002-11-14 19:49:16 +0000995 */
996
Tim Petersea7f75d2002-12-07 21:39:16 +0000997static int
Guido van Rossum1f121312002-11-14 19:49:16 +0000998tail_contains(PyObject *list, int whence, PyObject *o) {
999 int j, size;
1000 size = PyList_GET_SIZE(list);
1001
1002 for (j = whence+1; j < size; j++) {
1003 if (PyList_GET_ITEM(list, j) == o)
1004 return 1;
1005 }
1006 return 0;
1007}
1008
Guido van Rossum98f33732002-11-25 21:36:54 +00001009static PyObject *
1010class_name(PyObject *cls)
1011{
1012 PyObject *name = PyObject_GetAttrString(cls, "__name__");
1013 if (name == NULL) {
1014 PyErr_Clear();
1015 Py_XDECREF(name);
1016 name = PyObject_Repr(cls);
1017 }
1018 if (name == NULL)
1019 return NULL;
1020 if (!PyString_Check(name)) {
1021 Py_DECREF(name);
1022 return NULL;
1023 }
1024 return name;
1025}
1026
1027static int
1028check_duplicates(PyObject *list)
1029{
1030 int i, j, n;
1031 /* Let's use a quadratic time algorithm,
1032 assuming that the bases lists is short.
1033 */
1034 n = PyList_GET_SIZE(list);
1035 for (i = 0; i < n; i++) {
1036 PyObject *o = PyList_GET_ITEM(list, i);
1037 for (j = i + 1; j < n; j++) {
1038 if (PyList_GET_ITEM(list, j) == o) {
1039 o = class_name(o);
1040 PyErr_Format(PyExc_TypeError,
1041 "duplicate base class %s",
1042 o ? PyString_AS_STRING(o) : "?");
1043 Py_XDECREF(o);
1044 return -1;
1045 }
1046 }
1047 }
1048 return 0;
1049}
1050
1051/* Raise a TypeError for an MRO order disagreement.
1052
1053 It's hard to produce a good error message. In the absence of better
1054 insight into error reporting, report the classes that were candidates
1055 to be put next into the MRO. There is some conflict between the
1056 order in which they should be put in the MRO, but it's hard to
1057 diagnose what constraint can't be satisfied.
1058*/
1059
1060static void
1061set_mro_error(PyObject *to_merge, int *remain)
1062{
1063 int i, n, off, to_merge_size;
1064 char buf[1000];
1065 PyObject *k, *v;
1066 PyObject *set = PyDict_New();
1067
1068 to_merge_size = PyList_GET_SIZE(to_merge);
1069 for (i = 0; i < to_merge_size; i++) {
1070 PyObject *L = PyList_GET_ITEM(to_merge, i);
1071 if (remain[i] < PyList_GET_SIZE(L)) {
1072 PyObject *c = PyList_GET_ITEM(L, remain[i]);
1073 if (PyDict_SetItem(set, c, Py_None) < 0)
1074 return;
1075 }
1076 }
1077 n = PyDict_Size(set);
1078
Raymond Hettinger83245b52003-03-12 04:25:42 +00001079 off = PyOS_snprintf(buf, sizeof(buf), "Cannot create class.\
1080The superclasses have conflicting\n\
1081inheritance trees which leave the method resolution order (MRO)\n\
1082undefined for bases");
Guido van Rossum98f33732002-11-25 21:36:54 +00001083 i = 0;
1084 while (PyDict_Next(set, &i, &k, &v) && off < sizeof(buf)) {
1085 PyObject *name = class_name(k);
1086 off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s",
1087 name ? PyString_AS_STRING(name) : "?");
1088 Py_XDECREF(name);
1089 if (--n && off+1 < sizeof(buf)) {
1090 buf[off++] = ',';
1091 buf[off] = '\0';
1092 }
1093 }
1094 PyErr_SetString(PyExc_TypeError, buf);
1095 Py_DECREF(set);
1096}
1097
Tim Petersea7f75d2002-12-07 21:39:16 +00001098static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001099pmerge(PyObject *acc, PyObject* to_merge) {
1100 int i, j, to_merge_size;
1101 int *remain;
1102 int ok, empty_cnt;
Tim Petersea7f75d2002-12-07 21:39:16 +00001103
Guido van Rossum1f121312002-11-14 19:49:16 +00001104 to_merge_size = PyList_GET_SIZE(to_merge);
1105
Guido van Rossum98f33732002-11-25 21:36:54 +00001106 /* remain stores an index into each sublist of to_merge.
1107 remain[i] is the index of the next base in to_merge[i]
1108 that is not included in acc.
1109 */
Guido van Rossum1f121312002-11-14 19:49:16 +00001110 remain = PyMem_MALLOC(SIZEOF_INT*to_merge_size);
1111 if (remain == NULL)
1112 return -1;
1113 for (i = 0; i < to_merge_size; i++)
1114 remain[i] = 0;
1115
1116 again:
1117 empty_cnt = 0;
1118 for (i = 0; i < to_merge_size; i++) {
1119 PyObject *candidate;
Tim Petersea7f75d2002-12-07 21:39:16 +00001120
Guido van Rossum1f121312002-11-14 19:49:16 +00001121 PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
1122
1123 if (remain[i] >= PyList_GET_SIZE(cur_list)) {
1124 empty_cnt++;
1125 continue;
1126 }
1127
Guido van Rossum98f33732002-11-25 21:36:54 +00001128 /* Choose next candidate for MRO.
1129
1130 The input sequences alone can determine the choice.
1131 If not, choose the class which appears in the MRO
1132 of the earliest direct superclass of the new class.
1133 */
1134
Guido van Rossum1f121312002-11-14 19:49:16 +00001135 candidate = PyList_GET_ITEM(cur_list, remain[i]);
1136 for (j = 0; j < to_merge_size; j++) {
1137 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum98f33732002-11-25 21:36:54 +00001138 if (tail_contains(j_lst, remain[j], candidate)) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001139 goto skip; /* continue outer loop */
Guido van Rossum98f33732002-11-25 21:36:54 +00001140 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001141 }
1142 ok = PyList_Append(acc, candidate);
1143 if (ok < 0) {
1144 PyMem_Free(remain);
1145 return -1;
1146 }
1147 for (j = 0; j < to_merge_size; j++) {
1148 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum768158c2002-12-31 16:33:01 +00001149 if (remain[j] < PyList_GET_SIZE(j_lst) &&
1150 PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001151 remain[j]++;
1152 }
1153 }
1154 goto again;
Tim Peters9a6b8d82002-11-14 23:22:33 +00001155 skip: ;
Guido van Rossum1f121312002-11-14 19:49:16 +00001156 }
1157
Guido van Rossum98f33732002-11-25 21:36:54 +00001158 if (empty_cnt == to_merge_size) {
1159 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001160 return 0;
Guido van Rossum98f33732002-11-25 21:36:54 +00001161 }
1162 set_mro_error(to_merge, remain);
1163 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001164 return -1;
1165}
1166
Tim Peters6d6c1a32001-08-02 04:15:00 +00001167static PyObject *
1168mro_implementation(PyTypeObject *type)
1169{
1170 int i, n, ok;
1171 PyObject *bases, *result;
Guido van Rossum1f121312002-11-14 19:49:16 +00001172 PyObject *to_merge, *bases_aslist;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001173
Guido van Rossum63517572002-06-18 16:44:57 +00001174 if(type->tp_dict == NULL) {
1175 if(PyType_Ready(type) < 0)
1176 return NULL;
1177 }
1178
Guido van Rossum98f33732002-11-25 21:36:54 +00001179 /* Find a superclass linearization that honors the constraints
1180 of the explicit lists of bases and the constraints implied by
Tim Petersea7f75d2002-12-07 21:39:16 +00001181 each base class.
Guido van Rossum98f33732002-11-25 21:36:54 +00001182
1183 to_merge is a list of lists, where each list is a superclass
1184 linearization implied by a base class. The last element of
1185 to_merge is the declared list of bases.
1186 */
1187
Tim Peters6d6c1a32001-08-02 04:15:00 +00001188 bases = type->tp_bases;
1189 n = PyTuple_GET_SIZE(bases);
Guido van Rossum1f121312002-11-14 19:49:16 +00001190
1191 to_merge = PyList_New(n+1);
1192 if (to_merge == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001193 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001194
Tim Peters6d6c1a32001-08-02 04:15:00 +00001195 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001196 PyObject *base = PyTuple_GET_ITEM(bases, i);
1197 PyObject *parentMRO;
1198 if (PyType_Check(base))
1199 parentMRO = PySequence_List(
1200 ((PyTypeObject*)base)->tp_mro);
1201 else
1202 parentMRO = classic_mro(base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001203 if (parentMRO == NULL) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001204 Py_DECREF(to_merge);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001205 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001206 }
1207
1208 PyList_SET_ITEM(to_merge, i, parentMRO);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001209 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001210
1211 bases_aslist = PySequence_List(bases);
1212 if (bases_aslist == NULL) {
1213 Py_DECREF(to_merge);
1214 return NULL;
1215 }
Guido van Rossum98f33732002-11-25 21:36:54 +00001216 /* This is just a basic sanity check. */
1217 if (check_duplicates(bases_aslist) < 0) {
1218 Py_DECREF(to_merge);
1219 Py_DECREF(bases_aslist);
1220 return NULL;
1221 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001222 PyList_SET_ITEM(to_merge, n, bases_aslist);
1223
1224 result = Py_BuildValue("[O]", (PyObject *)type);
1225 if (result == NULL) {
1226 Py_DECREF(to_merge);
1227 return NULL;
1228 }
1229
1230 ok = pmerge(result, to_merge);
1231 Py_DECREF(to_merge);
1232 if (ok < 0) {
1233 Py_DECREF(result);
1234 return NULL;
1235 }
1236
Tim Peters6d6c1a32001-08-02 04:15:00 +00001237 return result;
1238}
1239
1240static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001241mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001242{
1243 PyTypeObject *type = (PyTypeObject *)self;
1244
Tim Peters6d6c1a32001-08-02 04:15:00 +00001245 return mro_implementation(type);
1246}
1247
1248static int
1249mro_internal(PyTypeObject *type)
1250{
1251 PyObject *mro, *result, *tuple;
1252
1253 if (type->ob_type == &PyType_Type) {
1254 result = mro_implementation(type);
1255 }
1256 else {
Guido van Rossum60718732001-08-28 17:47:51 +00001257 static PyObject *mro_str;
1258 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001259 if (mro == NULL)
1260 return -1;
1261 result = PyObject_CallObject(mro, NULL);
1262 Py_DECREF(mro);
1263 }
1264 if (result == NULL)
1265 return -1;
1266 tuple = PySequence_Tuple(result);
1267 Py_DECREF(result);
1268 type->tp_mro = tuple;
1269 return 0;
1270}
1271
1272
1273/* Calculate the best base amongst multiple base classes.
1274 This is the first one that's on the path to the "solid base". */
1275
1276static PyTypeObject *
1277best_base(PyObject *bases)
1278{
1279 int i, n;
1280 PyTypeObject *base, *winner, *candidate, *base_i;
Tim Petersa91e9642001-11-14 23:32:33 +00001281 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001282
1283 assert(PyTuple_Check(bases));
1284 n = PyTuple_GET_SIZE(bases);
1285 assert(n > 0);
Tim Petersa91e9642001-11-14 23:32:33 +00001286 base = NULL;
1287 winner = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001288 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001289 base_proto = PyTuple_GET_ITEM(bases, i);
1290 if (PyClass_Check(base_proto))
1291 continue;
1292 if (!PyType_Check(base_proto)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001293 PyErr_SetString(
1294 PyExc_TypeError,
1295 "bases must be types");
1296 return NULL;
1297 }
Tim Petersa91e9642001-11-14 23:32:33 +00001298 base_i = (PyTypeObject *)base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001299 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001300 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001301 return NULL;
1302 }
1303 candidate = solid_base(base_i);
Tim Petersa91e9642001-11-14 23:32:33 +00001304 if (winner == NULL) {
1305 winner = candidate;
1306 base = base_i;
1307 }
1308 else if (PyType_IsSubtype(winner, candidate))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001309 ;
1310 else if (PyType_IsSubtype(candidate, winner)) {
1311 winner = candidate;
1312 base = base_i;
1313 }
1314 else {
1315 PyErr_SetString(
1316 PyExc_TypeError,
1317 "multiple bases have "
1318 "instance lay-out conflict");
1319 return NULL;
1320 }
1321 }
Guido van Rossume54616c2001-12-14 04:19:56 +00001322 if (base == NULL)
1323 PyErr_SetString(PyExc_TypeError,
1324 "a new-style class can't have only classic bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001325 return base;
1326}
1327
1328static int
1329extra_ivars(PyTypeObject *type, PyTypeObject *base)
1330{
Neil Schemenauerc806c882001-08-29 23:54:54 +00001331 size_t t_size = type->tp_basicsize;
1332 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001333
Guido van Rossum9676b222001-08-17 20:32:36 +00001334 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001335 if (type->tp_itemsize || base->tp_itemsize) {
1336 /* If itemsize is involved, stricter rules */
1337 return t_size != b_size ||
1338 type->tp_itemsize != base->tp_itemsize;
1339 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001340 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
1341 type->tp_weaklistoffset + sizeof(PyObject *) == t_size)
1342 t_size -= sizeof(PyObject *);
1343 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
1344 type->tp_dictoffset + sizeof(PyObject *) == t_size)
1345 t_size -= sizeof(PyObject *);
1346
1347 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001348}
1349
1350static PyTypeObject *
1351solid_base(PyTypeObject *type)
1352{
1353 PyTypeObject *base;
1354
1355 if (type->tp_base)
1356 base = solid_base(type->tp_base);
1357 else
1358 base = &PyBaseObject_Type;
1359 if (extra_ivars(type, base))
1360 return type;
1361 else
1362 return base;
1363}
1364
Jeremy Hylton938ace62002-07-17 16:30:39 +00001365static void object_dealloc(PyObject *);
1366static int object_init(PyObject *, PyObject *, PyObject *);
1367static int update_slot(PyTypeObject *, PyObject *);
1368static void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001369
1370static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001371subtype_dict(PyObject *obj, void *context)
1372{
1373 PyObject **dictptr = _PyObject_GetDictPtr(obj);
1374 PyObject *dict;
1375
1376 if (dictptr == NULL) {
1377 PyErr_SetString(PyExc_AttributeError,
1378 "This object has no __dict__");
1379 return NULL;
1380 }
1381 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +00001382 if (dict == NULL)
1383 *dictptr = dict = PyDict_New();
1384 Py_XINCREF(dict);
1385 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001386}
1387
Guido van Rossum6661be32001-10-26 04:26:12 +00001388static int
1389subtype_setdict(PyObject *obj, PyObject *value, void *context)
1390{
1391 PyObject **dictptr = _PyObject_GetDictPtr(obj);
1392 PyObject *dict;
1393
1394 if (dictptr == NULL) {
1395 PyErr_SetString(PyExc_AttributeError,
1396 "This object has no __dict__");
1397 return -1;
1398 }
Guido van Rossumd331cb52001-12-05 19:46:42 +00001399 if (value != NULL && !PyDict_Check(value)) {
Guido van Rossum6661be32001-10-26 04:26:12 +00001400 PyErr_SetString(PyExc_TypeError,
1401 "__dict__ must be set to a dictionary");
1402 return -1;
1403 }
1404 dict = *dictptr;
Guido van Rossumd331cb52001-12-05 19:46:42 +00001405 Py_XINCREF(value);
Guido van Rossum6661be32001-10-26 04:26:12 +00001406 *dictptr = value;
1407 Py_XDECREF(dict);
1408 return 0;
1409}
1410
Guido van Rossumad47da02002-08-12 19:05:44 +00001411static PyObject *
1412subtype_getweakref(PyObject *obj, void *context)
1413{
1414 PyObject **weaklistptr;
1415 PyObject *result;
1416
1417 if (obj->ob_type->tp_weaklistoffset == 0) {
1418 PyErr_SetString(PyExc_AttributeError,
1419 "This object has no __weaklist__");
1420 return NULL;
1421 }
1422 assert(obj->ob_type->tp_weaklistoffset > 0);
1423 assert(obj->ob_type->tp_weaklistoffset + sizeof(PyObject *) <=
Guido van Rossum3747a0f2002-08-12 19:25:08 +00001424 (size_t)(obj->ob_type->tp_basicsize));
Guido van Rossumad47da02002-08-12 19:05:44 +00001425 weaklistptr = (PyObject **)
Guido van Rossum3747a0f2002-08-12 19:25:08 +00001426 ((char *)obj + obj->ob_type->tp_weaklistoffset);
Guido van Rossumad47da02002-08-12 19:05:44 +00001427 if (*weaklistptr == NULL)
1428 result = Py_None;
1429 else
1430 result = *weaklistptr;
1431 Py_INCREF(result);
1432 return result;
1433}
1434
Guido van Rossum373c7412003-01-07 13:41:37 +00001435/* Three variants on the subtype_getsets list. */
1436
1437static PyGetSetDef subtype_getsets_full[] = {
Guido van Rossumad47da02002-08-12 19:05:44 +00001438 {"__dict__", subtype_dict, subtype_setdict,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001439 PyDoc_STR("dictionary for instance variables (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001440 {"__weakref__", subtype_getweakref, NULL,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001441 PyDoc_STR("list of weak references to the object (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001442 {0}
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001443};
1444
Guido van Rossum373c7412003-01-07 13:41:37 +00001445static PyGetSetDef subtype_getsets_dict_only[] = {
1446 {"__dict__", subtype_dict, subtype_setdict,
1447 PyDoc_STR("dictionary for instance variables (if defined)")},
1448 {0}
1449};
1450
1451static PyGetSetDef subtype_getsets_weakref_only[] = {
1452 {"__weakref__", subtype_getweakref, NULL,
1453 PyDoc_STR("list of weak references to the object (if defined)")},
1454 {0}
1455};
1456
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001457static int
1458valid_identifier(PyObject *s)
1459{
Guido van Rossum03013a02002-07-16 14:30:28 +00001460 unsigned char *p;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001461 int i, n;
1462
1463 if (!PyString_Check(s)) {
1464 PyErr_SetString(PyExc_TypeError,
1465 "__slots__ must be strings");
1466 return 0;
1467 }
Guido van Rossum03013a02002-07-16 14:30:28 +00001468 p = (unsigned char *) PyString_AS_STRING(s);
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001469 n = PyString_GET_SIZE(s);
1470 /* We must reject an empty name. As a hack, we bump the
1471 length to 1 so that the loop will balk on the trailing \0. */
1472 if (n == 0)
1473 n = 1;
1474 for (i = 0; i < n; i++, p++) {
1475 if (!(i == 0 ? isalpha(*p) : isalnum(*p)) && *p != '_') {
1476 PyErr_SetString(PyExc_TypeError,
1477 "__slots__ must be identifiers");
1478 return 0;
1479 }
1480 }
1481 return 1;
1482}
1483
Martin v. Löwisd919a592002-10-14 21:07:28 +00001484#ifdef Py_USING_UNICODE
1485/* Replace Unicode objects in slots. */
1486
1487static PyObject *
1488_unicode_to_string(PyObject *slots, int nslots)
1489{
1490 PyObject *tmp = slots;
1491 PyObject *o, *o1;
1492 int i;
1493 intintargfunc copy = slots->ob_type->tp_as_sequence->sq_slice;
1494 for (i = 0; i < nslots; i++) {
1495 if (PyUnicode_Check(o = PyTuple_GET_ITEM(tmp, i))) {
1496 if (tmp == slots) {
1497 tmp = copy(slots, 0, PyTuple_GET_SIZE(slots));
1498 if (tmp == NULL)
1499 return NULL;
1500 }
1501 o1 = _PyUnicode_AsDefaultEncodedString
1502 (o, NULL);
1503 if (o1 == NULL) {
1504 Py_DECREF(tmp);
1505 return 0;
1506 }
1507 Py_INCREF(o1);
1508 Py_DECREF(o);
1509 PyTuple_SET_ITEM(tmp, i, o1);
1510 }
1511 }
1512 return tmp;
1513}
1514#endif
1515
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001516static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001517type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
1518{
1519 PyObject *name, *bases, *dict;
1520 static char *kwlist[] = {"name", "bases", "dict", 0};
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001521 PyObject *slots, *tmp, *newslots;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001522 PyTypeObject *type, *base, *tmptype, *winner;
Guido van Rossume5c691a2003-03-07 15:13:17 +00001523 PyHeapTypeObject *et;
Guido van Rossum6f799372001-09-20 20:46:19 +00001524 PyMemberDef *mp;
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001525 int i, nbases, nslots, slotoffset, add_dict, add_weak;
Guido van Rossumad47da02002-08-12 19:05:44 +00001526 int j, may_add_dict, may_add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001527
Tim Peters3abca122001-10-27 19:37:48 +00001528 assert(args != NULL && PyTuple_Check(args));
1529 assert(kwds == NULL || PyDict_Check(kwds));
1530
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001531 /* Special case: type(x) should return x->ob_type */
Tim Peters3abca122001-10-27 19:37:48 +00001532 {
1533 const int nargs = PyTuple_GET_SIZE(args);
1534 const int nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
1535
1536 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
1537 PyObject *x = PyTuple_GET_ITEM(args, 0);
1538 Py_INCREF(x->ob_type);
1539 return (PyObject *) x->ob_type;
1540 }
1541
1542 /* SF bug 475327 -- if that didn't trigger, we need 3
1543 arguments. but PyArg_ParseTupleAndKeywords below may give
1544 a msg saying type() needs exactly 3. */
1545 if (nargs + nkwds != 3) {
1546 PyErr_SetString(PyExc_TypeError,
1547 "type() takes 1 or 3 arguments");
1548 return NULL;
1549 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001550 }
1551
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001552 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001553 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
1554 &name,
1555 &PyTuple_Type, &bases,
1556 &PyDict_Type, &dict))
1557 return NULL;
1558
1559 /* Determine the proper metatype to deal with this,
1560 and check for metatype conflicts while we're at it.
1561 Note that if some other metatype wins to contract,
1562 it's possible that its instances are not types. */
1563 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001564 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001565 for (i = 0; i < nbases; i++) {
1566 tmp = PyTuple_GET_ITEM(bases, i);
1567 tmptype = tmp->ob_type;
Tim Petersa91e9642001-11-14 23:32:33 +00001568 if (tmptype == &PyClass_Type)
1569 continue; /* Special case classic classes */
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001570 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001571 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001572 if (PyType_IsSubtype(tmptype, winner)) {
1573 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001574 continue;
1575 }
1576 PyErr_SetString(PyExc_TypeError,
1577 "metatype conflict among bases");
1578 return NULL;
1579 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001580 if (winner != metatype) {
1581 if (winner->tp_new != type_new) /* Pass it to the winner */
1582 return winner->tp_new(winner, args, kwds);
1583 metatype = winner;
1584 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001585
1586 /* Adjust for empty tuple bases */
1587 if (nbases == 0) {
1588 bases = Py_BuildValue("(O)", &PyBaseObject_Type);
1589 if (bases == NULL)
1590 return NULL;
1591 nbases = 1;
1592 }
1593 else
1594 Py_INCREF(bases);
1595
1596 /* XXX From here until type is allocated, "return NULL" leaks bases! */
1597
1598 /* Calculate best base, and check that all bases are type objects */
1599 base = best_base(bases);
1600 if (base == NULL)
1601 return NULL;
1602 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
1603 PyErr_Format(PyExc_TypeError,
1604 "type '%.100s' is not an acceptable base type",
1605 base->tp_name);
1606 return NULL;
1607 }
1608
Tim Peters6d6c1a32001-08-02 04:15:00 +00001609 /* Check for a __slots__ sequence variable in dict, and count it */
1610 slots = PyDict_GetItemString(dict, "__slots__");
1611 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +00001612 add_dict = 0;
1613 add_weak = 0;
Guido van Rossumad47da02002-08-12 19:05:44 +00001614 may_add_dict = base->tp_dictoffset == 0;
1615 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
1616 if (slots == NULL) {
1617 if (may_add_dict) {
1618 add_dict++;
1619 }
1620 if (may_add_weak) {
1621 add_weak++;
1622 }
1623 }
1624 else {
1625 /* Have slots */
1626
Tim Peters6d6c1a32001-08-02 04:15:00 +00001627 /* Make it into a tuple */
1628 if (PyString_Check(slots))
1629 slots = Py_BuildValue("(O)", slots);
1630 else
1631 slots = PySequence_Tuple(slots);
1632 if (slots == NULL)
1633 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00001634 assert(PyTuple_Check(slots));
1635
1636 /* Are slots allowed? */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001637 nslots = PyTuple_GET_SIZE(slots);
Guido van Rossume5c691a2003-03-07 15:13:17 +00001638 if (nslots > 0 && base->tp_itemsize != 0 && !PyType_Check(base)) {
1639 /* for the special case of meta types, allow slots */
Guido van Rossumc4141872001-08-30 04:43:35 +00001640 PyErr_Format(PyExc_TypeError,
1641 "nonempty __slots__ "
1642 "not supported for subtype of '%s'",
1643 base->tp_name);
Guido van Rossumad47da02002-08-12 19:05:44 +00001644 bad_slots:
1645 Py_DECREF(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +00001646 return NULL;
1647 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001648
Martin v. Löwisd919a592002-10-14 21:07:28 +00001649#ifdef Py_USING_UNICODE
1650 tmp = _unicode_to_string(slots, nslots);
Martin v. Löwis13b1a5c2002-10-14 21:11:34 +00001651 if (tmp != slots) {
1652 Py_DECREF(slots);
1653 slots = tmp;
1654 }
Martin v. Löwisd919a592002-10-14 21:07:28 +00001655 if (!tmp)
1656 return NULL;
1657#endif
Guido van Rossumad47da02002-08-12 19:05:44 +00001658 /* Check for valid slot names and two special cases */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001659 for (i = 0; i < nslots; i++) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001660 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
1661 char *s;
1662 if (!valid_identifier(tmp))
1663 goto bad_slots;
1664 assert(PyString_Check(tmp));
1665 s = PyString_AS_STRING(tmp);
1666 if (strcmp(s, "__dict__") == 0) {
1667 if (!may_add_dict || add_dict) {
1668 PyErr_SetString(PyExc_TypeError,
1669 "__dict__ slot disallowed: "
1670 "we already got one");
1671 goto bad_slots;
1672 }
1673 add_dict++;
1674 }
1675 if (strcmp(s, "__weakref__") == 0) {
1676 if (!may_add_weak || add_weak) {
1677 PyErr_SetString(PyExc_TypeError,
1678 "__weakref__ slot disallowed: "
1679 "either we already got one, "
1680 "or __itemsize__ != 0");
1681 goto bad_slots;
1682 }
1683 add_weak++;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001684 }
1685 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001686
Guido van Rossumad47da02002-08-12 19:05:44 +00001687 /* Copy slots into yet another tuple, demangling names */
1688 newslots = PyTuple_New(nslots - add_dict - add_weak);
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001689 if (newslots == NULL)
Guido van Rossumad47da02002-08-12 19:05:44 +00001690 goto bad_slots;
1691 for (i = j = 0; i < nslots; i++) {
1692 char *s;
Guido van Rossum8e829202002-08-16 03:47:49 +00001693 char buffer[256];
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001694 tmp = PyTuple_GET_ITEM(slots, i);
Guido van Rossumad47da02002-08-12 19:05:44 +00001695 s = PyString_AS_STRING(tmp);
1696 if ((add_dict && strcmp(s, "__dict__") == 0) ||
1697 (add_weak && strcmp(s, "__weakref__") == 0))
1698 continue;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001699 if (_Py_Mangle(PyString_AS_STRING(name),
Guido van Rossumad47da02002-08-12 19:05:44 +00001700 PyString_AS_STRING(tmp),
1701 buffer, sizeof(buffer)))
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001702 {
1703 tmp = PyString_FromString(buffer);
1704 } else {
1705 Py_INCREF(tmp);
1706 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001707 PyTuple_SET_ITEM(newslots, j, tmp);
1708 j++;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001709 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001710 assert(j == nslots - add_dict - add_weak);
1711 nslots = j;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001712 Py_DECREF(slots);
1713 slots = newslots;
1714
Guido van Rossumad47da02002-08-12 19:05:44 +00001715 /* Secondary bases may provide weakrefs or dict */
1716 if (nbases > 1 &&
1717 ((may_add_dict && !add_dict) ||
1718 (may_add_weak && !add_weak))) {
1719 for (i = 0; i < nbases; i++) {
1720 tmp = PyTuple_GET_ITEM(bases, i);
1721 if (tmp == (PyObject *)base)
1722 continue; /* Skip primary base */
1723 if (PyClass_Check(tmp)) {
1724 /* Classic base class provides both */
1725 if (may_add_dict && !add_dict)
1726 add_dict++;
1727 if (may_add_weak && !add_weak)
1728 add_weak++;
1729 break;
1730 }
1731 assert(PyType_Check(tmp));
1732 tmptype = (PyTypeObject *)tmp;
1733 if (may_add_dict && !add_dict &&
1734 tmptype->tp_dictoffset != 0)
1735 add_dict++;
1736 if (may_add_weak && !add_weak &&
1737 tmptype->tp_weaklistoffset != 0)
1738 add_weak++;
1739 if (may_add_dict && !add_dict)
1740 continue;
1741 if (may_add_weak && !add_weak)
1742 continue;
1743 /* Nothing more to check */
1744 break;
1745 }
1746 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001747 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001748
1749 /* XXX From here until type is safely allocated,
1750 "return NULL" may leak slots! */
1751
1752 /* Allocate the type object */
1753 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
Guido van Rossumad47da02002-08-12 19:05:44 +00001754 if (type == NULL) {
1755 Py_XDECREF(slots);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001756 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00001757 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001758
1759 /* Keep name and slots alive in the extended type object */
Guido van Rossume5c691a2003-03-07 15:13:17 +00001760 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001761 Py_INCREF(name);
1762 et->name = name;
1763 et->slots = slots;
1764
Guido van Rossumdc91b992001-08-08 22:26:22 +00001765 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001766 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
1767 Py_TPFLAGS_BASETYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00001768 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
1769 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00001770
1771 /* It's a new-style number unless it specifically inherits any
1772 old-style numeric behavior */
1773 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
1774 (base->tp_as_number == NULL))
1775 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
1776
1777 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001778 type->tp_as_number = &et->as_number;
1779 type->tp_as_sequence = &et->as_sequence;
1780 type->tp_as_mapping = &et->as_mapping;
1781 type->tp_as_buffer = &et->as_buffer;
1782 type->tp_name = PyString_AS_STRING(name);
1783
1784 /* Set tp_base and tp_bases */
1785 type->tp_bases = bases;
1786 Py_INCREF(base);
1787 type->tp_base = base;
1788
Guido van Rossum687ae002001-10-15 22:03:32 +00001789 /* Initialize tp_dict from passed-in dict */
1790 type->tp_dict = dict = PyDict_Copy(dict);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001791 if (dict == NULL) {
1792 Py_DECREF(type);
1793 return NULL;
1794 }
1795
Guido van Rossumc3542212001-08-16 09:18:56 +00001796 /* Set __module__ in the dict */
1797 if (PyDict_GetItemString(dict, "__module__") == NULL) {
1798 tmp = PyEval_GetGlobals();
1799 if (tmp != NULL) {
1800 tmp = PyDict_GetItemString(tmp, "__name__");
1801 if (tmp != NULL) {
1802 if (PyDict_SetItemString(dict, "__module__",
1803 tmp) < 0)
1804 return NULL;
1805 }
1806 }
1807 }
1808
Tim Peters2f93e282001-10-04 05:27:00 +00001809 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
Tim Peters24008312002-03-17 18:56:20 +00001810 and is a string. The __doc__ accessor will first look for tp_doc;
1811 if that fails, it will still look into __dict__.
Tim Peters2f93e282001-10-04 05:27:00 +00001812 */
1813 {
1814 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
1815 if (doc != NULL && PyString_Check(doc)) {
1816 const size_t n = (size_t)PyString_GET_SIZE(doc);
Tim Peters59f809d2001-10-04 05:43:02 +00001817 type->tp_doc = (char *)PyObject_MALLOC(n+1);
Tim Peters2f93e282001-10-04 05:27:00 +00001818 if (type->tp_doc == NULL) {
1819 Py_DECREF(type);
1820 return NULL;
1821 }
1822 memcpy(type->tp_doc, PyString_AS_STRING(doc), n+1);
1823 }
1824 }
1825
Tim Peters6d6c1a32001-08-02 04:15:00 +00001826 /* Special-case __new__: if it's a plain function,
1827 make it a static function */
1828 tmp = PyDict_GetItemString(dict, "__new__");
1829 if (tmp != NULL && PyFunction_Check(tmp)) {
1830 tmp = PyStaticMethod_New(tmp);
1831 if (tmp == NULL) {
1832 Py_DECREF(type);
1833 return NULL;
1834 }
1835 PyDict_SetItemString(dict, "__new__", tmp);
1836 Py_DECREF(tmp);
1837 }
1838
1839 /* Add descriptors for custom slots from __slots__, or for __dict__ */
Guido van Rossume5c691a2003-03-07 15:13:17 +00001840 mp = PyHeapType_GET_MEMBERS(et);
Neil Schemenauerc806c882001-08-29 23:54:54 +00001841 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001842 if (slots != NULL) {
1843 for (i = 0; i < nslots; i++, mp++) {
1844 mp->name = PyString_AS_STRING(
1845 PyTuple_GET_ITEM(slots, i));
Guido van Rossum64b206c2001-12-04 17:13:22 +00001846 mp->type = T_OBJECT_EX;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001847 mp->offset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +00001848 if (base->tp_weaklistoffset == 0 &&
Guido van Rossum64b206c2001-12-04 17:13:22 +00001849 strcmp(mp->name, "__weakref__") == 0) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001850 add_weak++;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001851 mp->type = T_OBJECT;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001852 mp->flags = READONLY;
Guido van Rossum9676b222001-08-17 20:32:36 +00001853 type->tp_weaklistoffset = slotoffset;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001854 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001855 slotoffset += sizeof(PyObject *);
1856 }
1857 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001858 if (add_dict) {
1859 if (base->tp_itemsize)
1860 type->tp_dictoffset = -(long)sizeof(PyObject *);
1861 else
1862 type->tp_dictoffset = slotoffset;
1863 slotoffset += sizeof(PyObject *);
1864 }
1865 if (add_weak) {
1866 assert(!base->tp_itemsize);
1867 type->tp_weaklistoffset = slotoffset;
1868 slotoffset += sizeof(PyObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001869 }
1870 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001871 type->tp_itemsize = base->tp_itemsize;
Guido van Rossume5c691a2003-03-07 15:13:17 +00001872 type->tp_members = PyHeapType_GET_MEMBERS(et);
Guido van Rossum373c7412003-01-07 13:41:37 +00001873
1874 if (type->tp_weaklistoffset && type->tp_dictoffset)
1875 type->tp_getset = subtype_getsets_full;
1876 else if (type->tp_weaklistoffset && !type->tp_dictoffset)
1877 type->tp_getset = subtype_getsets_weakref_only;
1878 else if (!type->tp_weaklistoffset && type->tp_dictoffset)
1879 type->tp_getset = subtype_getsets_dict_only;
1880 else
1881 type->tp_getset = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001882
1883 /* Special case some slots */
1884 if (type->tp_dictoffset != 0 || nslots > 0) {
1885 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
1886 type->tp_getattro = PyObject_GenericGetAttr;
1887 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
1888 type->tp_setattro = PyObject_GenericSetAttr;
1889 }
1890 type->tp_dealloc = subtype_dealloc;
1891
Guido van Rossum9475a232001-10-05 20:51:39 +00001892 /* Enable GC unless there are really no instance variables possible */
1893 if (!(type->tp_basicsize == sizeof(PyObject) &&
1894 type->tp_itemsize == 0))
1895 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
1896
Tim Peters6d6c1a32001-08-02 04:15:00 +00001897 /* Always override allocation strategy to use regular heap */
1898 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00001899 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001900 type->tp_free = PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00001901 type->tp_traverse = subtype_traverse;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001902 type->tp_clear = subtype_clear;
Guido van Rossum048eb752001-10-02 21:24:57 +00001903 }
1904 else
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001905 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001906
1907 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001908 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001909 Py_DECREF(type);
1910 return NULL;
1911 }
1912
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001913 /* Put the proper slots in place */
1914 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00001915
Tim Peters6d6c1a32001-08-02 04:15:00 +00001916 return (PyObject *)type;
1917}
1918
1919/* Internal API to look for a name through the MRO.
1920 This returns a borrowed reference, and doesn't set an exception! */
1921PyObject *
1922_PyType_Lookup(PyTypeObject *type, PyObject *name)
1923{
1924 int i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00001925 PyObject *mro, *res, *base, *dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001926
Guido van Rossum687ae002001-10-15 22:03:32 +00001927 /* Look in tp_dict of types in MRO */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001928 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00001929
1930 /* If mro is NULL, the type is either not yet initialized
1931 by PyType_Ready(), or already cleared by type_clear().
1932 Either way the safest thing to do is to return NULL. */
1933 if (mro == NULL)
1934 return NULL;
1935
Tim Peters6d6c1a32001-08-02 04:15:00 +00001936 assert(PyTuple_Check(mro));
1937 n = PyTuple_GET_SIZE(mro);
1938 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001939 base = PyTuple_GET_ITEM(mro, i);
1940 if (PyClass_Check(base))
1941 dict = ((PyClassObject *)base)->cl_dict;
1942 else {
1943 assert(PyType_Check(base));
1944 dict = ((PyTypeObject *)base)->tp_dict;
1945 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001946 assert(dict && PyDict_Check(dict));
1947 res = PyDict_GetItem(dict, name);
1948 if (res != NULL)
1949 return res;
1950 }
1951 return NULL;
1952}
1953
1954/* This is similar to PyObject_GenericGetAttr(),
1955 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
1956static PyObject *
1957type_getattro(PyTypeObject *type, PyObject *name)
1958{
1959 PyTypeObject *metatype = type->ob_type;
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001960 PyObject *meta_attribute, *attribute;
1961 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001962
1963 /* Initialize this type (we'll assume the metatype is initialized) */
1964 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001965 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001966 return NULL;
1967 }
1968
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001969 /* No readable descriptor found yet */
1970 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00001971
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001972 /* Look for the attribute in the metatype */
1973 meta_attribute = _PyType_Lookup(metatype, name);
1974
1975 if (meta_attribute != NULL) {
1976 meta_get = meta_attribute->ob_type->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00001977
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001978 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
1979 /* Data descriptors implement tp_descr_set to intercept
1980 * writes. Assume the attribute is not overridden in
1981 * type's tp_dict (and bases): call the descriptor now.
1982 */
1983 return meta_get(meta_attribute, (PyObject *)type,
1984 (PyObject *)metatype);
1985 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001986 }
1987
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001988 /* No data descriptor found on metatype. Look in tp_dict of this
1989 * type and its bases */
1990 attribute = _PyType_Lookup(type, name);
1991 if (attribute != NULL) {
1992 /* Implement descriptor functionality, if any */
1993 descrgetfunc local_get = attribute->ob_type->tp_descr_get;
1994 if (local_get != NULL) {
1995 /* NULL 2nd argument indicates the descriptor was
1996 * found on the target object itself (or a base) */
1997 return local_get(attribute, (PyObject *)NULL,
1998 (PyObject *)type);
1999 }
Tim Peters34592512002-07-11 06:23:50 +00002000
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002001 Py_INCREF(attribute);
2002 return attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002003 }
2004
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002005 /* No attribute found in local __dict__ (or bases): use the
2006 * descriptor from the metatype, if any */
2007 if (meta_get != NULL)
2008 return meta_get(meta_attribute, (PyObject *)type,
2009 (PyObject *)metatype);
2010
2011 /* If an ordinary attribute was found on the metatype, return it now */
2012 if (meta_attribute != NULL) {
2013 Py_INCREF(meta_attribute);
2014 return meta_attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002015 }
2016
2017 /* Give up */
2018 PyErr_Format(PyExc_AttributeError,
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002019 "type object '%.50s' has no attribute '%.400s'",
2020 type->tp_name, PyString_AS_STRING(name));
Tim Peters6d6c1a32001-08-02 04:15:00 +00002021 return NULL;
2022}
2023
2024static int
2025type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
2026{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002027 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2028 PyErr_Format(
2029 PyExc_TypeError,
2030 "can't set attributes of built-in/extension type '%s'",
2031 type->tp_name);
2032 return -1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002033 }
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002034 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
2035 return -1;
2036 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002037}
2038
2039static void
2040type_dealloc(PyTypeObject *type)
2041{
Guido van Rossume5c691a2003-03-07 15:13:17 +00002042 PyHeapTypeObject *et;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002043
2044 /* Assert this is a heap-allocated type object */
2045 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002046 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00002047 PyObject_ClearWeakRefs((PyObject *)type);
Guido van Rossume5c691a2003-03-07 15:13:17 +00002048 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002049 Py_XDECREF(type->tp_base);
2050 Py_XDECREF(type->tp_dict);
2051 Py_XDECREF(type->tp_bases);
2052 Py_XDECREF(type->tp_mro);
Guido van Rossum687ae002001-10-15 22:03:32 +00002053 Py_XDECREF(type->tp_cache);
Guido van Rossum1c450732001-10-08 15:18:27 +00002054 Py_XDECREF(type->tp_subclasses);
Neal Norwitzcee5ca02002-07-30 00:42:06 +00002055 PyObject_Free(type->tp_doc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002056 Py_XDECREF(et->name);
2057 Py_XDECREF(et->slots);
2058 type->ob_type->tp_free((PyObject *)type);
2059}
2060
Guido van Rossum1c450732001-10-08 15:18:27 +00002061static PyObject *
2062type_subclasses(PyTypeObject *type, PyObject *args_ignored)
2063{
2064 PyObject *list, *raw, *ref;
2065 int i, n;
2066
2067 list = PyList_New(0);
2068 if (list == NULL)
2069 return NULL;
2070 raw = type->tp_subclasses;
2071 if (raw == NULL)
2072 return list;
2073 assert(PyList_Check(raw));
2074 n = PyList_GET_SIZE(raw);
2075 for (i = 0; i < n; i++) {
2076 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00002077 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00002078 ref = PyWeakref_GET_OBJECT(ref);
2079 if (ref != Py_None) {
2080 if (PyList_Append(list, ref) < 0) {
2081 Py_DECREF(list);
2082 return NULL;
2083 }
2084 }
2085 }
2086 return list;
2087}
2088
Tim Peters6d6c1a32001-08-02 04:15:00 +00002089static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002090 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002091 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
Guido van Rossum1c450732001-10-08 15:18:27 +00002092 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002093 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002094 {0}
2095};
2096
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002097PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002098"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002099"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002100
Guido van Rossum048eb752001-10-02 21:24:57 +00002101static int
2102type_traverse(PyTypeObject *type, visitproc visit, void *arg)
2103{
Guido van Rossum048eb752001-10-02 21:24:57 +00002104 int err;
2105
Guido van Rossuma3862092002-06-10 15:24:42 +00002106 /* Because of type_is_gc(), the collector only calls this
2107 for heaptypes. */
2108 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002109
2110#define VISIT(SLOT) \
2111 if (SLOT) { \
2112 err = visit((PyObject *)(SLOT), arg); \
2113 if (err) \
2114 return err; \
2115 }
2116
2117 VISIT(type->tp_dict);
Guido van Rossum687ae002001-10-15 22:03:32 +00002118 VISIT(type->tp_cache);
Guido van Rossum048eb752001-10-02 21:24:57 +00002119 VISIT(type->tp_mro);
2120 VISIT(type->tp_bases);
2121 VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00002122
2123 /* There's no need to visit type->tp_subclasses or
Guido van Rossume5c691a2003-03-07 15:13:17 +00002124 ((PyHeapTypeObject *)type)->slots, because they can't be involved
Guido van Rossuma3862092002-06-10 15:24:42 +00002125 in cycles; tp_subclasses is a list of weak references,
2126 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00002127
2128#undef VISIT
2129
2130 return 0;
2131}
2132
2133static int
2134type_clear(PyTypeObject *type)
2135{
Guido van Rossum048eb752001-10-02 21:24:57 +00002136 PyObject *tmp;
2137
Guido van Rossuma3862092002-06-10 15:24:42 +00002138 /* Because of type_is_gc(), the collector only calls this
2139 for heaptypes. */
2140 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002141
2142#define CLEAR(SLOT) \
2143 if (SLOT) { \
2144 tmp = (PyObject *)(SLOT); \
2145 SLOT = NULL; \
2146 Py_DECREF(tmp); \
2147 }
2148
Guido van Rossuma3862092002-06-10 15:24:42 +00002149 /* The only field we need to clear is tp_mro, which is part of a
2150 hard cycle (its first element is the class itself) that won't
2151 be broken otherwise (it's a tuple and tuples don't have a
2152 tp_clear handler). None of the other fields need to be
2153 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00002154
Guido van Rossuma3862092002-06-10 15:24:42 +00002155 tp_dict:
2156 It is a dict, so the collector will call its tp_clear.
2157
2158 tp_cache:
2159 Not used; if it were, it would be a dict.
2160
2161 tp_bases, tp_base:
2162 If these are involved in a cycle, there must be at least
2163 one other, mutable object in the cycle, e.g. a base
2164 class's dict; the cycle will be broken that way.
2165
2166 tp_subclasses:
2167 A list of weak references can't be part of a cycle; and
2168 lists have their own tp_clear.
2169
Guido van Rossume5c691a2003-03-07 15:13:17 +00002170 slots (in PyHeapTypeObject):
Guido van Rossuma3862092002-06-10 15:24:42 +00002171 A tuple of strings can't be part of a cycle.
2172 */
2173
2174 CLEAR(type->tp_mro);
Tim Peters2f93e282001-10-04 05:27:00 +00002175
Guido van Rossum048eb752001-10-02 21:24:57 +00002176#undef CLEAR
2177
2178 return 0;
2179}
2180
2181static int
2182type_is_gc(PyTypeObject *type)
2183{
2184 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
2185}
2186
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002187PyTypeObject PyType_Type = {
2188 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002189 0, /* ob_size */
2190 "type", /* tp_name */
Guido van Rossume5c691a2003-03-07 15:13:17 +00002191 sizeof(PyHeapTypeObject), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00002192 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002193 (destructor)type_dealloc, /* tp_dealloc */
2194 0, /* tp_print */
2195 0, /* tp_getattr */
2196 0, /* tp_setattr */
2197 type_compare, /* tp_compare */
2198 (reprfunc)type_repr, /* tp_repr */
2199 0, /* tp_as_number */
2200 0, /* tp_as_sequence */
2201 0, /* tp_as_mapping */
2202 (hashfunc)_Py_HashPointer, /* tp_hash */
2203 (ternaryfunc)type_call, /* tp_call */
2204 0, /* tp_str */
2205 (getattrofunc)type_getattro, /* tp_getattro */
2206 (setattrofunc)type_setattro, /* tp_setattro */
2207 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00002208 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2209 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002210 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00002211 (traverseproc)type_traverse, /* tp_traverse */
2212 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002213 0, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00002214 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002215 0, /* tp_iter */
2216 0, /* tp_iternext */
2217 type_methods, /* tp_methods */
2218 type_members, /* tp_members */
2219 type_getsets, /* tp_getset */
2220 0, /* tp_base */
2221 0, /* tp_dict */
2222 0, /* tp_descr_get */
2223 0, /* tp_descr_set */
2224 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
2225 0, /* tp_init */
2226 0, /* tp_alloc */
2227 type_new, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002228 PyObject_GC_Del, /* tp_free */
Guido van Rossum048eb752001-10-02 21:24:57 +00002229 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002230};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002231
2232
2233/* The base type of all types (eventually)... except itself. */
2234
2235static int
2236object_init(PyObject *self, PyObject *args, PyObject *kwds)
2237{
2238 return 0;
2239}
2240
Guido van Rossum298e4212003-02-13 16:30:16 +00002241/* If we don't have a tp_new for a new-style class, new will use this one.
2242 Therefore this should take no arguments/keywords. However, this new may
2243 also be inherited by objects that define a tp_init but no tp_new. These
2244 objects WILL pass argumets to tp_new, because it gets the same args as
2245 tp_init. So only allow arguments if we aren't using the default init, in
2246 which case we expect init to handle argument parsing. */
2247static PyObject *
2248object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2249{
2250 if (type->tp_init == object_init && (PyTuple_GET_SIZE(args) ||
2251 (kwds && PyDict_Check(kwds) && PyDict_Size(kwds)))) {
2252 PyErr_SetString(PyExc_TypeError,
2253 "default __new__ takes no parameters");
2254 return NULL;
2255 }
2256 return type->tp_alloc(type, 0);
2257}
2258
Tim Peters6d6c1a32001-08-02 04:15:00 +00002259static void
2260object_dealloc(PyObject *self)
2261{
2262 self->ob_type->tp_free(self);
2263}
2264
Guido van Rossum8e248182001-08-12 05:17:56 +00002265static PyObject *
2266object_repr(PyObject *self)
2267{
Guido van Rossum76e69632001-08-16 18:52:43 +00002268 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00002269 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002270
Guido van Rossum76e69632001-08-16 18:52:43 +00002271 type = self->ob_type;
2272 mod = type_module(type, NULL);
2273 if (mod == NULL)
2274 PyErr_Clear();
2275 else if (!PyString_Check(mod)) {
2276 Py_DECREF(mod);
2277 mod = NULL;
2278 }
2279 name = type_name(type, NULL);
2280 if (name == NULL)
2281 return NULL;
2282 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002283 rtn = PyString_FromFormat("<%s.%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002284 PyString_AS_STRING(mod),
2285 PyString_AS_STRING(name),
2286 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002287 else
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002288 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002289 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002290 Py_XDECREF(mod);
2291 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00002292 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002293}
2294
Guido van Rossumb8f63662001-08-15 23:57:02 +00002295static PyObject *
2296object_str(PyObject *self)
2297{
2298 unaryfunc f;
2299
2300 f = self->ob_type->tp_repr;
2301 if (f == NULL)
2302 f = object_repr;
2303 return f(self);
2304}
2305
Guido van Rossum8e248182001-08-12 05:17:56 +00002306static long
2307object_hash(PyObject *self)
2308{
2309 return _Py_HashPointer(self);
2310}
Guido van Rossum8e248182001-08-12 05:17:56 +00002311
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002312static PyObject *
2313object_get_class(PyObject *self, void *closure)
2314{
2315 Py_INCREF(self->ob_type);
2316 return (PyObject *)(self->ob_type);
2317}
2318
2319static int
2320equiv_structs(PyTypeObject *a, PyTypeObject *b)
2321{
2322 return a == b ||
2323 (a != NULL &&
2324 b != NULL &&
2325 a->tp_basicsize == b->tp_basicsize &&
2326 a->tp_itemsize == b->tp_itemsize &&
2327 a->tp_dictoffset == b->tp_dictoffset &&
2328 a->tp_weaklistoffset == b->tp_weaklistoffset &&
2329 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
2330 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
2331}
2332
2333static int
2334same_slots_added(PyTypeObject *a, PyTypeObject *b)
2335{
2336 PyTypeObject *base = a->tp_base;
2337 int size;
2338
2339 if (base != b->tp_base)
2340 return 0;
2341 if (equiv_structs(a, base) && equiv_structs(b, base))
2342 return 1;
2343 size = base->tp_basicsize;
2344 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
2345 size += sizeof(PyObject *);
2346 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
2347 size += sizeof(PyObject *);
2348 return size == a->tp_basicsize && size == b->tp_basicsize;
2349}
2350
2351static int
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002352compatible_for_assignment(PyTypeObject* old, PyTypeObject* new, char* attr)
2353{
2354 PyTypeObject *newbase, *oldbase;
2355
2356 if (new->tp_dealloc != old->tp_dealloc ||
2357 new->tp_free != old->tp_free)
2358 {
2359 PyErr_Format(PyExc_TypeError,
2360 "%s assignment: "
2361 "'%s' deallocator differs from '%s'",
2362 attr,
2363 new->tp_name,
2364 old->tp_name);
2365 return 0;
2366 }
2367 newbase = new;
2368 oldbase = old;
2369 while (equiv_structs(newbase, newbase->tp_base))
2370 newbase = newbase->tp_base;
2371 while (equiv_structs(oldbase, oldbase->tp_base))
2372 oldbase = oldbase->tp_base;
2373 if (newbase != oldbase &&
2374 (newbase->tp_base != oldbase->tp_base ||
2375 !same_slots_added(newbase, oldbase))) {
2376 PyErr_Format(PyExc_TypeError,
2377 "%s assignment: "
2378 "'%s' object layout differs from '%s'",
2379 attr,
2380 new->tp_name,
2381 old->tp_name);
2382 return 0;
2383 }
Tim Petersea7f75d2002-12-07 21:39:16 +00002384
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002385 return 1;
2386}
2387
2388static int
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002389object_set_class(PyObject *self, PyObject *value, void *closure)
2390{
2391 PyTypeObject *old = self->ob_type;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002392 PyTypeObject *new;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002393
Guido van Rossumb6b89422002-04-15 01:03:30 +00002394 if (value == NULL) {
2395 PyErr_SetString(PyExc_TypeError,
2396 "can't delete __class__ attribute");
2397 return -1;
2398 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002399 if (!PyType_Check(value)) {
2400 PyErr_Format(PyExc_TypeError,
2401 "__class__ must be set to new-style class, not '%s' object",
2402 value->ob_type->tp_name);
2403 return -1;
2404 }
2405 new = (PyTypeObject *)value;
Guido van Rossum40af8892002-08-10 05:42:07 +00002406 if (!(new->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
2407 !(old->tp_flags & Py_TPFLAGS_HEAPTYPE))
2408 {
2409 PyErr_Format(PyExc_TypeError,
2410 "__class__ assignment: only for heap types");
2411 return -1;
2412 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002413 if (compatible_for_assignment(new, old, "__class__")) {
2414 Py_INCREF(new);
2415 self->ob_type = new;
2416 Py_DECREF(old);
2417 return 0;
2418 }
2419 else {
Guido van Rossum9ee4b942002-05-24 18:47:47 +00002420 return -1;
2421 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002422}
2423
2424static PyGetSetDef object_getsets[] = {
2425 {"__class__", object_get_class, object_set_class,
Neal Norwitz858e34f2002-08-13 17:18:45 +00002426 PyDoc_STR("the object's class")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002427 {0}
2428};
2429
Guido van Rossumc53f0092003-02-18 22:05:12 +00002430
Guido van Rossum036f9992003-02-21 22:02:54 +00002431/* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
2432 We fall back to helpers in copy_reg for:
2433 - pickle protocols < 2
2434 - calculating the list of slot names (done only once per class)
2435 - the __newobj__ function (which is used as a token but never called)
2436*/
2437
2438static PyObject *
2439import_copy_reg(void)
2440{
2441 static PyObject *copy_reg_str;
Guido van Rossum3926a632001-09-25 16:25:58 +00002442
2443 if (!copy_reg_str) {
2444 copy_reg_str = PyString_InternFromString("copy_reg");
2445 if (copy_reg_str == NULL)
2446 return NULL;
2447 }
Guido van Rossum036f9992003-02-21 22:02:54 +00002448
2449 return PyImport_Import(copy_reg_str);
2450}
2451
2452static PyObject *
2453slotnames(PyObject *cls)
2454{
2455 PyObject *clsdict;
2456 PyObject *copy_reg;
2457 PyObject *slotnames;
2458
2459 if (!PyType_Check(cls)) {
2460 Py_INCREF(Py_None);
2461 return Py_None;
2462 }
2463
2464 clsdict = ((PyTypeObject *)cls)->tp_dict;
2465 slotnames = PyDict_GetItemString(clsdict, "__slotnames__");
2466 if (slotnames != NULL) {
2467 Py_INCREF(slotnames);
2468 return slotnames;
2469 }
2470
2471 copy_reg = import_copy_reg();
2472 if (copy_reg == NULL)
2473 return NULL;
2474
2475 slotnames = PyObject_CallMethod(copy_reg, "_slotnames", "O", cls);
2476 Py_DECREF(copy_reg);
2477 if (slotnames != NULL &&
2478 slotnames != Py_None &&
2479 !PyList_Check(slotnames))
2480 {
2481 PyErr_SetString(PyExc_TypeError,
2482 "copy_reg._slotnames didn't return a list or None");
2483 Py_DECREF(slotnames);
2484 slotnames = NULL;
2485 }
2486
2487 return slotnames;
2488}
2489
2490static PyObject *
2491reduce_2(PyObject *obj)
2492{
2493 PyObject *cls, *getnewargs;
2494 PyObject *args = NULL, *args2 = NULL;
2495 PyObject *getstate = NULL, *state = NULL, *names = NULL;
2496 PyObject *slots = NULL, *listitems = NULL, *dictitems = NULL;
2497 PyObject *copy_reg = NULL, *newobj = NULL, *res = NULL;
2498 int i, n;
2499
2500 cls = PyObject_GetAttrString(obj, "__class__");
2501 if (cls == NULL)
2502 return NULL;
2503
2504 getnewargs = PyObject_GetAttrString(obj, "__getnewargs__");
2505 if (getnewargs != NULL) {
2506 args = PyObject_CallObject(getnewargs, NULL);
2507 Py_DECREF(getnewargs);
2508 if (args != NULL && !PyTuple_Check(args)) {
2509 PyErr_SetString(PyExc_TypeError,
2510 "__getnewargs__ should return a tuple");
2511 goto end;
2512 }
2513 }
2514 else {
2515 PyErr_Clear();
2516 args = PyTuple_New(0);
2517 }
2518 if (args == NULL)
2519 goto end;
2520
2521 getstate = PyObject_GetAttrString(obj, "__getstate__");
2522 if (getstate != NULL) {
2523 state = PyObject_CallObject(getstate, NULL);
2524 Py_DECREF(getstate);
2525 }
2526 else {
2527 state = PyObject_GetAttrString(obj, "__dict__");
2528 if (state == NULL) {
2529 PyErr_Clear();
2530 state = Py_None;
2531 Py_INCREF(state);
2532 }
2533 names = slotnames(cls);
2534 if (names == NULL)
2535 goto end;
2536 if (names != Py_None) {
2537 assert(PyList_Check(names));
2538 slots = PyDict_New();
2539 if (slots == NULL)
2540 goto end;
2541 n = 0;
2542 /* Can't pre-compute the list size; the list
2543 is stored on the class so accessible to other
2544 threads, which may be run by DECREF */
2545 for (i = 0; i < PyList_GET_SIZE(names); i++) {
2546 PyObject *name, *value;
2547 name = PyList_GET_ITEM(names, i);
2548 value = PyObject_GetAttr(obj, name);
2549 if (value == NULL)
2550 PyErr_Clear();
2551 else {
2552 int err = PyDict_SetItem(slots, name,
2553 value);
2554 Py_DECREF(value);
2555 if (err)
2556 goto end;
2557 n++;
2558 }
2559 }
2560 if (n) {
2561 state = Py_BuildValue("(NO)", state, slots);
2562 if (state == NULL)
2563 goto end;
2564 }
2565 }
2566 }
2567
2568 if (!PyList_Check(obj)) {
2569 listitems = Py_None;
2570 Py_INCREF(listitems);
2571 }
2572 else {
2573 listitems = PyObject_GetIter(obj);
2574 if (listitems == NULL)
2575 goto end;
2576 }
2577
2578 if (!PyDict_Check(obj)) {
2579 dictitems = Py_None;
2580 Py_INCREF(dictitems);
2581 }
2582 else {
2583 dictitems = PyObject_CallMethod(obj, "iteritems", "");
2584 if (dictitems == NULL)
2585 goto end;
2586 }
2587
2588 copy_reg = import_copy_reg();
2589 if (copy_reg == NULL)
2590 goto end;
2591 newobj = PyObject_GetAttrString(copy_reg, "__newobj__");
2592 if (newobj == NULL)
2593 goto end;
2594
2595 n = PyTuple_GET_SIZE(args);
2596 args2 = PyTuple_New(n+1);
2597 if (args2 == NULL)
2598 goto end;
2599 PyTuple_SET_ITEM(args2, 0, cls);
2600 cls = NULL;
2601 for (i = 0; i < n; i++) {
2602 PyObject *v = PyTuple_GET_ITEM(args, i);
2603 Py_INCREF(v);
2604 PyTuple_SET_ITEM(args2, i+1, v);
2605 }
2606
2607 res = Py_BuildValue("(OOOOO)",
2608 newobj, args2, state, listitems, dictitems);
2609
2610 end:
2611 Py_XDECREF(cls);
2612 Py_XDECREF(args);
2613 Py_XDECREF(args2);
2614 Py_XDECREF(state);
2615 Py_XDECREF(names);
2616 Py_XDECREF(listitems);
2617 Py_XDECREF(dictitems);
2618 Py_XDECREF(copy_reg);
2619 Py_XDECREF(newobj);
2620 return res;
2621}
2622
2623static PyObject *
2624object_reduce_ex(PyObject *self, PyObject *args)
2625{
2626 /* Call copy_reg._reduce_ex(self, proto) */
2627 PyObject *reduce, *copy_reg, *res;
2628 int proto = 0;
2629
2630 if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
2631 return NULL;
2632
2633 reduce = PyObject_GetAttrString(self, "__reduce__");
2634 if (reduce == NULL)
2635 PyErr_Clear();
2636 else {
2637 PyObject *cls, *clsreduce, *objreduce;
2638 int override;
2639 cls = PyObject_GetAttrString(self, "__class__");
2640 if (cls == NULL) {
2641 Py_DECREF(reduce);
2642 return NULL;
2643 }
2644 clsreduce = PyObject_GetAttrString(cls, "__reduce__");
2645 Py_DECREF(cls);
2646 if (clsreduce == NULL) {
2647 Py_DECREF(reduce);
2648 return NULL;
2649 }
2650 objreduce = PyDict_GetItemString(PyBaseObject_Type.tp_dict,
2651 "__reduce__");
2652 override = (clsreduce != objreduce);
2653 Py_DECREF(clsreduce);
2654 if (override) {
2655 res = PyObject_CallObject(reduce, NULL);
2656 Py_DECREF(reduce);
2657 return res;
2658 }
2659 else
2660 Py_DECREF(reduce);
2661 }
2662
2663 if (proto >= 2)
2664 return reduce_2(self);
2665
2666 copy_reg = import_copy_reg();
Guido van Rossum3926a632001-09-25 16:25:58 +00002667 if (!copy_reg)
2668 return NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00002669
Guido van Rossumc53f0092003-02-18 22:05:12 +00002670 res = PyEval_CallMethod(copy_reg, "_reduce_ex", "(Oi)", self, proto);
Guido van Rossum3926a632001-09-25 16:25:58 +00002671 Py_DECREF(copy_reg);
Guido van Rossum036f9992003-02-21 22:02:54 +00002672
Guido van Rossum3926a632001-09-25 16:25:58 +00002673 return res;
2674}
2675
2676static PyMethodDef object_methods[] = {
Guido van Rossumc53f0092003-02-18 22:05:12 +00002677 {"__reduce_ex__", object_reduce_ex, METH_VARARGS,
2678 PyDoc_STR("helper for pickle")},
2679 {"__reduce__", object_reduce_ex, METH_VARARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002680 PyDoc_STR("helper for pickle")},
Guido van Rossum3926a632001-09-25 16:25:58 +00002681 {0}
2682};
2683
Guido van Rossum036f9992003-02-21 22:02:54 +00002684
Tim Peters6d6c1a32001-08-02 04:15:00 +00002685PyTypeObject PyBaseObject_Type = {
2686 PyObject_HEAD_INIT(&PyType_Type)
2687 0, /* ob_size */
2688 "object", /* tp_name */
2689 sizeof(PyObject), /* tp_basicsize */
2690 0, /* tp_itemsize */
2691 (destructor)object_dealloc, /* tp_dealloc */
2692 0, /* tp_print */
2693 0, /* tp_getattr */
2694 0, /* tp_setattr */
2695 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002696 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002697 0, /* tp_as_number */
2698 0, /* tp_as_sequence */
2699 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002700 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002701 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002702 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002703 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002704 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002705 0, /* tp_as_buffer */
2706 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002707 PyDoc_STR("The most base type"), /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002708 0, /* tp_traverse */
2709 0, /* tp_clear */
2710 0, /* tp_richcompare */
2711 0, /* tp_weaklistoffset */
2712 0, /* tp_iter */
2713 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00002714 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002715 0, /* tp_members */
2716 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002717 0, /* tp_base */
2718 0, /* tp_dict */
2719 0, /* tp_descr_get */
2720 0, /* tp_descr_set */
2721 0, /* tp_dictoffset */
2722 object_init, /* tp_init */
2723 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossum298e4212003-02-13 16:30:16 +00002724 object_new, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002725 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002726};
2727
2728
2729/* Initialize the __dict__ in a type object */
2730
2731static int
2732add_methods(PyTypeObject *type, PyMethodDef *meth)
2733{
Guido van Rossum687ae002001-10-15 22:03:32 +00002734 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002735
2736 for (; meth->ml_name != NULL; meth++) {
2737 PyObject *descr;
2738 if (PyDict_GetItemString(dict, meth->ml_name))
2739 continue;
Fred Drake7bf97152002-03-28 05:33:33 +00002740 if (meth->ml_flags & METH_CLASS) {
2741 if (meth->ml_flags & METH_STATIC) {
2742 PyErr_SetString(PyExc_ValueError,
2743 "method cannot be both class and static");
2744 return -1;
2745 }
Tim Petersbca1cbc2002-12-09 22:56:13 +00002746 descr = PyDescr_NewClassMethod(type, meth);
Fred Drake7bf97152002-03-28 05:33:33 +00002747 }
2748 else if (meth->ml_flags & METH_STATIC) {
Guido van Rossum9af48ff2003-02-11 17:12:46 +00002749 PyObject *cfunc = PyCFunction_New(meth, NULL);
2750 if (cfunc == NULL)
2751 return -1;
2752 descr = PyStaticMethod_New(cfunc);
2753 Py_DECREF(cfunc);
Fred Drake7bf97152002-03-28 05:33:33 +00002754 }
2755 else {
2756 descr = PyDescr_NewMethod(type, meth);
2757 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002758 if (descr == NULL)
2759 return -1;
Fred Drake7bf97152002-03-28 05:33:33 +00002760 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002761 return -1;
2762 Py_DECREF(descr);
2763 }
2764 return 0;
2765}
2766
2767static int
Guido van Rossum6f799372001-09-20 20:46:19 +00002768add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002769{
Guido van Rossum687ae002001-10-15 22:03:32 +00002770 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002771
2772 for (; memb->name != NULL; memb++) {
2773 PyObject *descr;
2774 if (PyDict_GetItemString(dict, memb->name))
2775 continue;
2776 descr = PyDescr_NewMember(type, memb);
2777 if (descr == NULL)
2778 return -1;
2779 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
2780 return -1;
2781 Py_DECREF(descr);
2782 }
2783 return 0;
2784}
2785
2786static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00002787add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002788{
Guido van Rossum687ae002001-10-15 22:03:32 +00002789 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002790
2791 for (; gsp->name != NULL; gsp++) {
2792 PyObject *descr;
2793 if (PyDict_GetItemString(dict, gsp->name))
2794 continue;
2795 descr = PyDescr_NewGetSet(type, gsp);
2796
2797 if (descr == NULL)
2798 return -1;
2799 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
2800 return -1;
2801 Py_DECREF(descr);
2802 }
2803 return 0;
2804}
2805
Guido van Rossum13d52f02001-08-10 21:24:08 +00002806static void
2807inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002808{
2809 int oldsize, newsize;
2810
Guido van Rossum13d52f02001-08-10 21:24:08 +00002811 /* Special flag magic */
2812 if (!type->tp_as_buffer && base->tp_as_buffer) {
2813 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
2814 type->tp_flags |=
2815 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
2816 }
2817 if (!type->tp_as_sequence && base->tp_as_sequence) {
2818 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
2819 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
2820 }
2821 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
2822 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
2823 if ((!type->tp_as_number && base->tp_as_number) ||
2824 (!type->tp_as_sequence && base->tp_as_sequence)) {
2825 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
2826 if (!type->tp_as_number && !type->tp_as_sequence) {
2827 type->tp_flags |= base->tp_flags &
2828 Py_TPFLAGS_HAVE_INPLACEOPS;
2829 }
2830 }
2831 /* Wow */
2832 }
2833 if (!type->tp_as_number && base->tp_as_number) {
2834 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
2835 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
2836 }
2837
2838 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00002839 oldsize = base->tp_basicsize;
2840 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
2841 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
2842 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00002843 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
2844 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00002845 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00002846 if (type->tp_traverse == NULL)
2847 type->tp_traverse = base->tp_traverse;
2848 if (type->tp_clear == NULL)
2849 type->tp_clear = base->tp_clear;
2850 }
2851 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
Guido van Rossumf884b742001-12-17 17:14:22 +00002852 /* The condition below could use some explanation.
2853 It appears that tp_new is not inherited for static types
2854 whose base class is 'object'; this seems to be a precaution
2855 so that old extension types don't suddenly become
2856 callable (object.__new__ wouldn't insure the invariants
2857 that the extension type's own factory function ensures).
2858 Heap types, of course, are under our control, so they do
2859 inherit tp_new; static extension types that specify some
2860 other built-in type as the default are considered
2861 new-style-aware so they also inherit object.__new__. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002862 if (base != &PyBaseObject_Type ||
2863 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2864 if (type->tp_new == NULL)
2865 type->tp_new = base->tp_new;
2866 }
2867 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00002868 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00002869
2870 /* Copy other non-function slots */
2871
2872#undef COPYVAL
2873#define COPYVAL(SLOT) \
2874 if (type->SLOT == 0) type->SLOT = base->SLOT
2875
2876 COPYVAL(tp_itemsize);
2877 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
2878 COPYVAL(tp_weaklistoffset);
2879 }
2880 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2881 COPYVAL(tp_dictoffset);
2882 }
Guido van Rossum13d52f02001-08-10 21:24:08 +00002883}
2884
2885static void
2886inherit_slots(PyTypeObject *type, PyTypeObject *base)
2887{
2888 PyTypeObject *basebase;
2889
2890#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00002891#undef COPYSLOT
2892#undef COPYNUM
2893#undef COPYSEQ
2894#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00002895#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00002896
2897#define SLOTDEFINED(SLOT) \
2898 (base->SLOT != 0 && \
2899 (basebase == NULL || base->SLOT != basebase->SLOT))
2900
Tim Peters6d6c1a32001-08-02 04:15:00 +00002901#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00002902 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00002903
2904#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
2905#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
2906#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00002907#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002908
Guido van Rossum13d52f02001-08-10 21:24:08 +00002909 /* This won't inherit indirect slots (from tp_as_number etc.)
2910 if type doesn't provide the space. */
2911
2912 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
2913 basebase = base->tp_base;
2914 if (basebase->tp_as_number == NULL)
2915 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002916 COPYNUM(nb_add);
2917 COPYNUM(nb_subtract);
2918 COPYNUM(nb_multiply);
2919 COPYNUM(nb_divide);
2920 COPYNUM(nb_remainder);
2921 COPYNUM(nb_divmod);
2922 COPYNUM(nb_power);
2923 COPYNUM(nb_negative);
2924 COPYNUM(nb_positive);
2925 COPYNUM(nb_absolute);
2926 COPYNUM(nb_nonzero);
2927 COPYNUM(nb_invert);
2928 COPYNUM(nb_lshift);
2929 COPYNUM(nb_rshift);
2930 COPYNUM(nb_and);
2931 COPYNUM(nb_xor);
2932 COPYNUM(nb_or);
2933 COPYNUM(nb_coerce);
2934 COPYNUM(nb_int);
2935 COPYNUM(nb_long);
2936 COPYNUM(nb_float);
2937 COPYNUM(nb_oct);
2938 COPYNUM(nb_hex);
2939 COPYNUM(nb_inplace_add);
2940 COPYNUM(nb_inplace_subtract);
2941 COPYNUM(nb_inplace_multiply);
2942 COPYNUM(nb_inplace_divide);
2943 COPYNUM(nb_inplace_remainder);
2944 COPYNUM(nb_inplace_power);
2945 COPYNUM(nb_inplace_lshift);
2946 COPYNUM(nb_inplace_rshift);
2947 COPYNUM(nb_inplace_and);
2948 COPYNUM(nb_inplace_xor);
2949 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00002950 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
2951 COPYNUM(nb_true_divide);
2952 COPYNUM(nb_floor_divide);
2953 COPYNUM(nb_inplace_true_divide);
2954 COPYNUM(nb_inplace_floor_divide);
2955 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002956 }
2957
Guido van Rossum13d52f02001-08-10 21:24:08 +00002958 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
2959 basebase = base->tp_base;
2960 if (basebase->tp_as_sequence == NULL)
2961 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002962 COPYSEQ(sq_length);
2963 COPYSEQ(sq_concat);
2964 COPYSEQ(sq_repeat);
2965 COPYSEQ(sq_item);
2966 COPYSEQ(sq_slice);
2967 COPYSEQ(sq_ass_item);
2968 COPYSEQ(sq_ass_slice);
2969 COPYSEQ(sq_contains);
2970 COPYSEQ(sq_inplace_concat);
2971 COPYSEQ(sq_inplace_repeat);
2972 }
2973
Guido van Rossum13d52f02001-08-10 21:24:08 +00002974 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
2975 basebase = base->tp_base;
2976 if (basebase->tp_as_mapping == NULL)
2977 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002978 COPYMAP(mp_length);
2979 COPYMAP(mp_subscript);
2980 COPYMAP(mp_ass_subscript);
2981 }
2982
Tim Petersfc57ccb2001-10-12 02:38:24 +00002983 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
2984 basebase = base->tp_base;
2985 if (basebase->tp_as_buffer == NULL)
2986 basebase = NULL;
2987 COPYBUF(bf_getreadbuffer);
2988 COPYBUF(bf_getwritebuffer);
2989 COPYBUF(bf_getsegcount);
2990 COPYBUF(bf_getcharbuffer);
2991 }
2992
Guido van Rossum13d52f02001-08-10 21:24:08 +00002993 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002994
Tim Peters6d6c1a32001-08-02 04:15:00 +00002995 COPYSLOT(tp_dealloc);
2996 COPYSLOT(tp_print);
2997 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
2998 type->tp_getattr = base->tp_getattr;
2999 type->tp_getattro = base->tp_getattro;
3000 }
3001 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
3002 type->tp_setattr = base->tp_setattr;
3003 type->tp_setattro = base->tp_setattro;
3004 }
3005 /* tp_compare see tp_richcompare */
3006 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003007 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003008 COPYSLOT(tp_call);
3009 COPYSLOT(tp_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003010 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003011 if (type->tp_compare == NULL &&
3012 type->tp_richcompare == NULL &&
3013 type->tp_hash == NULL)
3014 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003015 type->tp_compare = base->tp_compare;
3016 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003017 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003018 }
3019 }
3020 else {
3021 COPYSLOT(tp_compare);
3022 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003023 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
3024 COPYSLOT(tp_iter);
3025 COPYSLOT(tp_iternext);
3026 }
3027 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
3028 COPYSLOT(tp_descr_get);
3029 COPYSLOT(tp_descr_set);
3030 COPYSLOT(tp_dictoffset);
3031 COPYSLOT(tp_init);
3032 COPYSLOT(tp_alloc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003033 COPYSLOT(tp_free);
Guido van Rossumcc8fe042002-04-05 17:10:16 +00003034 COPYSLOT(tp_is_gc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003035 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003036}
3037
Jeremy Hylton938ace62002-07-17 16:30:39 +00003038static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00003039
Tim Peters6d6c1a32001-08-02 04:15:00 +00003040int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00003041PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003042{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003043 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003044 PyTypeObject *base;
3045 int i, n;
3046
Guido van Rossumcab05802002-06-10 15:29:03 +00003047 if (type->tp_flags & Py_TPFLAGS_READY) {
3048 assert(type->tp_dict != NULL);
Guido van Rossumd614f972001-08-10 17:39:49 +00003049 return 0;
Guido van Rossumcab05802002-06-10 15:29:03 +00003050 }
Guido van Rossumd614f972001-08-10 17:39:49 +00003051 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00003052
3053 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003054
Tim Peters36eb4df2003-03-23 03:33:13 +00003055#ifdef Py_TRACE_REFS
3056 /* PyType_Ready is the closest thing we have to a choke point
3057 * for type objects, so is the best place I can think of to try
3058 * to get type objects into the doubly-linked list of all objects.
3059 * Still, not all type objects go thru PyType_Ready.
3060 */
3061 if (type->_ob_next == NULL) {
3062 assert(type->_ob_prev == NULL);
3063 _Py_AddToAllObjects((PyObject *)type);
3064 }
3065#endif
3066
Tim Peters6d6c1a32001-08-02 04:15:00 +00003067 /* Initialize tp_base (defaults to BaseObject unless that's us) */
3068 base = type->tp_base;
3069 if (base == NULL && type != &PyBaseObject_Type)
3070 base = type->tp_base = &PyBaseObject_Type;
3071
Guido van Rossum323a9cf2002-08-14 17:26:30 +00003072 /* Initialize the base class */
3073 if (base && base->tp_dict == NULL) {
3074 if (PyType_Ready(base) < 0)
3075 goto error;
3076 }
3077
Guido van Rossum0986d822002-04-08 01:38:42 +00003078 /* Initialize ob_type if NULL. This means extensions that want to be
3079 compilable separately on Windows can call PyType_Ready() instead of
3080 initializing the ob_type field of their type objects. */
3081 if (type->ob_type == NULL)
3082 type->ob_type = base->ob_type;
3083
Tim Peters6d6c1a32001-08-02 04:15:00 +00003084 /* Initialize tp_bases */
3085 bases = type->tp_bases;
3086 if (bases == NULL) {
3087 if (base == NULL)
3088 bases = PyTuple_New(0);
3089 else
3090 bases = Py_BuildValue("(O)", base);
3091 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003092 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003093 type->tp_bases = bases;
3094 }
3095
Guido van Rossum687ae002001-10-15 22:03:32 +00003096 /* Initialize tp_dict */
3097 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003098 if (dict == NULL) {
3099 dict = PyDict_New();
3100 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003101 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00003102 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003103 }
3104
Guido van Rossum687ae002001-10-15 22:03:32 +00003105 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003106 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003107 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003108 if (type->tp_methods != NULL) {
3109 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003110 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003111 }
3112 if (type->tp_members != NULL) {
3113 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003114 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003115 }
3116 if (type->tp_getset != NULL) {
3117 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003118 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003119 }
3120
Tim Peters6d6c1a32001-08-02 04:15:00 +00003121 /* Calculate method resolution order */
3122 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00003123 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003124 }
3125
Guido van Rossum13d52f02001-08-10 21:24:08 +00003126 /* Inherit special flags from dominant base */
3127 if (type->tp_base != NULL)
3128 inherit_special(type, type->tp_base);
3129
Tim Peters6d6c1a32001-08-02 04:15:00 +00003130 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003131 bases = type->tp_mro;
3132 assert(bases != NULL);
3133 assert(PyTuple_Check(bases));
3134 n = PyTuple_GET_SIZE(bases);
3135 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003136 PyObject *b = PyTuple_GET_ITEM(bases, i);
3137 if (PyType_Check(b))
3138 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003139 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003140
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003141 /* if the type dictionary doesn't contain a __doc__, set it from
3142 the tp_doc slot.
3143 */
3144 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
3145 if (type->tp_doc != NULL) {
3146 PyObject *doc = PyString_FromString(type->tp_doc);
3147 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
3148 Py_DECREF(doc);
3149 } else {
Guido van Rossumd4641072002-04-03 02:13:37 +00003150 PyDict_SetItemString(type->tp_dict,
3151 "__doc__", Py_None);
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003152 }
3153 }
3154
Guido van Rossum13d52f02001-08-10 21:24:08 +00003155 /* Some more special stuff */
3156 base = type->tp_base;
3157 if (base != NULL) {
3158 if (type->tp_as_number == NULL)
3159 type->tp_as_number = base->tp_as_number;
3160 if (type->tp_as_sequence == NULL)
3161 type->tp_as_sequence = base->tp_as_sequence;
3162 if (type->tp_as_mapping == NULL)
3163 type->tp_as_mapping = base->tp_as_mapping;
Guido van Rossumeea47182003-02-11 20:39:59 +00003164 if (type->tp_as_buffer == NULL)
3165 type->tp_as_buffer = base->tp_as_buffer;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003166 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003167
Guido van Rossum1c450732001-10-08 15:18:27 +00003168 /* Link into each base class's list of subclasses */
3169 bases = type->tp_bases;
3170 n = PyTuple_GET_SIZE(bases);
3171 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003172 PyObject *b = PyTuple_GET_ITEM(bases, i);
3173 if (PyType_Check(b) &&
3174 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00003175 goto error;
3176 }
3177
Guido van Rossum13d52f02001-08-10 21:24:08 +00003178 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00003179 assert(type->tp_dict != NULL);
3180 type->tp_flags =
3181 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003182 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00003183
3184 error:
3185 type->tp_flags &= ~Py_TPFLAGS_READYING;
3186 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003187}
3188
Guido van Rossum1c450732001-10-08 15:18:27 +00003189static int
3190add_subclass(PyTypeObject *base, PyTypeObject *type)
3191{
3192 int i;
3193 PyObject *list, *ref, *new;
3194
3195 list = base->tp_subclasses;
3196 if (list == NULL) {
3197 base->tp_subclasses = list = PyList_New(0);
3198 if (list == NULL)
3199 return -1;
3200 }
3201 assert(PyList_Check(list));
3202 new = PyWeakref_NewRef((PyObject *)type, NULL);
3203 i = PyList_GET_SIZE(list);
3204 while (--i >= 0) {
3205 ref = PyList_GET_ITEM(list, i);
3206 assert(PyWeakref_CheckRef(ref));
Guido van Rossum3930bc32002-10-18 13:51:49 +00003207 if (PyWeakref_GET_OBJECT(ref) == Py_None)
3208 return PyList_SetItem(list, i, new);
Guido van Rossum1c450732001-10-08 15:18:27 +00003209 }
3210 i = PyList_Append(list, new);
3211 Py_DECREF(new);
3212 return i;
3213}
3214
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003215static void
3216remove_subclass(PyTypeObject *base, PyTypeObject *type)
3217{
3218 int i;
3219 PyObject *list, *ref;
3220
3221 list = base->tp_subclasses;
3222 if (list == NULL) {
3223 return;
3224 }
3225 assert(PyList_Check(list));
3226 i = PyList_GET_SIZE(list);
3227 while (--i >= 0) {
3228 ref = PyList_GET_ITEM(list, i);
3229 assert(PyWeakref_CheckRef(ref));
3230 if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
3231 /* this can't fail, right? */
3232 PySequence_DelItem(list, i);
3233 return;
3234 }
3235 }
3236}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003237
3238/* Generic wrappers for overloadable 'operators' such as __getitem__ */
3239
3240/* There's a wrapper *function* for each distinct function typedef used
3241 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
3242 wrapper *table* for each distinct operation (e.g. __len__, __add__).
3243 Most tables have only one entry; the tables for binary operators have two
3244 entries, one regular and one with reversed arguments. */
3245
3246static PyObject *
3247wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
3248{
3249 inquiry func = (inquiry)wrapped;
3250 int res;
3251
3252 if (!PyArg_ParseTuple(args, ""))
3253 return NULL;
3254 res = (*func)(self);
3255 if (res == -1 && PyErr_Occurred())
3256 return NULL;
3257 return PyInt_FromLong((long)res);
3258}
3259
Tim Peters6d6c1a32001-08-02 04:15:00 +00003260static PyObject *
3261wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
3262{
3263 binaryfunc func = (binaryfunc)wrapped;
3264 PyObject *other;
3265
3266 if (!PyArg_ParseTuple(args, "O", &other))
3267 return NULL;
3268 return (*func)(self, other);
3269}
3270
3271static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003272wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
3273{
3274 binaryfunc func = (binaryfunc)wrapped;
3275 PyObject *other;
3276
3277 if (!PyArg_ParseTuple(args, "O", &other))
3278 return NULL;
3279 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003280 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003281 Py_INCREF(Py_NotImplemented);
3282 return Py_NotImplemented;
3283 }
3284 return (*func)(self, other);
3285}
3286
3287static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003288wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3289{
3290 binaryfunc func = (binaryfunc)wrapped;
3291 PyObject *other;
3292
3293 if (!PyArg_ParseTuple(args, "O", &other))
3294 return NULL;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003295 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003296 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003297 Py_INCREF(Py_NotImplemented);
3298 return Py_NotImplemented;
3299 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003300 return (*func)(other, self);
3301}
3302
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003303static PyObject *
3304wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
3305{
3306 coercion func = (coercion)wrapped;
3307 PyObject *other, *res;
3308 int ok;
3309
3310 if (!PyArg_ParseTuple(args, "O", &other))
3311 return NULL;
3312 ok = func(&self, &other);
3313 if (ok < 0)
3314 return NULL;
3315 if (ok > 0) {
3316 Py_INCREF(Py_NotImplemented);
3317 return Py_NotImplemented;
3318 }
3319 res = PyTuple_New(2);
3320 if (res == NULL) {
3321 Py_DECREF(self);
3322 Py_DECREF(other);
3323 return NULL;
3324 }
3325 PyTuple_SET_ITEM(res, 0, self);
3326 PyTuple_SET_ITEM(res, 1, other);
3327 return res;
3328}
3329
Tim Peters6d6c1a32001-08-02 04:15:00 +00003330static PyObject *
3331wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
3332{
3333 ternaryfunc func = (ternaryfunc)wrapped;
3334 PyObject *other;
3335 PyObject *third = Py_None;
3336
3337 /* Note: This wrapper only works for __pow__() */
3338
3339 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
3340 return NULL;
3341 return (*func)(self, other, third);
3342}
3343
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00003344static PyObject *
3345wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3346{
3347 ternaryfunc func = (ternaryfunc)wrapped;
3348 PyObject *other;
3349 PyObject *third = Py_None;
3350
3351 /* Note: This wrapper only works for __pow__() */
3352
3353 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
3354 return NULL;
3355 return (*func)(other, self, third);
3356}
3357
Tim Peters6d6c1a32001-08-02 04:15:00 +00003358static PyObject *
3359wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
3360{
3361 unaryfunc func = (unaryfunc)wrapped;
3362
3363 if (!PyArg_ParseTuple(args, ""))
3364 return NULL;
3365 return (*func)(self);
3366}
3367
Tim Peters6d6c1a32001-08-02 04:15:00 +00003368static PyObject *
3369wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
3370{
3371 intargfunc func = (intargfunc)wrapped;
3372 int i;
3373
3374 if (!PyArg_ParseTuple(args, "i", &i))
3375 return NULL;
3376 return (*func)(self, i);
3377}
3378
Guido van Rossum5d815f32001-08-17 21:57:47 +00003379static int
3380getindex(PyObject *self, PyObject *arg)
3381{
3382 int i;
3383
3384 i = PyInt_AsLong(arg);
3385 if (i == -1 && PyErr_Occurred())
3386 return -1;
3387 if (i < 0) {
3388 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
3389 if (sq && sq->sq_length) {
3390 int n = (*sq->sq_length)(self);
3391 if (n < 0)
3392 return -1;
3393 i += n;
3394 }
3395 }
3396 return i;
3397}
3398
3399static PyObject *
3400wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
3401{
3402 intargfunc func = (intargfunc)wrapped;
3403 PyObject *arg;
3404 int i;
3405
Guido van Rossumf4593e02001-10-03 12:09:30 +00003406 if (PyTuple_GET_SIZE(args) == 1) {
3407 arg = PyTuple_GET_ITEM(args, 0);
3408 i = getindex(self, arg);
3409 if (i == -1 && PyErr_Occurred())
3410 return NULL;
3411 return (*func)(self, i);
3412 }
3413 PyArg_ParseTuple(args, "O", &arg);
3414 assert(PyErr_Occurred());
3415 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003416}
3417
Tim Peters6d6c1a32001-08-02 04:15:00 +00003418static PyObject *
3419wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
3420{
3421 intintargfunc func = (intintargfunc)wrapped;
3422 int i, j;
3423
3424 if (!PyArg_ParseTuple(args, "ii", &i, &j))
3425 return NULL;
3426 return (*func)(self, i, j);
3427}
3428
Tim Peters6d6c1a32001-08-02 04:15:00 +00003429static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003430wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003431{
3432 intobjargproc func = (intobjargproc)wrapped;
3433 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003434 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003435
Guido van Rossum5d815f32001-08-17 21:57:47 +00003436 if (!PyArg_ParseTuple(args, "OO", &arg, &value))
3437 return NULL;
3438 i = getindex(self, arg);
3439 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00003440 return NULL;
3441 res = (*func)(self, i, value);
3442 if (res == -1 && PyErr_Occurred())
3443 return NULL;
3444 Py_INCREF(Py_None);
3445 return Py_None;
3446}
3447
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003448static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003449wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003450{
3451 intobjargproc func = (intobjargproc)wrapped;
3452 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003453 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003454
Guido van Rossum5d815f32001-08-17 21:57:47 +00003455 if (!PyArg_ParseTuple(args, "O", &arg))
3456 return NULL;
3457 i = getindex(self, arg);
3458 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003459 return NULL;
3460 res = (*func)(self, i, NULL);
3461 if (res == -1 && PyErr_Occurred())
3462 return NULL;
3463 Py_INCREF(Py_None);
3464 return Py_None;
3465}
3466
Tim Peters6d6c1a32001-08-02 04:15:00 +00003467static PyObject *
3468wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
3469{
3470 intintobjargproc func = (intintobjargproc)wrapped;
3471 int i, j, res;
3472 PyObject *value;
3473
3474 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
3475 return NULL;
3476 res = (*func)(self, i, j, value);
3477 if (res == -1 && PyErr_Occurred())
3478 return NULL;
3479 Py_INCREF(Py_None);
3480 return Py_None;
3481}
3482
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003483static PyObject *
3484wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
3485{
3486 intintobjargproc func = (intintobjargproc)wrapped;
3487 int i, j, res;
3488
3489 if (!PyArg_ParseTuple(args, "ii", &i, &j))
3490 return NULL;
3491 res = (*func)(self, i, j, NULL);
3492 if (res == -1 && PyErr_Occurred())
3493 return NULL;
3494 Py_INCREF(Py_None);
3495 return Py_None;
3496}
3497
Tim Peters6d6c1a32001-08-02 04:15:00 +00003498/* XXX objobjproc is a misnomer; should be objargpred */
3499static PyObject *
3500wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
3501{
3502 objobjproc func = (objobjproc)wrapped;
3503 int res;
3504 PyObject *value;
3505
3506 if (!PyArg_ParseTuple(args, "O", &value))
3507 return NULL;
3508 res = (*func)(self, value);
3509 if (res == -1 && PyErr_Occurred())
3510 return NULL;
3511 return PyInt_FromLong((long)res);
3512}
3513
Tim Peters6d6c1a32001-08-02 04:15:00 +00003514static PyObject *
3515wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
3516{
3517 objobjargproc func = (objobjargproc)wrapped;
3518 int res;
3519 PyObject *key, *value;
3520
3521 if (!PyArg_ParseTuple(args, "OO", &key, &value))
3522 return NULL;
3523 res = (*func)(self, key, value);
3524 if (res == -1 && PyErr_Occurred())
3525 return NULL;
3526 Py_INCREF(Py_None);
3527 return Py_None;
3528}
3529
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003530static PyObject *
3531wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
3532{
3533 objobjargproc func = (objobjargproc)wrapped;
3534 int res;
3535 PyObject *key;
3536
3537 if (!PyArg_ParseTuple(args, "O", &key))
3538 return NULL;
3539 res = (*func)(self, key, NULL);
3540 if (res == -1 && PyErr_Occurred())
3541 return NULL;
3542 Py_INCREF(Py_None);
3543 return Py_None;
3544}
3545
Tim Peters6d6c1a32001-08-02 04:15:00 +00003546static PyObject *
3547wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
3548{
3549 cmpfunc func = (cmpfunc)wrapped;
3550 int res;
3551 PyObject *other;
3552
3553 if (!PyArg_ParseTuple(args, "O", &other))
3554 return NULL;
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00003555 if (other->ob_type->tp_compare != func &&
3556 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00003557 PyErr_Format(
3558 PyExc_TypeError,
3559 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
3560 self->ob_type->tp_name,
3561 self->ob_type->tp_name,
3562 other->ob_type->tp_name);
3563 return NULL;
3564 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003565 res = (*func)(self, other);
3566 if (PyErr_Occurred())
3567 return NULL;
3568 return PyInt_FromLong((long)res);
3569}
3570
Tim Peters6d6c1a32001-08-02 04:15:00 +00003571static PyObject *
3572wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
3573{
3574 setattrofunc func = (setattrofunc)wrapped;
3575 int res;
3576 PyObject *name, *value;
3577
3578 if (!PyArg_ParseTuple(args, "OO", &name, &value))
3579 return NULL;
3580 res = (*func)(self, name, value);
3581 if (res < 0)
3582 return NULL;
3583 Py_INCREF(Py_None);
3584 return Py_None;
3585}
3586
3587static PyObject *
3588wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
3589{
3590 setattrofunc func = (setattrofunc)wrapped;
3591 int res;
3592 PyObject *name;
3593
3594 if (!PyArg_ParseTuple(args, "O", &name))
3595 return NULL;
3596 res = (*func)(self, name, NULL);
3597 if (res < 0)
3598 return NULL;
3599 Py_INCREF(Py_None);
3600 return Py_None;
3601}
3602
Tim Peters6d6c1a32001-08-02 04:15:00 +00003603static PyObject *
3604wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
3605{
3606 hashfunc func = (hashfunc)wrapped;
3607 long res;
3608
3609 if (!PyArg_ParseTuple(args, ""))
3610 return NULL;
3611 res = (*func)(self);
3612 if (res == -1 && PyErr_Occurred())
3613 return NULL;
3614 return PyInt_FromLong(res);
3615}
3616
Tim Peters6d6c1a32001-08-02 04:15:00 +00003617static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00003618wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003619{
3620 ternaryfunc func = (ternaryfunc)wrapped;
3621
Guido van Rossumc8e56452001-10-22 00:43:43 +00003622 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003623}
3624
Tim Peters6d6c1a32001-08-02 04:15:00 +00003625static PyObject *
3626wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
3627{
3628 richcmpfunc func = (richcmpfunc)wrapped;
3629 PyObject *other;
3630
3631 if (!PyArg_ParseTuple(args, "O", &other))
3632 return NULL;
3633 return (*func)(self, other, op);
3634}
3635
3636#undef RICHCMP_WRAPPER
3637#define RICHCMP_WRAPPER(NAME, OP) \
3638static PyObject * \
3639richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
3640{ \
3641 return wrap_richcmpfunc(self, args, wrapped, OP); \
3642}
3643
Jack Jansen8e938b42001-08-08 15:29:49 +00003644RICHCMP_WRAPPER(lt, Py_LT)
3645RICHCMP_WRAPPER(le, Py_LE)
3646RICHCMP_WRAPPER(eq, Py_EQ)
3647RICHCMP_WRAPPER(ne, Py_NE)
3648RICHCMP_WRAPPER(gt, Py_GT)
3649RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003650
Tim Peters6d6c1a32001-08-02 04:15:00 +00003651static PyObject *
3652wrap_next(PyObject *self, PyObject *args, void *wrapped)
3653{
3654 unaryfunc func = (unaryfunc)wrapped;
3655 PyObject *res;
3656
3657 if (!PyArg_ParseTuple(args, ""))
3658 return NULL;
3659 res = (*func)(self);
3660 if (res == NULL && !PyErr_Occurred())
3661 PyErr_SetNone(PyExc_StopIteration);
3662 return res;
3663}
3664
Tim Peters6d6c1a32001-08-02 04:15:00 +00003665static PyObject *
3666wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
3667{
3668 descrgetfunc func = (descrgetfunc)wrapped;
3669 PyObject *obj;
3670 PyObject *type = NULL;
3671
3672 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
3673 return NULL;
Guido van Rossum82ed25c2003-02-11 16:25:43 +00003674 if (obj == Py_None)
3675 obj = NULL;
3676 if (type == Py_None)
3677 type = NULL;
3678 if (type == NULL &&obj == NULL) {
3679 PyErr_SetString(PyExc_TypeError,
3680 "__get__(None, None) is invalid");
3681 return NULL;
3682 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003683 return (*func)(self, obj, type);
3684}
3685
Tim Peters6d6c1a32001-08-02 04:15:00 +00003686static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003687wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003688{
3689 descrsetfunc func = (descrsetfunc)wrapped;
3690 PyObject *obj, *value;
3691 int ret;
3692
3693 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
3694 return NULL;
3695 ret = (*func)(self, obj, value);
3696 if (ret < 0)
3697 return NULL;
3698 Py_INCREF(Py_None);
3699 return Py_None;
3700}
Guido van Rossum22b13872002-08-06 21:41:44 +00003701
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00003702static PyObject *
3703wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
3704{
3705 descrsetfunc func = (descrsetfunc)wrapped;
3706 PyObject *obj;
3707 int ret;
3708
3709 if (!PyArg_ParseTuple(args, "O", &obj))
3710 return NULL;
3711 ret = (*func)(self, obj, NULL);
3712 if (ret < 0)
3713 return NULL;
3714 Py_INCREF(Py_None);
3715 return Py_None;
3716}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003717
Tim Peters6d6c1a32001-08-02 04:15:00 +00003718static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00003719wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003720{
3721 initproc func = (initproc)wrapped;
3722
Guido van Rossumc8e56452001-10-22 00:43:43 +00003723 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003724 return NULL;
3725 Py_INCREF(Py_None);
3726 return Py_None;
3727}
3728
Tim Peters6d6c1a32001-08-02 04:15:00 +00003729static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003730tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003731{
Barry Warsaw60f01882001-08-22 19:24:42 +00003732 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003733 PyObject *arg0, *res;
3734
3735 if (self == NULL || !PyType_Check(self))
3736 Py_FatalError("__new__() called with non-type 'self'");
3737 type = (PyTypeObject *)self;
3738 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003739 PyErr_Format(PyExc_TypeError,
3740 "%s.__new__(): not enough arguments",
3741 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003742 return NULL;
3743 }
3744 arg0 = PyTuple_GET_ITEM(args, 0);
3745 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003746 PyErr_Format(PyExc_TypeError,
3747 "%s.__new__(X): X is not a type object (%s)",
3748 type->tp_name,
3749 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003750 return NULL;
3751 }
3752 subtype = (PyTypeObject *)arg0;
3753 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003754 PyErr_Format(PyExc_TypeError,
3755 "%s.__new__(%s): %s is not a subtype of %s",
3756 type->tp_name,
3757 subtype->tp_name,
3758 subtype->tp_name,
3759 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003760 return NULL;
3761 }
Barry Warsaw60f01882001-08-22 19:24:42 +00003762
3763 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00003764 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00003765 most derived base that's not a heap type is this type. */
3766 staticbase = subtype;
3767 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
3768 staticbase = staticbase->tp_base;
Guido van Rossuma8c60f42001-09-14 19:43:36 +00003769 if (staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003770 PyErr_Format(PyExc_TypeError,
3771 "%s.__new__(%s) is not safe, use %s.__new__()",
3772 type->tp_name,
3773 subtype->tp_name,
3774 staticbase == NULL ? "?" : staticbase->tp_name);
3775 return NULL;
3776 }
3777
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003778 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
3779 if (args == NULL)
3780 return NULL;
3781 res = type->tp_new(subtype, args, kwds);
3782 Py_DECREF(args);
3783 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003784}
3785
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003786static struct PyMethodDef tp_new_methoddef[] = {
3787 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00003788 PyDoc_STR("T.__new__(S, ...) -> "
3789 "a new object with type S, a subtype of T")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00003790 {0}
3791};
3792
3793static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003794add_tp_new_wrapper(PyTypeObject *type)
3795{
Guido van Rossumf040ede2001-08-07 16:40:56 +00003796 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003797
Guido van Rossum687ae002001-10-15 22:03:32 +00003798 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00003799 return 0;
3800 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003801 if (func == NULL)
3802 return -1;
Guido van Rossum687ae002001-10-15 22:03:32 +00003803 return PyDict_SetItemString(type->tp_dict, "__new__", func);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003804}
3805
Guido van Rossumf040ede2001-08-07 16:40:56 +00003806/* Slot wrappers that call the corresponding __foo__ slot. See comments
3807 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003808
Guido van Rossumdc91b992001-08-08 22:26:22 +00003809#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003810static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003811FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003812{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00003813 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003814 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003815}
3816
Guido van Rossumdc91b992001-08-08 22:26:22 +00003817#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003818static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003819FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003820{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003821 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003822 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003823}
3824
Guido van Rossumcd118802003-01-06 22:57:47 +00003825/* Boolean helper for SLOT1BINFULL().
3826 right.__class__ is a nontrivial subclass of left.__class__. */
3827static int
3828method_is_overloaded(PyObject *left, PyObject *right, char *name)
3829{
3830 PyObject *a, *b;
3831 int ok;
3832
3833 b = PyObject_GetAttrString((PyObject *)(right->ob_type), name);
3834 if (b == NULL) {
3835 PyErr_Clear();
3836 /* If right doesn't have it, it's not overloaded */
3837 return 0;
3838 }
3839
3840 a = PyObject_GetAttrString((PyObject *)(left->ob_type), name);
3841 if (a == NULL) {
3842 PyErr_Clear();
3843 Py_DECREF(b);
3844 /* If right has it but left doesn't, it's overloaded */
3845 return 1;
3846 }
3847
3848 ok = PyObject_RichCompareBool(a, b, Py_NE);
3849 Py_DECREF(a);
3850 Py_DECREF(b);
3851 if (ok < 0) {
3852 PyErr_Clear();
3853 return 0;
3854 }
3855
3856 return ok;
3857}
3858
Guido van Rossumdc91b992001-08-08 22:26:22 +00003859
3860#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003861static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003862FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003863{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003864 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00003865 int do_other = self->ob_type != other->ob_type && \
3866 other->ob_type->tp_as_number != NULL && \
3867 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003868 if (self->ob_type->tp_as_number != NULL && \
3869 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
3870 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00003871 if (do_other && \
Guido van Rossumcd118802003-01-06 22:57:47 +00003872 PyType_IsSubtype(other->ob_type, self->ob_type) && \
3873 method_is_overloaded(self, other, ROPSTR)) { \
Guido van Rossum55f20992001-10-01 17:18:22 +00003874 r = call_maybe( \
3875 other, ROPSTR, &rcache_str, "(O)", self); \
3876 if (r != Py_NotImplemented) \
3877 return r; \
3878 Py_DECREF(r); \
3879 do_other = 0; \
3880 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00003881 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00003882 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003883 if (r != Py_NotImplemented || \
3884 other->ob_type == self->ob_type) \
3885 return r; \
3886 Py_DECREF(r); \
3887 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00003888 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00003889 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00003890 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003891 } \
3892 Py_INCREF(Py_NotImplemented); \
3893 return Py_NotImplemented; \
3894}
3895
3896#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
3897 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
3898
3899#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
3900static PyObject * \
3901FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
3902{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003903 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003904 return call_method(self, OPSTR, &cache_str, \
3905 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003906}
3907
3908static int
3909slot_sq_length(PyObject *self)
3910{
Guido van Rossum2730b132001-08-28 18:22:14 +00003911 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00003912 PyObject *res = call_method(self, "__len__", &len_str, "()");
Guido van Rossum26111622001-10-01 16:42:49 +00003913 int len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003914
3915 if (res == NULL)
3916 return -1;
Guido van Rossum26111622001-10-01 16:42:49 +00003917 len = (int)PyInt_AsLong(res);
3918 Py_DECREF(res);
Jeremy Hylton73a088e2002-07-25 16:43:29 +00003919 if (len == -1 && PyErr_Occurred())
3920 return -1;
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00003921 if (len < 0) {
Guido van Rossum22b13872002-08-06 21:41:44 +00003922 PyErr_SetString(PyExc_ValueError,
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00003923 "__len__() should return >= 0");
3924 return -1;
3925 }
Guido van Rossum26111622001-10-01 16:42:49 +00003926 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003927}
3928
Guido van Rossumdc91b992001-08-08 22:26:22 +00003929SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
3930SLOT1(slot_sq_repeat, "__mul__", int, "i")
Guido van Rossumf4593e02001-10-03 12:09:30 +00003931
3932/* Super-optimized version of slot_sq_item.
3933 Other slots could do the same... */
3934static PyObject *
3935slot_sq_item(PyObject *self, int i)
3936{
3937 static PyObject *getitem_str;
3938 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
3939 descrgetfunc f;
3940
3941 if (getitem_str == NULL) {
3942 getitem_str = PyString_InternFromString("__getitem__");
3943 if (getitem_str == NULL)
3944 return NULL;
3945 }
3946 func = _PyType_Lookup(self->ob_type, getitem_str);
3947 if (func != NULL) {
Guido van Rossumf4593e02001-10-03 12:09:30 +00003948 if ((f = func->ob_type->tp_descr_get) == NULL)
3949 Py_INCREF(func);
Neal Norwitz673cd822002-10-18 16:33:13 +00003950 else {
Guido van Rossumf4593e02001-10-03 12:09:30 +00003951 func = f(func, self, (PyObject *)(self->ob_type));
Neal Norwitz673cd822002-10-18 16:33:13 +00003952 if (func == NULL) {
3953 return NULL;
3954 }
3955 }
Guido van Rossumf4593e02001-10-03 12:09:30 +00003956 ival = PyInt_FromLong(i);
3957 if (ival != NULL) {
3958 args = PyTuple_New(1);
3959 if (args != NULL) {
3960 PyTuple_SET_ITEM(args, 0, ival);
3961 retval = PyObject_Call(func, args, NULL);
3962 Py_XDECREF(args);
3963 Py_XDECREF(func);
3964 return retval;
3965 }
3966 }
3967 }
3968 else {
3969 PyErr_SetObject(PyExc_AttributeError, getitem_str);
3970 }
3971 Py_XDECREF(args);
3972 Py_XDECREF(ival);
3973 Py_XDECREF(func);
3974 return NULL;
3975}
3976
Guido van Rossumdc91b992001-08-08 22:26:22 +00003977SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003978
3979static int
3980slot_sq_ass_item(PyObject *self, int index, PyObject *value)
3981{
3982 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003983 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003984
3985 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003986 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003987 "(i)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003988 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003989 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003990 "(iO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003991 if (res == NULL)
3992 return -1;
3993 Py_DECREF(res);
3994 return 0;
3995}
3996
3997static int
3998slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
3999{
4000 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004001 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004002
4003 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004004 res = call_method(self, "__delslice__", &delslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004005 "(ii)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004006 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004007 res = call_method(self, "__setslice__", &setslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004008 "(iiO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004009 if (res == NULL)
4010 return -1;
4011 Py_DECREF(res);
4012 return 0;
4013}
4014
4015static int
4016slot_sq_contains(PyObject *self, PyObject *value)
4017{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004018 PyObject *func, *res, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00004019 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004020
Guido van Rossum55f20992001-10-01 17:18:22 +00004021 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004022
4023 if (func != NULL) {
4024 args = Py_BuildValue("(O)", value);
4025 if (args == NULL)
4026 res = NULL;
4027 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004028 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004029 Py_DECREF(args);
4030 }
4031 Py_DECREF(func);
4032 if (res == NULL)
4033 return -1;
4034 return PyObject_IsTrue(res);
4035 }
Guido van Rossum55f20992001-10-01 17:18:22 +00004036 else if (PyErr_Occurred())
4037 return -1;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004038 else {
Tim Peters16a77ad2001-09-08 04:00:12 +00004039 return _PySequence_IterSearch(self, value,
4040 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004041 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004042}
4043
Guido van Rossumdc91b992001-08-08 22:26:22 +00004044SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
4045SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004046
4047#define slot_mp_length slot_sq_length
4048
Guido van Rossumdc91b992001-08-08 22:26:22 +00004049SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004050
4051static int
4052slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
4053{
4054 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004055 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004056
4057 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004058 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004059 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004060 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004061 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004062 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004063 if (res == NULL)
4064 return -1;
4065 Py_DECREF(res);
4066 return 0;
4067}
4068
Guido van Rossumdc91b992001-08-08 22:26:22 +00004069SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
4070SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
4071SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
4072SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
4073SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
4074SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
4075
Jeremy Hylton938ace62002-07-17 16:30:39 +00004076static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00004077
4078SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
4079 nb_power, "__pow__", "__rpow__")
4080
4081static PyObject *
4082slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
4083{
Guido van Rossum2730b132001-08-28 18:22:14 +00004084 static PyObject *pow_str;
4085
Guido van Rossumdc91b992001-08-08 22:26:22 +00004086 if (modulus == Py_None)
4087 return slot_nb_power_binary(self, other);
Guido van Rossum23094982002-06-10 14:30:43 +00004088 /* Three-arg power doesn't use __rpow__. But ternary_op
4089 can call this when the second argument's type uses
4090 slot_nb_power, so check before calling self.__pow__. */
4091 if (self->ob_type->tp_as_number != NULL &&
4092 self->ob_type->tp_as_number->nb_power == slot_nb_power) {
4093 return call_method(self, "__pow__", &pow_str,
4094 "(OO)", other, modulus);
4095 }
4096 Py_INCREF(Py_NotImplemented);
4097 return Py_NotImplemented;
Guido van Rossumdc91b992001-08-08 22:26:22 +00004098}
4099
4100SLOT0(slot_nb_negative, "__neg__")
4101SLOT0(slot_nb_positive, "__pos__")
4102SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004103
4104static int
4105slot_nb_nonzero(PyObject *self)
4106{
Tim Petersea7f75d2002-12-07 21:39:16 +00004107 PyObject *func, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00004108 static PyObject *nonzero_str, *len_str;
Tim Petersea7f75d2002-12-07 21:39:16 +00004109 int result = -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004110
Guido van Rossum55f20992001-10-01 17:18:22 +00004111 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004112 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00004113 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00004114 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00004115 func = lookup_maybe(self, "__len__", &len_str);
Tim Petersea7f75d2002-12-07 21:39:16 +00004116 if (func == NULL)
4117 return PyErr_Occurred() ? -1 : 1;
4118 }
4119 args = PyTuple_New(0);
4120 if (args != NULL) {
4121 PyObject *temp = PyObject_Call(func, args, NULL);
4122 Py_DECREF(args);
4123 if (temp != NULL) {
4124 result = PyObject_IsTrue(temp);
4125 Py_DECREF(temp);
Guido van Rossum55f20992001-10-01 17:18:22 +00004126 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004127 }
Guido van Rossum55f20992001-10-01 17:18:22 +00004128 Py_DECREF(func);
Tim Petersea7f75d2002-12-07 21:39:16 +00004129 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004130}
4131
Guido van Rossumdc91b992001-08-08 22:26:22 +00004132SLOT0(slot_nb_invert, "__invert__")
4133SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
4134SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
4135SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
4136SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
4137SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004138
4139static int
4140slot_nb_coerce(PyObject **a, PyObject **b)
4141{
4142 static PyObject *coerce_str;
4143 PyObject *self = *a, *other = *b;
4144
4145 if (self->ob_type->tp_as_number != NULL &&
4146 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
4147 PyObject *r;
4148 r = call_maybe(
4149 self, "__coerce__", &coerce_str, "(O)", other);
4150 if (r == NULL)
4151 return -1;
4152 if (r == Py_NotImplemented) {
4153 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004154 }
Guido van Rossum55f20992001-10-01 17:18:22 +00004155 else {
4156 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
4157 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004158 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00004159 Py_DECREF(r);
4160 return -1;
4161 }
4162 *a = PyTuple_GET_ITEM(r, 0);
4163 Py_INCREF(*a);
4164 *b = PyTuple_GET_ITEM(r, 1);
4165 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004166 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00004167 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004168 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004169 }
4170 if (other->ob_type->tp_as_number != NULL &&
4171 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
4172 PyObject *r;
4173 r = call_maybe(
4174 other, "__coerce__", &coerce_str, "(O)", self);
4175 if (r == NULL)
4176 return -1;
4177 if (r == Py_NotImplemented) {
4178 Py_DECREF(r);
4179 return 1;
4180 }
4181 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
4182 PyErr_SetString(PyExc_TypeError,
4183 "__coerce__ didn't return a 2-tuple");
4184 Py_DECREF(r);
4185 return -1;
4186 }
4187 *a = PyTuple_GET_ITEM(r, 1);
4188 Py_INCREF(*a);
4189 *b = PyTuple_GET_ITEM(r, 0);
4190 Py_INCREF(*b);
4191 Py_DECREF(r);
4192 return 0;
4193 }
4194 return 1;
4195}
4196
Guido van Rossumdc91b992001-08-08 22:26:22 +00004197SLOT0(slot_nb_int, "__int__")
4198SLOT0(slot_nb_long, "__long__")
4199SLOT0(slot_nb_float, "__float__")
4200SLOT0(slot_nb_oct, "__oct__")
4201SLOT0(slot_nb_hex, "__hex__")
4202SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
4203SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
4204SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
4205SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
4206SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Guido van Rossum6e5680f2002-10-15 01:01:53 +00004207SLOT1(slot_nb_inplace_power, "__ipow__", PyObject *, "O")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004208SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
4209SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
4210SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
4211SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
4212SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
4213SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
4214 "__floordiv__", "__rfloordiv__")
4215SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
4216SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
4217SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004218
4219static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00004220half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004221{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004222 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004223 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004224 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004225
Guido van Rossum60718732001-08-28 17:47:51 +00004226 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004227 if (func == NULL) {
4228 PyErr_Clear();
4229 }
4230 else {
4231 args = Py_BuildValue("(O)", other);
4232 if (args == NULL)
4233 res = NULL;
4234 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004235 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004236 Py_DECREF(args);
4237 }
Raymond Hettingerab5dae32002-06-24 13:08:16 +00004238 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004239 if (res != Py_NotImplemented) {
4240 if (res == NULL)
4241 return -2;
4242 c = PyInt_AsLong(res);
4243 Py_DECREF(res);
4244 if (c == -1 && PyErr_Occurred())
4245 return -2;
4246 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
4247 }
4248 Py_DECREF(res);
4249 }
4250 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004251}
4252
Guido van Rossumab3b0342001-09-18 20:38:53 +00004253/* This slot is published for the benefit of try_3way_compare in object.c */
4254int
4255_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00004256{
4257 int c;
4258
Guido van Rossumab3b0342001-09-18 20:38:53 +00004259 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004260 c = half_compare(self, other);
4261 if (c <= 1)
4262 return c;
4263 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00004264 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004265 c = half_compare(other, self);
4266 if (c < -1)
4267 return -2;
4268 if (c <= 1)
4269 return -c;
4270 }
4271 return (void *)self < (void *)other ? -1 :
4272 (void *)self > (void *)other ? 1 : 0;
4273}
4274
4275static PyObject *
4276slot_tp_repr(PyObject *self)
4277{
4278 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004279 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004280
Guido van Rossum60718732001-08-28 17:47:51 +00004281 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004282 if (func != NULL) {
4283 res = PyEval_CallObject(func, NULL);
4284 Py_DECREF(func);
4285 return res;
4286 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00004287 PyErr_Clear();
4288 return PyString_FromFormat("<%s object at %p>",
4289 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004290}
4291
4292static PyObject *
4293slot_tp_str(PyObject *self)
4294{
4295 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004296 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004297
Guido van Rossum60718732001-08-28 17:47:51 +00004298 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004299 if (func != NULL) {
4300 res = PyEval_CallObject(func, NULL);
4301 Py_DECREF(func);
4302 return res;
4303 }
4304 else {
4305 PyErr_Clear();
4306 return slot_tp_repr(self);
4307 }
4308}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004309
4310static long
4311slot_tp_hash(PyObject *self)
4312{
Tim Peters61ce0a92002-12-06 23:38:02 +00004313 PyObject *func;
Guido van Rossum60718732001-08-28 17:47:51 +00004314 static PyObject *hash_str, *eq_str, *cmp_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004315 long h;
4316
Guido van Rossum60718732001-08-28 17:47:51 +00004317 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004318
4319 if (func != NULL) {
Tim Peters61ce0a92002-12-06 23:38:02 +00004320 PyObject *res = PyEval_CallObject(func, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004321 Py_DECREF(func);
4322 if (res == NULL)
4323 return -1;
4324 h = PyInt_AsLong(res);
Tim Peters61ce0a92002-12-06 23:38:02 +00004325 Py_DECREF(res);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004326 }
4327 else {
4328 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004329 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004330 if (func == NULL) {
4331 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004332 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004333 }
4334 if (func != NULL) {
4335 Py_DECREF(func);
4336 PyErr_SetString(PyExc_TypeError, "unhashable type");
4337 return -1;
4338 }
4339 PyErr_Clear();
4340 h = _Py_HashPointer((void *)self);
4341 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004342 if (h == -1 && !PyErr_Occurred())
4343 h = -2;
4344 return h;
4345}
4346
4347static PyObject *
4348slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
4349{
Guido van Rossum60718732001-08-28 17:47:51 +00004350 static PyObject *call_str;
4351 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004352 PyObject *res;
4353
4354 if (meth == NULL)
4355 return NULL;
4356 res = PyObject_Call(meth, args, kwds);
4357 Py_DECREF(meth);
4358 return res;
4359}
4360
Guido van Rossum14a6f832001-10-17 13:59:09 +00004361/* There are two slot dispatch functions for tp_getattro.
4362
4363 - slot_tp_getattro() is used when __getattribute__ is overridden
4364 but no __getattr__ hook is present;
4365
4366 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
4367
Guido van Rossumc334df52002-04-04 23:44:47 +00004368 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
4369 detects the absence of __getattr__ and then installs the simpler slot if
4370 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00004371
Tim Peters6d6c1a32001-08-02 04:15:00 +00004372static PyObject *
4373slot_tp_getattro(PyObject *self, PyObject *name)
4374{
Guido van Rossum14a6f832001-10-17 13:59:09 +00004375 static PyObject *getattribute_str = NULL;
4376 return call_method(self, "__getattribute__", &getattribute_str,
4377 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004378}
4379
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004380static PyObject *
4381slot_tp_getattr_hook(PyObject *self, PyObject *name)
4382{
4383 PyTypeObject *tp = self->ob_type;
4384 PyObject *getattr, *getattribute, *res;
4385 static PyObject *getattribute_str = NULL;
4386 static PyObject *getattr_str = NULL;
4387
4388 if (getattr_str == NULL) {
4389 getattr_str = PyString_InternFromString("__getattr__");
4390 if (getattr_str == NULL)
4391 return NULL;
4392 }
4393 if (getattribute_str == NULL) {
4394 getattribute_str =
4395 PyString_InternFromString("__getattribute__");
4396 if (getattribute_str == NULL)
4397 return NULL;
4398 }
4399 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004400 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004401 /* No __getattr__ hook: use a simpler dispatcher */
4402 tp->tp_getattro = slot_tp_getattro;
4403 return slot_tp_getattro(self, name);
4404 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004405 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004406 if (getattribute == NULL ||
4407 (getattribute->ob_type == &PyWrapperDescr_Type &&
4408 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
4409 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004410 res = PyObject_GenericGetAttr(self, name);
4411 else
4412 res = PyObject_CallFunction(getattribute, "OO", self, name);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004413 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004414 PyErr_Clear();
4415 res = PyObject_CallFunction(getattr, "OO", self, name);
4416 }
4417 return res;
4418}
4419
Tim Peters6d6c1a32001-08-02 04:15:00 +00004420static int
4421slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
4422{
4423 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004424 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004425
4426 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004427 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004428 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004429 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004430 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004431 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004432 if (res == NULL)
4433 return -1;
4434 Py_DECREF(res);
4435 return 0;
4436}
4437
4438/* Map rich comparison operators to their __xx__ namesakes */
4439static char *name_op[] = {
4440 "__lt__",
4441 "__le__",
4442 "__eq__",
4443 "__ne__",
4444 "__gt__",
4445 "__ge__",
4446};
4447
4448static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00004449half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004450{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004451 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004452 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00004453
Guido van Rossum60718732001-08-28 17:47:51 +00004454 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004455 if (func == NULL) {
4456 PyErr_Clear();
4457 Py_INCREF(Py_NotImplemented);
4458 return Py_NotImplemented;
4459 }
4460 args = Py_BuildValue("(O)", other);
4461 if (args == NULL)
4462 res = NULL;
4463 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004464 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004465 Py_DECREF(args);
4466 }
4467 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004468 return res;
4469}
4470
Guido van Rossumb8f63662001-08-15 23:57:02 +00004471/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
4472static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
4473
4474static PyObject *
4475slot_tp_richcompare(PyObject *self, PyObject *other, int op)
4476{
4477 PyObject *res;
4478
4479 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
4480 res = half_richcompare(self, other, op);
4481 if (res != Py_NotImplemented)
4482 return res;
4483 Py_DECREF(res);
4484 }
4485 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
4486 res = half_richcompare(other, self, swapped_op[op]);
4487 if (res != Py_NotImplemented) {
4488 return res;
4489 }
4490 Py_DECREF(res);
4491 }
4492 Py_INCREF(Py_NotImplemented);
4493 return Py_NotImplemented;
4494}
4495
4496static PyObject *
4497slot_tp_iter(PyObject *self)
4498{
4499 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004500 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004501
Guido van Rossum60718732001-08-28 17:47:51 +00004502 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004503 if (func != NULL) {
Guido van Rossum84b2bed2002-08-16 17:01:09 +00004504 PyObject *args;
4505 args = res = PyTuple_New(0);
4506 if (args != NULL) {
4507 res = PyObject_Call(func, args, NULL);
4508 Py_DECREF(args);
4509 }
4510 Py_DECREF(func);
4511 return res;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004512 }
4513 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004514 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004515 if (func == NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00004516 PyErr_SetString(PyExc_TypeError,
4517 "iteration over non-sequence");
Guido van Rossumb8f63662001-08-15 23:57:02 +00004518 return NULL;
4519 }
4520 Py_DECREF(func);
4521 return PySeqIter_New(self);
4522}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004523
4524static PyObject *
4525slot_tp_iternext(PyObject *self)
4526{
Guido van Rossum2730b132001-08-28 18:22:14 +00004527 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00004528 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004529}
4530
Guido van Rossum1a493502001-08-17 16:47:50 +00004531static PyObject *
4532slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4533{
4534 PyTypeObject *tp = self->ob_type;
4535 PyObject *get;
4536 static PyObject *get_str = NULL;
4537
4538 if (get_str == NULL) {
4539 get_str = PyString_InternFromString("__get__");
4540 if (get_str == NULL)
4541 return NULL;
4542 }
4543 get = _PyType_Lookup(tp, get_str);
4544 if (get == NULL) {
4545 /* Avoid further slowdowns */
4546 if (tp->tp_descr_get == slot_tp_descr_get)
4547 tp->tp_descr_get = NULL;
4548 Py_INCREF(self);
4549 return self;
4550 }
Guido van Rossum2c252392001-08-24 10:13:31 +00004551 if (obj == NULL)
4552 obj = Py_None;
4553 if (type == NULL)
4554 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00004555 return PyObject_CallFunction(get, "OOO", self, obj, type);
4556}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004557
4558static int
4559slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
4560{
Guido van Rossum2c252392001-08-24 10:13:31 +00004561 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004562 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00004563
4564 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00004565 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004566 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00004567 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004568 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004569 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004570 if (res == NULL)
4571 return -1;
4572 Py_DECREF(res);
4573 return 0;
4574}
4575
4576static int
4577slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
4578{
Guido van Rossum60718732001-08-28 17:47:51 +00004579 static PyObject *init_str;
4580 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004581 PyObject *res;
4582
4583 if (meth == NULL)
4584 return -1;
4585 res = PyObject_Call(meth, args, kwds);
4586 Py_DECREF(meth);
4587 if (res == NULL)
4588 return -1;
4589 Py_DECREF(res);
4590 return 0;
4591}
4592
4593static PyObject *
4594slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4595{
Guido van Rossum7bed2132002-08-08 21:57:53 +00004596 static PyObject *new_str;
4597 PyObject *func;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004598 PyObject *newargs, *x;
4599 int i, n;
4600
Guido van Rossum7bed2132002-08-08 21:57:53 +00004601 if (new_str == NULL) {
4602 new_str = PyString_InternFromString("__new__");
4603 if (new_str == NULL)
4604 return NULL;
4605 }
4606 func = PyObject_GetAttr((PyObject *)type, new_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004607 if (func == NULL)
4608 return NULL;
4609 assert(PyTuple_Check(args));
4610 n = PyTuple_GET_SIZE(args);
4611 newargs = PyTuple_New(n+1);
4612 if (newargs == NULL)
4613 return NULL;
4614 Py_INCREF(type);
4615 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
4616 for (i = 0; i < n; i++) {
4617 x = PyTuple_GET_ITEM(args, i);
4618 Py_INCREF(x);
4619 PyTuple_SET_ITEM(newargs, i+1, x);
4620 }
4621 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00004622 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004623 Py_DECREF(func);
4624 return x;
4625}
4626
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004627static void
4628slot_tp_del(PyObject *self)
4629{
4630 static PyObject *del_str = NULL;
4631 PyObject *del, *res;
4632 PyObject *error_type, *error_value, *error_traceback;
4633
4634 /* Temporarily resurrect the object. */
4635 assert(self->ob_refcnt == 0);
4636 self->ob_refcnt = 1;
4637
4638 /* Save the current exception, if any. */
4639 PyErr_Fetch(&error_type, &error_value, &error_traceback);
4640
4641 /* Execute __del__ method, if any. */
4642 del = lookup_maybe(self, "__del__", &del_str);
4643 if (del != NULL) {
4644 res = PyEval_CallObject(del, NULL);
4645 if (res == NULL)
4646 PyErr_WriteUnraisable(del);
4647 else
4648 Py_DECREF(res);
4649 Py_DECREF(del);
4650 }
4651
4652 /* Restore the saved exception. */
4653 PyErr_Restore(error_type, error_value, error_traceback);
4654
4655 /* Undo the temporary resurrection; can't use DECREF here, it would
4656 * cause a recursive call.
4657 */
4658 assert(self->ob_refcnt > 0);
4659 if (--self->ob_refcnt == 0)
4660 return; /* this is the normal path out */
4661
4662 /* __del__ resurrected it! Make it look like the original Py_DECREF
4663 * never happened.
4664 */
4665 {
4666 int refcnt = self->ob_refcnt;
4667 _Py_NewReference(self);
4668 self->ob_refcnt = refcnt;
4669 }
4670 assert(!PyType_IS_GC(self->ob_type) ||
4671 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
4672 /* If Py_REF_DEBUG, the original decref dropped _Py_RefTotal, but
4673 * _Py_NewReference bumped it again, so that's a wash.
4674 * If Py_TRACE_REFS, _Py_NewReference re-added self to the object
4675 * chain, so no more to do there either.
4676 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
4677 * _Py_NewReference bumped tp_allocs: both of those need to be
4678 * undone.
4679 */
4680#ifdef COUNT_ALLOCS
4681 --self->ob_type->tp_frees;
4682 --self->ob_type->tp_allocs;
4683#endif
4684}
4685
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004686
4687/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
Guido van Rossume5c691a2003-03-07 15:13:17 +00004688 functions. The offsets here are relative to the 'PyHeapTypeObject'
4689 structure, which incorporates the additional structures used for numbers,
4690 sequences and mappings.
4691 Note that multiple names may map to the same slot (e.g. __eq__,
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004692 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00004693 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
4694 terminated with an all-zero entry. (This table is further initialized and
4695 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004696
Guido van Rossum6d204072001-10-21 00:44:31 +00004697typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004698
4699#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00004700#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004701#undef ETSLOT
4702#undef SQSLOT
4703#undef MPSLOT
4704#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00004705#undef UNSLOT
4706#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004707#undef BINSLOT
4708#undef RBINSLOT
4709
Guido van Rossum6d204072001-10-21 00:44:31 +00004710#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004711 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
4712 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00004713#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
4714 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004715 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00004716#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Guido van Rossume5c691a2003-03-07 15:13:17 +00004717 {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004718 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00004719#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4720 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
4721#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4722 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
4723#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4724 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
4725#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4726 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
4727 "x." NAME "() <==> " DOC)
4728#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4729 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
4730 "x." NAME "(y) <==> x" DOC "y")
4731#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
4732 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
4733 "x." NAME "(y) <==> x" DOC "y")
4734#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
4735 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
4736 "x." NAME "(y) <==> y" DOC "x")
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004737
4738static slotdef slotdefs[] = {
Guido van Rossum6d204072001-10-21 00:44:31 +00004739 SQSLOT("__len__", sq_length, slot_sq_length, wrap_inquiry,
4740 "x.__len__() <==> len(x)"),
4741 SQSLOT("__add__", sq_concat, slot_sq_concat, wrap_binaryfunc,
4742 "x.__add__(y) <==> x+y"),
4743 SQSLOT("__mul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
4744 "x.__mul__(n) <==> x*n"),
4745 SQSLOT("__rmul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
4746 "x.__rmul__(n) <==> n*x"),
4747 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
4748 "x.__getitem__(y) <==> x[y]"),
4749 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_intintargfunc,
4750 "x.__getslice__(i, j) <==> x[i:j]"),
4751 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
4752 "x.__setitem__(i, y) <==> x[i]=y"),
4753 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
4754 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004755 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Guido van Rossum6d204072001-10-21 00:44:31 +00004756 wrap_intintobjargproc,
4757 "x.__setslice__(i, j, y) <==> x[i:j]=y"),
4758 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
4759 "x.__delslice__(i, j) <==> del x[i:j]"),
4760 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
4761 "x.__contains__(y) <==> y in x"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004762 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat,
Guido van Rossum6d204072001-10-21 00:44:31 +00004763 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004764 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat,
Guido van Rossum6d204072001-10-21 00:44:31 +00004765 wrap_intargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004766
Guido van Rossum6d204072001-10-21 00:44:31 +00004767 MPSLOT("__len__", mp_length, slot_mp_length, wrap_inquiry,
4768 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00004769 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004770 wrap_binaryfunc,
4771 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004772 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004773 wrap_objobjargproc,
4774 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004775 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004776 wrap_delitem,
4777 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004778
Guido van Rossum6d204072001-10-21 00:44:31 +00004779 BINSLOT("__add__", nb_add, slot_nb_add,
4780 "+"),
4781 RBINSLOT("__radd__", nb_add, slot_nb_add,
4782 "+"),
4783 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
4784 "-"),
4785 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
4786 "-"),
4787 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
4788 "*"),
4789 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
4790 "*"),
4791 BINSLOT("__div__", nb_divide, slot_nb_divide,
4792 "/"),
4793 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
4794 "/"),
4795 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
4796 "%"),
4797 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
4798 "%"),
4799 BINSLOT("__divmod__", nb_divmod, slot_nb_divmod,
4800 "divmod(x, y)"),
4801 RBINSLOT("__rdivmod__", nb_divmod, slot_nb_divmod,
4802 "divmod(y, x)"),
4803 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
4804 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
4805 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
4806 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
4807 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
4808 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
4809 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
4810 "abs(x)"),
Guido van Rossumdfce3bf2002-03-10 14:11:16 +00004811 UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquiry,
Guido van Rossum6d204072001-10-21 00:44:31 +00004812 "x != 0"),
4813 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
4814 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
4815 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
4816 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
4817 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
4818 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
4819 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
4820 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
4821 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
4822 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
4823 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
4824 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
4825 "x.__coerce__(y) <==> coerce(x, y)"),
4826 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
4827 "int(x)"),
4828 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
4829 "long(x)"),
4830 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
4831 "float(x)"),
4832 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
4833 "oct(x)"),
4834 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
4835 "hex(x)"),
4836 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
4837 wrap_binaryfunc, "+"),
4838 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
4839 wrap_binaryfunc, "-"),
4840 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
4841 wrap_binaryfunc, "*"),
4842 IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
4843 wrap_binaryfunc, "/"),
4844 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
4845 wrap_binaryfunc, "%"),
4846 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
Guido van Rossum6e5680f2002-10-15 01:01:53 +00004847 wrap_binaryfunc, "**"),
Guido van Rossum6d204072001-10-21 00:44:31 +00004848 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
4849 wrap_binaryfunc, "<<"),
4850 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
4851 wrap_binaryfunc, ">>"),
4852 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
4853 wrap_binaryfunc, "&"),
4854 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
4855 wrap_binaryfunc, "^"),
4856 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
4857 wrap_binaryfunc, "|"),
4858 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
4859 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
4860 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
4861 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
4862 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
4863 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
4864 IBSLOT("__itruediv__", nb_inplace_true_divide,
4865 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004866
Guido van Rossum6d204072001-10-21 00:44:31 +00004867 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
4868 "x.__str__() <==> str(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00004869 TPSLOT("__str__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00004870 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
4871 "x.__repr__() <==> repr(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00004872 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00004873 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
4874 "x.__cmp__(y) <==> cmp(x,y)"),
4875 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
4876 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00004877 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
4878 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004879 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00004880 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
4881 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
4882 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
4883 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
4884 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
4885 "x.__setattr__('name', value) <==> x.name = value"),
4886 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
4887 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
4888 "x.__delattr__('name') <==> del x.name"),
4889 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
4890 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
4891 "x.__lt__(y) <==> x<y"),
4892 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
4893 "x.__le__(y) <==> x<=y"),
4894 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
4895 "x.__eq__(y) <==> x==y"),
4896 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
4897 "x.__ne__(y) <==> x!=y"),
4898 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
4899 "x.__gt__(y) <==> x>y"),
4900 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
4901 "x.__ge__(y) <==> x>=y"),
4902 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
4903 "x.__iter__() <==> iter(x)"),
4904 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
4905 "x.next() -> the next value, or raise StopIteration"),
4906 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
4907 "descr.__get__(obj[, type]) -> value"),
4908 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
4909 "descr.__set__(obj, value)"),
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004910 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
4911 wrap_descr_delete, "descr.__delete__(obj)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00004912 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00004913 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00004914 "see x.__class__.__doc__ for signature",
4915 PyWrapperFlag_KEYWORDS),
4916 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004917 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004918 {NULL}
4919};
4920
Guido van Rossumc334df52002-04-04 23:44:47 +00004921/* Given a type pointer and an offset gotten from a slotdef entry, return a
4922 pointer to the actual slot. This is not quite the same as simply adding
4923 the offset to the type pointer, since it takes care to indirect through the
4924 proper indirection pointer (as_buffer, etc.); it returns NULL if the
4925 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004926static void **
4927slotptr(PyTypeObject *type, int offset)
4928{
4929 char *ptr;
4930
Guido van Rossume5c691a2003-03-07 15:13:17 +00004931 /* Note: this depends on the order of the members of PyHeapTypeObject! */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004932 assert(offset >= 0);
Guido van Rossume5c691a2003-03-07 15:13:17 +00004933 assert(offset < offsetof(PyHeapTypeObject, as_buffer));
4934 if (offset >= offsetof(PyHeapTypeObject, as_sequence)) {
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004935 ptr = (void *)type->tp_as_sequence;
Guido van Rossume5c691a2003-03-07 15:13:17 +00004936 offset -= offsetof(PyHeapTypeObject, as_sequence);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004937 }
Guido van Rossume5c691a2003-03-07 15:13:17 +00004938 else if (offset >= offsetof(PyHeapTypeObject, as_mapping)) {
Guido van Rossum09638c12002-06-13 19:17:46 +00004939 ptr = (void *)type->tp_as_mapping;
Guido van Rossume5c691a2003-03-07 15:13:17 +00004940 offset -= offsetof(PyHeapTypeObject, as_mapping);
Guido van Rossum09638c12002-06-13 19:17:46 +00004941 }
Guido van Rossume5c691a2003-03-07 15:13:17 +00004942 else if (offset >= offsetof(PyHeapTypeObject, as_number)) {
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004943 ptr = (void *)type->tp_as_number;
Guido van Rossume5c691a2003-03-07 15:13:17 +00004944 offset -= offsetof(PyHeapTypeObject, as_number);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004945 }
4946 else {
4947 ptr = (void *)type;
4948 }
4949 if (ptr != NULL)
4950 ptr += offset;
4951 return (void **)ptr;
4952}
Guido van Rossumf040ede2001-08-07 16:40:56 +00004953
Guido van Rossumc334df52002-04-04 23:44:47 +00004954/* Length of array of slotdef pointers used to store slots with the
4955 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
4956 the same __name__, for any __name__. Since that's a static property, it is
4957 appropriate to declare fixed-size arrays for this. */
4958#define MAX_EQUIV 10
4959
4960/* Return a slot pointer for a given name, but ONLY if the attribute has
4961 exactly one slot function. The name must be an interned string. */
4962static void **
4963resolve_slotdups(PyTypeObject *type, PyObject *name)
4964{
4965 /* XXX Maybe this could be optimized more -- but is it worth it? */
4966
4967 /* pname and ptrs act as a little cache */
4968 static PyObject *pname;
4969 static slotdef *ptrs[MAX_EQUIV];
4970 slotdef *p, **pp;
4971 void **res, **ptr;
4972
4973 if (pname != name) {
4974 /* Collect all slotdefs that match name into ptrs. */
4975 pname = name;
4976 pp = ptrs;
4977 for (p = slotdefs; p->name_strobj; p++) {
4978 if (p->name_strobj == name)
4979 *pp++ = p;
4980 }
4981 *pp = NULL;
4982 }
4983
4984 /* Look in all matching slots of the type; if exactly one of these has
4985 a filled-in slot, return its value. Otherwise return NULL. */
4986 res = NULL;
4987 for (pp = ptrs; *pp; pp++) {
4988 ptr = slotptr(type, (*pp)->offset);
4989 if (ptr == NULL || *ptr == NULL)
4990 continue;
4991 if (res != NULL)
4992 return NULL;
4993 res = ptr;
4994 }
4995 return res;
4996}
4997
4998/* Common code for update_these_slots() and fixup_slot_dispatchers(). This
4999 does some incredibly complex thinking and then sticks something into the
5000 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
5001 interests, and then stores a generic wrapper or a specific function into
5002 the slot.) Return a pointer to the next slotdef with a different offset,
5003 because that's convenient for fixup_slot_dispatchers(). */
5004static slotdef *
5005update_one_slot(PyTypeObject *type, slotdef *p)
5006{
5007 PyObject *descr;
5008 PyWrapperDescrObject *d;
5009 void *generic = NULL, *specific = NULL;
5010 int use_generic = 0;
5011 int offset = p->offset;
5012 void **ptr = slotptr(type, offset);
5013
5014 if (ptr == NULL) {
5015 do {
5016 ++p;
5017 } while (p->offset == offset);
5018 return p;
5019 }
5020 do {
5021 descr = _PyType_Lookup(type, p->name_strobj);
5022 if (descr == NULL)
5023 continue;
5024 if (descr->ob_type == &PyWrapperDescr_Type) {
5025 void **tptr = resolve_slotdups(type, p->name_strobj);
5026 if (tptr == NULL || tptr == ptr)
5027 generic = p->function;
5028 d = (PyWrapperDescrObject *)descr;
5029 if (d->d_base->wrapper == p->wrapper &&
5030 PyType_IsSubtype(type, d->d_type))
5031 {
5032 if (specific == NULL ||
5033 specific == d->d_wrapped)
5034 specific = d->d_wrapped;
5035 else
5036 use_generic = 1;
5037 }
5038 }
Guido van Rossum721f62e2002-08-09 02:14:34 +00005039 else if (descr->ob_type == &PyCFunction_Type &&
5040 PyCFunction_GET_FUNCTION(descr) ==
5041 (PyCFunction)tp_new_wrapper &&
5042 strcmp(p->name, "__new__") == 0)
5043 {
5044 /* The __new__ wrapper is not a wrapper descriptor,
5045 so must be special-cased differently.
5046 If we don't do this, creating an instance will
5047 always use slot_tp_new which will look up
5048 __new__ in the MRO which will call tp_new_wrapper
5049 which will look through the base classes looking
5050 for a static base and call its tp_new (usually
5051 PyType_GenericNew), after performing various
5052 sanity checks and constructing a new argument
5053 list. Cut all that nonsense short -- this speeds
5054 up instance creation tremendously. */
5055 specific = type->tp_new;
5056 /* XXX I'm not 100% sure that there isn't a hole
5057 in this reasoning that requires additional
5058 sanity checks. I'll buy the first person to
5059 point out a bug in this reasoning a beer. */
5060 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005061 else {
5062 use_generic = 1;
5063 generic = p->function;
5064 }
5065 } while ((++p)->offset == offset);
5066 if (specific && !use_generic)
5067 *ptr = specific;
5068 else
5069 *ptr = generic;
5070 return p;
5071}
5072
Guido van Rossum22b13872002-08-06 21:41:44 +00005073static int recurse_down_subclasses(PyTypeObject *type, slotdef **pp,
Jeremy Hylton938ace62002-07-17 16:30:39 +00005074 PyObject *name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005075
Guido van Rossumc334df52002-04-04 23:44:47 +00005076/* In the type, update the slots whose slotdefs are gathered in the pp0 array,
5077 and then do the same for all this type's subtypes. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005078static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005079update_these_slots(PyTypeObject *type, slotdef **pp0, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005080{
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005081 slotdef **pp;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005082
Guido van Rossumc334df52002-04-04 23:44:47 +00005083 for (pp = pp0; *pp; pp++)
5084 update_one_slot(type, *pp);
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005085 return recurse_down_subclasses(type, pp0, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005086}
5087
Guido van Rossumc334df52002-04-04 23:44:47 +00005088/* Update the slots whose slotdefs are gathered in the pp array in all (direct
5089 or indirect) subclasses of type. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005090static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005091recurse_down_subclasses(PyTypeObject *type, slotdef **pp, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005092{
5093 PyTypeObject *subclass;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005094 PyObject *ref, *subclasses, *dict;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005095 int i, n;
5096
5097 subclasses = type->tp_subclasses;
5098 if (subclasses == NULL)
5099 return 0;
5100 assert(PyList_Check(subclasses));
5101 n = PyList_GET_SIZE(subclasses);
5102 for (i = 0; i < n; i++) {
5103 ref = PyList_GET_ITEM(subclasses, i);
5104 assert(PyWeakref_CheckRef(ref));
5105 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
Guido van Rossum59e6c532002-06-14 02:27:07 +00005106 assert(subclass != NULL);
5107 if ((PyObject *)subclass == Py_None)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005108 continue;
5109 assert(PyType_Check(subclass));
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005110 /* Avoid recursing down into unaffected classes */
5111 dict = subclass->tp_dict;
5112 if (dict != NULL && PyDict_Check(dict) &&
5113 PyDict_GetItem(dict, name) != NULL)
5114 continue;
5115 if (update_these_slots(subclass, pp, name) < 0)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005116 return -1;
5117 }
5118 return 0;
5119}
5120
Guido van Rossumc334df52002-04-04 23:44:47 +00005121/* Comparison function for qsort() to compare slotdefs by their offset, and
5122 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005123static int
5124slotdef_cmp(const void *aa, const void *bb)
5125{
5126 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
5127 int c = a->offset - b->offset;
5128 if (c != 0)
5129 return c;
5130 else
5131 return a - b;
5132}
5133
Guido van Rossumc334df52002-04-04 23:44:47 +00005134/* Initialize the slotdefs table by adding interned string objects for the
5135 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005136static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005137init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005138{
5139 slotdef *p;
5140 static int initialized = 0;
5141
5142 if (initialized)
5143 return;
5144 for (p = slotdefs; p->name; p++) {
5145 p->name_strobj = PyString_InternFromString(p->name);
5146 if (!p->name_strobj)
Guido van Rossumc334df52002-04-04 23:44:47 +00005147 Py_FatalError("Out of memory interning slotdef names");
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005148 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005149 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
5150 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005151 initialized = 1;
5152}
5153
Guido van Rossumc334df52002-04-04 23:44:47 +00005154/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005155static int
5156update_slot(PyTypeObject *type, PyObject *name)
5157{
Guido van Rossumc334df52002-04-04 23:44:47 +00005158 slotdef *ptrs[MAX_EQUIV];
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005159 slotdef *p;
5160 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005161 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005162
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005163 init_slotdefs();
5164 pp = ptrs;
5165 for (p = slotdefs; p->name; p++) {
5166 /* XXX assume name is interned! */
5167 if (p->name_strobj == name)
5168 *pp++ = p;
5169 }
5170 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005171 for (pp = ptrs; *pp; pp++) {
5172 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005173 offset = p->offset;
5174 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005175 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005176 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005177 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005178 if (ptrs[0] == NULL)
5179 return 0; /* Not an attribute that affects any slots */
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005180 return update_these_slots(type, ptrs, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005181}
5182
Guido van Rossumc334df52002-04-04 23:44:47 +00005183/* Store the proper functions in the slot dispatches at class (type)
5184 definition time, based upon which operations the class overrides in its
5185 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00005186static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005187fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005188{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005189 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005190
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005191 init_slotdefs();
Guido van Rossumc334df52002-04-04 23:44:47 +00005192 for (p = slotdefs; p->name; )
5193 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005194}
Guido van Rossum705f0f52001-08-24 16:47:00 +00005195
Michael W. Hudson98bbc492002-11-26 14:47:27 +00005196static void
5197update_all_slots(PyTypeObject* type)
5198{
5199 slotdef *p;
5200
5201 init_slotdefs();
5202 for (p = slotdefs; p->name; p++) {
5203 /* update_slot returns int but can't actually fail */
5204 update_slot(type, p->name_strobj);
5205 }
5206}
5207
Guido van Rossum6d204072001-10-21 00:44:31 +00005208/* This function is called by PyType_Ready() to populate the type's
5209 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00005210 function slot (like tp_repr) that's defined in the type, one or more
5211 corresponding descriptors are added in the type's tp_dict dictionary
5212 under the appropriate name (like __repr__). Some function slots
5213 cause more than one descriptor to be added (for example, the nb_add
5214 slot adds both __add__ and __radd__ descriptors) and some function
5215 slots compete for the same descriptor (for example both sq_item and
5216 mp_subscript generate a __getitem__ descriptor).
5217
5218 In the latter case, the first slotdef entry encoutered wins. Since
Guido van Rossume5c691a2003-03-07 15:13:17 +00005219 slotdef entries are sorted by the offset of the slot in the
5220 PyHeapTypeObject, this gives us some control over disambiguating
5221 between competing slots: the members of PyHeapTypeObject are listed from most
Guido van Rossum09638c12002-06-13 19:17:46 +00005222 general to least general, so the most general slot is preferred. In
5223 particular, because as_mapping comes before as_sequence, for a type
5224 that defines both mp_subscript and sq_item, mp_subscript wins.
5225
5226 This only adds new descriptors and doesn't overwrite entries in
5227 tp_dict that were previously defined. The descriptors contain a
5228 reference to the C function they must call, so that it's safe if they
5229 are copied into a subtype's __dict__ and the subtype has a different
5230 C function in its slot -- calling the method defined by the
5231 descriptor will call the C function that was used to create it,
5232 rather than the C function present in the slot when it is called.
5233 (This is important because a subtype may have a C function in the
5234 slot that calls the method from the dictionary, and we want to avoid
5235 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00005236
5237static int
5238add_operators(PyTypeObject *type)
5239{
5240 PyObject *dict = type->tp_dict;
5241 slotdef *p;
5242 PyObject *descr;
5243 void **ptr;
5244
5245 init_slotdefs();
5246 for (p = slotdefs; p->name; p++) {
5247 if (p->wrapper == NULL)
5248 continue;
5249 ptr = slotptr(type, p->offset);
5250 if (!ptr || !*ptr)
5251 continue;
5252 if (PyDict_GetItem(dict, p->name_strobj))
5253 continue;
5254 descr = PyDescr_NewWrapper(type, p, *ptr);
5255 if (descr == NULL)
5256 return -1;
5257 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
5258 return -1;
5259 Py_DECREF(descr);
5260 }
5261 if (type->tp_new != NULL) {
5262 if (add_tp_new_wrapper(type) < 0)
5263 return -1;
5264 }
5265 return 0;
5266}
5267
Guido van Rossum705f0f52001-08-24 16:47:00 +00005268
5269/* Cooperative 'super' */
5270
5271typedef struct {
5272 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00005273 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005274 PyObject *obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005275 PyTypeObject *obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005276} superobject;
5277
Guido van Rossum6f799372001-09-20 20:46:19 +00005278static PyMemberDef super_members[] = {
5279 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
5280 "the class invoking super()"},
5281 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
5282 "the instance invoking super(); may be None"},
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005283 {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
5284 "the type of the the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005285 {0}
5286};
5287
Guido van Rossum705f0f52001-08-24 16:47:00 +00005288static void
5289super_dealloc(PyObject *self)
5290{
5291 superobject *su = (superobject *)self;
5292
Guido van Rossum048eb752001-10-02 21:24:57 +00005293 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005294 Py_XDECREF(su->obj);
5295 Py_XDECREF(su->type);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005296 Py_XDECREF(su->obj_type);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005297 self->ob_type->tp_free(self);
5298}
5299
5300static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005301super_repr(PyObject *self)
5302{
5303 superobject *su = (superobject *)self;
5304
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005305 if (su->obj_type)
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005306 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005307 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005308 su->type ? su->type->tp_name : "NULL",
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005309 su->obj_type->tp_name);
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005310 else
5311 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005312 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005313 su->type ? su->type->tp_name : "NULL");
5314}
5315
5316static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00005317super_getattro(PyObject *self, PyObject *name)
5318{
5319 superobject *su = (superobject *)self;
5320
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005321 if (su->obj_type != NULL) {
Tim Petersa91e9642001-11-14 23:32:33 +00005322 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005323 PyTypeObject *starttype;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005324 descrgetfunc f;
5325 int i, n;
5326
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005327 starttype = su->obj_type;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005328 mro = starttype->tp_mro;
5329
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005330 if (mro == NULL)
5331 n = 0;
5332 else {
5333 assert(PyTuple_Check(mro));
5334 n = PyTuple_GET_SIZE(mro);
5335 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005336 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00005337 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00005338 break;
5339 }
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005340#if 0
Guido van Rossume705ef12001-08-29 15:47:06 +00005341 if (i >= n && PyType_Check(su->obj)) {
Guido van Rossum155db9a2002-04-02 17:53:47 +00005342 starttype = (PyTypeObject *)(su->obj);
5343 mro = starttype->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005344 if (mro == NULL)
5345 n = 0;
5346 else {
5347 assert(PyTuple_Check(mro));
5348 n = PyTuple_GET_SIZE(mro);
5349 }
Guido van Rossume705ef12001-08-29 15:47:06 +00005350 for (i = 0; i < n; i++) {
5351 if ((PyObject *)(su->type) ==
5352 PyTuple_GET_ITEM(mro, i))
5353 break;
5354 }
Guido van Rossume705ef12001-08-29 15:47:06 +00005355 }
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005356#endif
Guido van Rossum705f0f52001-08-24 16:47:00 +00005357 i++;
5358 res = NULL;
5359 for (; i < n; i++) {
5360 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00005361 if (PyType_Check(tmp))
5362 dict = ((PyTypeObject *)tmp)->tp_dict;
5363 else if (PyClass_Check(tmp))
5364 dict = ((PyClassObject *)tmp)->cl_dict;
5365 else
5366 continue;
5367 res = PyDict_GetItem(dict, name);
Guido van Rossum5b443c62001-12-03 15:38:28 +00005368 if (res != NULL && !PyDescr_IsData(res)) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00005369 Py_INCREF(res);
5370 f = res->ob_type->tp_descr_get;
5371 if (f != NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00005372 tmp = f(res, su->obj,
5373 (PyObject *)starttype);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005374 Py_DECREF(res);
5375 res = tmp;
5376 }
5377 return res;
5378 }
5379 }
5380 }
5381 return PyObject_GenericGetAttr(self, name);
5382}
5383
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005384static PyTypeObject *
Guido van Rossum5b443c62001-12-03 15:38:28 +00005385supercheck(PyTypeObject *type, PyObject *obj)
5386{
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005387 /* Check that a super() call makes sense. Return a type object.
5388
5389 obj can be a new-style class, or an instance of one:
5390
5391 - If it is a class, it must be a subclass of 'type'. This case is
5392 used for class methods; the return value is obj.
5393
5394 - If it is an instance, it must be an instance of 'type'. This is
5395 the normal case; the return value is obj.__class__.
5396
5397 But... when obj is an instance, we want to allow for the case where
5398 obj->ob_type is not a subclass of type, but obj.__class__ is!
5399 This will allow using super() with a proxy for obj.
5400 */
5401
Guido van Rossum8e80a722003-02-18 19:22:22 +00005402 /* Check for first bullet above (special case) */
5403 if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
5404 Py_INCREF(obj);
5405 return (PyTypeObject *)obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005406 }
Guido van Rossum8e80a722003-02-18 19:22:22 +00005407
5408 /* Normal case */
5409 if (PyType_IsSubtype(obj->ob_type, type)) {
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005410 Py_INCREF(obj->ob_type);
5411 return obj->ob_type;
5412 }
5413 else {
5414 /* Try the slow way */
5415 static PyObject *class_str = NULL;
5416 PyObject *class_attr;
5417
5418 if (class_str == NULL) {
5419 class_str = PyString_FromString("__class__");
5420 if (class_str == NULL)
5421 return NULL;
5422 }
5423
5424 class_attr = PyObject_GetAttr(obj, class_str);
5425
5426 if (class_attr != NULL &&
5427 PyType_Check(class_attr) &&
5428 (PyTypeObject *)class_attr != obj->ob_type)
5429 {
5430 int ok = PyType_IsSubtype(
5431 (PyTypeObject *)class_attr, type);
5432 if (ok)
5433 return (PyTypeObject *)class_attr;
5434 }
5435
5436 if (class_attr == NULL)
5437 PyErr_Clear();
5438 else
5439 Py_DECREF(class_attr);
5440 }
5441
Tim Peters97e5ff52003-02-18 19:32:50 +00005442 PyErr_SetString(PyExc_TypeError,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005443 "super(type, obj): "
5444 "obj must be an instance or subtype of type");
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005445 return NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005446}
5447
Guido van Rossum705f0f52001-08-24 16:47:00 +00005448static PyObject *
5449super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5450{
5451 superobject *su = (superobject *)self;
5452 superobject *new;
5453
5454 if (obj == NULL || obj == Py_None || su->obj != NULL) {
5455 /* Not binding to an object, or already bound */
5456 Py_INCREF(self);
5457 return self;
5458 }
Guido van Rossum5b443c62001-12-03 15:38:28 +00005459 if (su->ob_type != &PySuper_Type)
5460 /* If su is an instance of a subclass of super,
5461 call its type */
5462 return PyObject_CallFunction((PyObject *)su->ob_type,
5463 "OO", su->type, obj);
5464 else {
5465 /* Inline the common case */
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005466 PyTypeObject *obj_type = supercheck(su->type, obj);
5467 if (obj_type == NULL)
Guido van Rossum5b443c62001-12-03 15:38:28 +00005468 return NULL;
5469 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
5470 NULL, NULL);
5471 if (new == NULL)
5472 return NULL;
5473 Py_INCREF(su->type);
5474 Py_INCREF(obj);
5475 new->type = su->type;
5476 new->obj = obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005477 new->obj_type = obj_type;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005478 return (PyObject *)new;
5479 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005480}
5481
5482static int
5483super_init(PyObject *self, PyObject *args, PyObject *kwds)
5484{
5485 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00005486 PyTypeObject *type;
5487 PyObject *obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005488 PyTypeObject *obj_type = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005489
5490 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
5491 return -1;
5492 if (obj == Py_None)
5493 obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005494 if (obj != NULL) {
5495 obj_type = supercheck(type, obj);
5496 if (obj_type == NULL)
5497 return -1;
5498 Py_INCREF(obj);
5499 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005500 Py_INCREF(type);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005501 su->type = type;
5502 su->obj = obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005503 su->obj_type = obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005504 return 0;
5505}
5506
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005507PyDoc_STRVAR(super_doc,
Guido van Rossum705f0f52001-08-24 16:47:00 +00005508"super(type) -> unbound super object\n"
5509"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00005510"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00005511"Typical use to call a cooperative superclass method:\n"
5512"class C(B):\n"
5513" def meth(self, arg):\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005514" super(C, self).meth(arg)");
Guido van Rossum705f0f52001-08-24 16:47:00 +00005515
Guido van Rossum048eb752001-10-02 21:24:57 +00005516static int
5517super_traverse(PyObject *self, visitproc visit, void *arg)
5518{
5519 superobject *su = (superobject *)self;
5520 int err;
5521
5522#define VISIT(SLOT) \
5523 if (SLOT) { \
5524 err = visit((PyObject *)(SLOT), arg); \
5525 if (err) \
5526 return err; \
5527 }
5528
5529 VISIT(su->obj);
5530 VISIT(su->type);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005531 VISIT(su->obj_type);
Guido van Rossum048eb752001-10-02 21:24:57 +00005532
5533#undef VISIT
5534
5535 return 0;
5536}
5537
Guido van Rossum705f0f52001-08-24 16:47:00 +00005538PyTypeObject PySuper_Type = {
5539 PyObject_HEAD_INIT(&PyType_Type)
5540 0, /* ob_size */
5541 "super", /* tp_name */
5542 sizeof(superobject), /* tp_basicsize */
5543 0, /* tp_itemsize */
5544 /* methods */
5545 super_dealloc, /* tp_dealloc */
5546 0, /* tp_print */
5547 0, /* tp_getattr */
5548 0, /* tp_setattr */
5549 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005550 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005551 0, /* tp_as_number */
5552 0, /* tp_as_sequence */
5553 0, /* tp_as_mapping */
5554 0, /* tp_hash */
5555 0, /* tp_call */
5556 0, /* tp_str */
5557 super_getattro, /* tp_getattro */
5558 0, /* tp_setattro */
5559 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00005560 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
5561 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005562 super_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00005563 super_traverse, /* tp_traverse */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005564 0, /* tp_clear */
5565 0, /* tp_richcompare */
5566 0, /* tp_weaklistoffset */
5567 0, /* tp_iter */
5568 0, /* tp_iternext */
5569 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005570 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005571 0, /* tp_getset */
5572 0, /* tp_base */
5573 0, /* tp_dict */
5574 super_descr_get, /* tp_descr_get */
5575 0, /* tp_descr_set */
5576 0, /* tp_dictoffset */
5577 super_init, /* tp_init */
5578 PyType_GenericAlloc, /* tp_alloc */
5579 PyType_GenericNew, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00005580 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005581};