blob: 2a7df8aa6326ad7e6462dbe0c1a9d60efcfffb99 [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* Type object implementation */
2
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003#include "Python.h"
Tim Peters6d6c1a32001-08-02 04:15:00 +00004#include "structmember.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00005
Guido van Rossum9923ffe2002-06-04 19:52:53 +00006#include <ctype.h>
7
Guido van Rossum6f799372001-09-20 20:46:19 +00008static PyMemberDef type_members[] = {
Tim Peters6d6c1a32001-08-02 04:15:00 +00009 {"__basicsize__", T_INT, offsetof(PyTypeObject,tp_basicsize),READONLY},
10 {"__itemsize__", T_INT, offsetof(PyTypeObject, tp_itemsize), READONLY},
11 {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY},
Guido van Rossum9676b222001-08-17 20:32:36 +000012 {"__weakrefoffset__", T_LONG,
Tim Peters6d6c1a32001-08-02 04:15:00 +000013 offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
14 {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY},
15 {"__dictoffset__", T_LONG,
16 offsetof(PyTypeObject, tp_dictoffset), READONLY},
Tim Peters6d6c1a32001-08-02 04:15:00 +000017 {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY},
18 {0}
19};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000020
Guido van Rossumc0b618a1997-05-02 03:12:38 +000021static PyObject *
Guido van Rossumc3542212001-08-16 09:18:56 +000022type_name(PyTypeObject *type, void *context)
23{
24 char *s;
25
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +000026 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
Guido van Rossume5c691a2003-03-07 15:13:17 +000027 PyHeapTypeObject* et = (PyHeapTypeObject*)type;
Tim Petersea7f75d2002-12-07 21:39:16 +000028
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +000029 Py_INCREF(et->name);
30 return et->name;
31 }
32 else {
33 s = strrchr(type->tp_name, '.');
34 if (s == NULL)
35 s = type->tp_name;
36 else
37 s++;
38 return PyString_FromString(s);
39 }
Guido van Rossumc3542212001-08-16 09:18:56 +000040}
41
Michael W. Hudson98bbc492002-11-26 14:47:27 +000042static int
43type_set_name(PyTypeObject *type, PyObject *value, void *context)
44{
Guido van Rossume5c691a2003-03-07 15:13:17 +000045 PyHeapTypeObject* et;
Michael W. Hudson98bbc492002-11-26 14:47:27 +000046
47 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
48 PyErr_Format(PyExc_TypeError,
49 "can't set %s.__name__", type->tp_name);
50 return -1;
51 }
52 if (!value) {
53 PyErr_Format(PyExc_TypeError,
54 "can't delete %s.__name__", type->tp_name);
55 return -1;
56 }
57 if (!PyString_Check(value)) {
58 PyErr_Format(PyExc_TypeError,
59 "can only assign string to %s.__name__, not '%s'",
60 type->tp_name, value->ob_type->tp_name);
61 return -1;
62 }
Tim Petersea7f75d2002-12-07 21:39:16 +000063 if (strlen(PyString_AS_STRING(value))
Michael W. Hudson98bbc492002-11-26 14:47:27 +000064 != (size_t)PyString_GET_SIZE(value)) {
65 PyErr_Format(PyExc_ValueError,
66 "__name__ must not contain null bytes");
67 return -1;
68 }
69
Guido van Rossume5c691a2003-03-07 15:13:17 +000070 et = (PyHeapTypeObject*)type;
Michael W. Hudson98bbc492002-11-26 14:47:27 +000071
72 Py_INCREF(value);
73
74 Py_DECREF(et->name);
75 et->name = value;
76
77 type->tp_name = PyString_AS_STRING(value);
78
79 return 0;
80}
81
Guido van Rossumc3542212001-08-16 09:18:56 +000082static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +000083type_module(PyTypeObject *type, void *context)
Guido van Rossum29ca26e1995-01-07 11:58:15 +000084{
Guido van Rossumc3542212001-08-16 09:18:56 +000085 PyObject *mod;
86 char *s;
87
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +000088 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
89 mod = PyDict_GetItemString(type->tp_dict, "__module__");
90 Py_XINCREF(mod);
Guido van Rossumc3542212001-08-16 09:18:56 +000091 return mod;
92 }
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +000093 else {
94 s = strrchr(type->tp_name, '.');
95 if (s != NULL)
96 return PyString_FromStringAndSize(
97 type->tp_name, (int)(s - type->tp_name));
98 return PyString_FromString("__builtin__");
99 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000100}
101
Guido van Rossum3926a632001-09-25 16:25:58 +0000102static int
103type_set_module(PyTypeObject *type, PyObject *value, void *context)
104{
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000105 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
Guido van Rossum3926a632001-09-25 16:25:58 +0000106 PyErr_Format(PyExc_TypeError,
107 "can't set %s.__module__", type->tp_name);
108 return -1;
109 }
110 if (!value) {
111 PyErr_Format(PyExc_TypeError,
112 "can't delete %s.__module__", type->tp_name);
113 return -1;
114 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000115
Guido van Rossum3926a632001-09-25 16:25:58 +0000116 return PyDict_SetItemString(type->tp_dict, "__module__", value);
117}
118
Tim Peters6d6c1a32001-08-02 04:15:00 +0000119static PyObject *
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000120type_get_bases(PyTypeObject *type, void *context)
121{
122 Py_INCREF(type->tp_bases);
123 return type->tp_bases;
124}
125
126static PyTypeObject *best_base(PyObject *);
127static int mro_internal(PyTypeObject *);
128static int compatible_for_assignment(PyTypeObject *, PyTypeObject *, char *);
129static int add_subclass(PyTypeObject*, PyTypeObject*);
130static void remove_subclass(PyTypeObject *, PyTypeObject *);
131static void update_all_slots(PyTypeObject *);
132
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000133typedef int (*update_callback)(PyTypeObject *, void *);
134static int update_subclasses(PyTypeObject *type, PyObject *name,
135 update_callback callback, void *data);
136static int recurse_down_subclasses(PyTypeObject *type, PyObject *name,
137 update_callback callback, void *data);
138
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000139static int
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000140mro_subclasses(PyTypeObject *type, PyObject* temp)
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000141{
142 PyTypeObject *subclass;
143 PyObject *ref, *subclasses, *old_mro;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000144 int i, n;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000145
146 subclasses = type->tp_subclasses;
147 if (subclasses == NULL)
148 return 0;
149 assert(PyList_Check(subclasses));
150 n = PyList_GET_SIZE(subclasses);
151 for (i = 0; i < n; i++) {
152 ref = PyList_GET_ITEM(subclasses, i);
153 assert(PyWeakref_CheckRef(ref));
154 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
155 assert(subclass != NULL);
156 if ((PyObject *)subclass == Py_None)
157 continue;
158 assert(PyType_Check(subclass));
159 old_mro = subclass->tp_mro;
160 if (mro_internal(subclass) < 0) {
161 subclass->tp_mro = old_mro;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000162 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000163 }
164 else {
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000165 PyObject* tuple;
166 tuple = Py_BuildValue("OO", subclass, old_mro);
Guido van Rossum19a02ba2003-04-15 22:09:45 +0000167 Py_DECREF(old_mro);
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000168 if (!tuple)
169 return -1;
170 if (PyList_Append(temp, tuple) < 0)
171 return -1;
Guido van Rossum19a02ba2003-04-15 22:09:45 +0000172 Py_DECREF(tuple);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000173 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000174 if (mro_subclasses(subclass, temp) < 0)
175 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000176 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000177 return 0;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000178}
179
180static int
181type_set_bases(PyTypeObject *type, PyObject *value, void *context)
182{
183 int i, r = 0;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000184 PyObject *ob, *temp;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000185 PyTypeObject *new_base, *old_base;
186 PyObject *old_bases, *old_mro;
187
188 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
189 PyErr_Format(PyExc_TypeError,
190 "can't set %s.__bases__", type->tp_name);
191 return -1;
192 }
193 if (!value) {
194 PyErr_Format(PyExc_TypeError,
195 "can't delete %s.__bases__", type->tp_name);
196 return -1;
197 }
198 if (!PyTuple_Check(value)) {
199 PyErr_Format(PyExc_TypeError,
200 "can only assign tuple to %s.__bases__, not %s",
201 type->tp_name, value->ob_type->tp_name);
202 return -1;
203 }
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +0000204 if (PyTuple_GET_SIZE(value) == 0) {
205 PyErr_Format(PyExc_TypeError,
206 "can only assign non-empty tuple to %s.__bases__, not ()",
207 type->tp_name);
208 return -1;
209 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000210 for (i = 0; i < PyTuple_GET_SIZE(value); i++) {
211 ob = PyTuple_GET_ITEM(value, i);
212 if (!PyClass_Check(ob) && !PyType_Check(ob)) {
213 PyErr_Format(
214 PyExc_TypeError,
215 "%s.__bases__ must be tuple of old- or new-style classes, not '%s'",
216 type->tp_name, ob->ob_type->tp_name);
217 return -1;
218 }
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +0000219 if (PyType_Check(ob)) {
220 if (PyType_IsSubtype((PyTypeObject*)ob, type)) {
221 PyErr_SetString(PyExc_TypeError,
222 "a __bases__ item causes an inheritance cycle");
223 return -1;
224 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000225 }
226 }
227
228 new_base = best_base(value);
229
230 if (!new_base) {
231 return -1;
232 }
233
234 if (!compatible_for_assignment(type->tp_base, new_base, "__bases__"))
235 return -1;
236
237 Py_INCREF(new_base);
238 Py_INCREF(value);
239
240 old_bases = type->tp_bases;
241 old_base = type->tp_base;
242 old_mro = type->tp_mro;
243
244 type->tp_bases = value;
245 type->tp_base = new_base;
246
247 if (mro_internal(type) < 0) {
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000248 goto bail;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000249 }
250
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000251 temp = PyList_New(0);
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000252 if (!temp)
253 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000254
255 r = mro_subclasses(type, temp);
256
257 if (r < 0) {
258 for (i = 0; i < PyList_Size(temp); i++) {
259 PyTypeObject* cls;
260 PyObject* mro;
Guido van Rossum19a02ba2003-04-15 22:09:45 +0000261 PyArg_ParseTuple(PyList_GET_ITEM(temp, i),
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000262 "OO", &cls, &mro);
263 Py_DECREF(cls->tp_mro);
264 cls->tp_mro = mro;
265 Py_INCREF(cls->tp_mro);
266 }
267 Py_DECREF(temp);
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000268 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000269 }
270
271 Py_DECREF(temp);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000272
273 /* any base that was in __bases__ but now isn't, we
Raymond Hettingera8285862002-12-14 17:17:56 +0000274 need to remove |type| from its tp_subclasses.
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000275 conversely, any class now in __bases__ that wasn't
Raymond Hettingera8285862002-12-14 17:17:56 +0000276 needs to have |type| added to its subclasses. */
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000277
278 /* for now, sod that: just remove from all old_bases,
279 add to all new_bases */
280
281 for (i = PyTuple_GET_SIZE(old_bases) - 1; i >= 0; i--) {
282 ob = PyTuple_GET_ITEM(old_bases, i);
283 if (PyType_Check(ob)) {
284 remove_subclass(
285 (PyTypeObject*)ob, type);
286 }
287 }
288
289 for (i = PyTuple_GET_SIZE(value) - 1; i >= 0; i--) {
290 ob = PyTuple_GET_ITEM(value, i);
291 if (PyType_Check(ob)) {
292 if (add_subclass((PyTypeObject*)ob, type) < 0)
293 r = -1;
294 }
295 }
296
297 update_all_slots(type);
298
299 Py_DECREF(old_bases);
300 Py_DECREF(old_base);
301 Py_DECREF(old_mro);
302
303 return r;
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000304
305 bail:
Michael W. Hudsone723e452003-08-07 14:58:10 +0000306 Py_DECREF(type->tp_bases);
307 Py_DECREF(type->tp_base);
308 if (type->tp_mro != old_mro) {
309 Py_DECREF(type->tp_mro);
310 }
311
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000312 type->tp_bases = old_bases;
313 type->tp_base = old_base;
314 type->tp_mro = old_mro;
Tim Petersea7f75d2002-12-07 21:39:16 +0000315
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000316 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000317}
318
319static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000320type_dict(PyTypeObject *type, void *context)
321{
322 if (type->tp_dict == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000323 Py_INCREF(Py_None);
324 return Py_None;
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000325 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000326 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000327}
328
Tim Peters24008312002-03-17 18:56:20 +0000329static PyObject *
330type_get_doc(PyTypeObject *type, void *context)
331{
332 PyObject *result;
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000333 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL)
Tim Peters24008312002-03-17 18:56:20 +0000334 return PyString_FromString(type->tp_doc);
Tim Peters24008312002-03-17 18:56:20 +0000335 result = PyDict_GetItemString(type->tp_dict, "__doc__");
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000336 if (result == NULL) {
337 result = Py_None;
338 Py_INCREF(result);
339 }
340 else if (result->ob_type->tp_descr_get) {
Tim Peters2b858972002-04-18 04:12:28 +0000341 result = result->ob_type->tp_descr_get(result, NULL,
342 (PyObject *)type);
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000343 }
344 else {
345 Py_INCREF(result);
346 }
Tim Peters24008312002-03-17 18:56:20 +0000347 return result;
348}
349
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000350static PyGetSetDef type_getsets[] = {
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000351 {"__name__", (getter)type_name, (setter)type_set_name, NULL},
352 {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL},
Guido van Rossum3926a632001-09-25 16:25:58 +0000353 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000354 {"__dict__", (getter)type_dict, NULL, NULL},
Tim Peters24008312002-03-17 18:56:20 +0000355 {"__doc__", (getter)type_get_doc, NULL, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000356 {0}
357};
358
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000359static int
360type_compare(PyObject *v, PyObject *w)
361{
362 /* This is called with type objects only. So we
363 can just compare the addresses. */
364 Py_uintptr_t vv = (Py_uintptr_t)v;
365 Py_uintptr_t ww = (Py_uintptr_t)w;
366 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
367}
368
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000369static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000370type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000371{
Barry Warsaw7ce36942001-08-24 18:34:26 +0000372 PyObject *mod, *name, *rtn;
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000373 char *kind;
Guido van Rossumc3542212001-08-16 09:18:56 +0000374
375 mod = type_module(type, NULL);
376 if (mod == NULL)
377 PyErr_Clear();
378 else if (!PyString_Check(mod)) {
379 Py_DECREF(mod);
380 mod = NULL;
381 }
382 name = type_name(type, NULL);
383 if (name == NULL)
384 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000385
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000386 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
387 kind = "class";
388 else
389 kind = "type";
390
Barry Warsaw7ce36942001-08-24 18:34:26 +0000391 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__")) {
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000392 rtn = PyString_FromFormat("<%s '%s.%s'>",
393 kind,
Barry Warsaw7ce36942001-08-24 18:34:26 +0000394 PyString_AS_STRING(mod),
395 PyString_AS_STRING(name));
396 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000397 else
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000398 rtn = PyString_FromFormat("<%s '%s'>", kind, type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000399
Guido van Rossumc3542212001-08-16 09:18:56 +0000400 Py_XDECREF(mod);
401 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000402 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000403}
404
Tim Peters6d6c1a32001-08-02 04:15:00 +0000405static PyObject *
406type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
407{
408 PyObject *obj;
409
410 if (type->tp_new == NULL) {
411 PyErr_Format(PyExc_TypeError,
412 "cannot create '%.100s' instances",
413 type->tp_name);
414 return NULL;
415 }
416
Tim Peters3f996e72001-09-13 19:18:27 +0000417 obj = type->tp_new(type, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000418 if (obj != NULL) {
Guido van Rossumf76de622001-10-18 15:49:21 +0000419 /* Ugly exception: when the call was type(something),
420 don't call tp_init on the result. */
421 if (type == &PyType_Type &&
422 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
423 (kwds == NULL ||
424 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
425 return obj;
Guido van Rossum8ace1ab2002-04-06 01:05:01 +0000426 /* If the returned object is not an instance of type,
427 it won't be initialized. */
428 if (!PyType_IsSubtype(obj->ob_type, type))
429 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000430 type = obj->ob_type;
Jeremy Hylton719841e2002-07-16 19:39:38 +0000431 if (PyType_HasFeature(type, Py_TPFLAGS_HAVE_CLASS) &&
432 type->tp_init != NULL &&
Tim Peters6d6c1a32001-08-02 04:15:00 +0000433 type->tp_init(obj, args, kwds) < 0) {
434 Py_DECREF(obj);
435 obj = NULL;
436 }
437 }
438 return obj;
439}
440
441PyObject *
442PyType_GenericAlloc(PyTypeObject *type, int nitems)
443{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000444 PyObject *obj;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000445 const size_t size = _PyObject_VAR_SIZE(type, nitems+1);
446 /* note that we need to add one, for the sentinel */
Tim Peters406fe3b2001-10-06 19:04:01 +0000447
448 if (PyType_IS_GC(type))
Neil Schemenauer09a2ae52002-04-12 03:06:53 +0000449 obj = _PyObject_GC_Malloc(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000450 else
Neil Schemenauerc806c882001-08-29 23:54:54 +0000451 obj = PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000452
Neil Schemenauerc806c882001-08-29 23:54:54 +0000453 if (obj == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000454 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000455
Neil Schemenauerc806c882001-08-29 23:54:54 +0000456 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000457
Tim Peters6d6c1a32001-08-02 04:15:00 +0000458 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
459 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000460
Tim Peters6d6c1a32001-08-02 04:15:00 +0000461 if (type->tp_itemsize == 0)
462 PyObject_INIT(obj, type);
463 else
464 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000465
Tim Peters6d6c1a32001-08-02 04:15:00 +0000466 if (PyType_IS_GC(type))
Neil Schemenauerc806c882001-08-29 23:54:54 +0000467 _PyObject_GC_TRACK(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000468 return obj;
469}
470
471PyObject *
472PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
473{
474 return type->tp_alloc(type, 0);
475}
476
Guido van Rossum9475a232001-10-05 20:51:39 +0000477/* Helpers for subtyping */
478
479static int
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000480traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
481{
482 int i, n;
483 PyMemberDef *mp;
484
485 n = type->ob_size;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000486 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000487 for (i = 0; i < n; i++, mp++) {
488 if (mp->type == T_OBJECT_EX) {
489 char *addr = (char *)self + mp->offset;
490 PyObject *obj = *(PyObject **)addr;
491 if (obj != NULL) {
492 int err = visit(obj, arg);
493 if (err)
494 return err;
495 }
496 }
497 }
498 return 0;
499}
500
501static int
Guido van Rossum9475a232001-10-05 20:51:39 +0000502subtype_traverse(PyObject *self, visitproc visit, void *arg)
503{
504 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000505 traverseproc basetraverse;
Guido van Rossum9475a232001-10-05 20:51:39 +0000506
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000507 /* Find the nearest base with a different tp_traverse,
508 and traverse slots while we're at it */
Guido van Rossum9475a232001-10-05 20:51:39 +0000509 type = self->ob_type;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000510 base = type;
511 while ((basetraverse = base->tp_traverse) == subtype_traverse) {
512 if (base->ob_size) {
513 int err = traverse_slots(base, self, visit, arg);
514 if (err)
515 return err;
516 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000517 base = base->tp_base;
518 assert(base);
519 }
520
521 if (type->tp_dictoffset != base->tp_dictoffset) {
522 PyObject **dictptr = _PyObject_GetDictPtr(self);
523 if (dictptr && *dictptr) {
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000524 int err = visit(*dictptr, arg);
Guido van Rossum9475a232001-10-05 20:51:39 +0000525 if (err)
526 return err;
527 }
528 }
529
Guido van Rossuma3862092002-06-10 15:24:42 +0000530 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
531 /* For a heaptype, the instances count as references
532 to the type. Traverse the type so the collector
533 can find cycles involving this link. */
534 int err = visit((PyObject *)type, arg);
535 if (err)
536 return err;
537 }
538
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000539 if (basetraverse)
540 return basetraverse(self, visit, arg);
541 return 0;
542}
543
544static void
545clear_slots(PyTypeObject *type, PyObject *self)
546{
547 int i, n;
548 PyMemberDef *mp;
549
550 n = type->ob_size;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000551 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000552 for (i = 0; i < n; i++, mp++) {
553 if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
554 char *addr = (char *)self + mp->offset;
555 PyObject *obj = *(PyObject **)addr;
556 if (obj != NULL) {
557 Py_DECREF(obj);
558 *(PyObject **)addr = NULL;
559 }
560 }
561 }
562}
563
564static int
565subtype_clear(PyObject *self)
566{
567 PyTypeObject *type, *base;
568 inquiry baseclear;
569
570 /* Find the nearest base with a different tp_clear
571 and clear slots while we're at it */
572 type = self->ob_type;
573 base = type;
574 while ((baseclear = base->tp_clear) == subtype_clear) {
575 if (base->ob_size)
576 clear_slots(base, self);
577 base = base->tp_base;
578 assert(base);
579 }
580
Guido van Rossuma3862092002-06-10 15:24:42 +0000581 /* There's no need to clear the instance dict (if any);
582 the collector will call its tp_clear handler. */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000583
584 if (baseclear)
585 return baseclear(self);
Guido van Rossum9475a232001-10-05 20:51:39 +0000586 return 0;
587}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000588
589static void
590subtype_dealloc(PyObject *self)
591{
Guido van Rossum14227b42001-12-06 02:35:58 +0000592 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000593 destructor basedealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000594
Guido van Rossum22b13872002-08-06 21:41:44 +0000595 /* Extract the type; we expect it to be a heap type */
596 type = self->ob_type;
597 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000598
Guido van Rossum22b13872002-08-06 21:41:44 +0000599 /* Test whether the type has GC exactly once */
600
601 if (!PyType_IS_GC(type)) {
602 /* It's really rare to find a dynamic type that doesn't have
603 GC; it can only happen when deriving from 'object' and not
604 adding any slots or instance variables. This allows
605 certain simplifications: there's no need to call
606 clear_slots(), or DECREF the dict, or clear weakrefs. */
607
608 /* Maybe call finalizer; exit early if resurrected */
Guido van Rossumfebd61d2002-08-08 20:55:20 +0000609 if (type->tp_del) {
610 type->tp_del(self);
611 if (self->ob_refcnt > 0)
612 return;
613 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000614
615 /* Find the nearest base with a different tp_dealloc */
616 base = type;
617 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
618 assert(base->ob_size == 0);
619 base = base->tp_base;
620 assert(base);
621 }
622
623 /* Call the base tp_dealloc() */
624 assert(basedealloc);
625 basedealloc(self);
626
627 /* Can't reference self beyond this point */
628 Py_DECREF(type);
629
630 /* Done */
631 return;
632 }
633
634 /* We get here only if the type has GC */
635
636 /* UnTrack and re-Track around the trashcan macro, alas */
Andrew M. Kuchlingc9172d32003-02-06 15:22:49 +0000637 /* See explanation at end of function for full disclosure */
Guido van Rossum0906e072002-08-07 20:42:09 +0000638 PyObject_GC_UnTrack(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000639 ++_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000640 Py_TRASHCAN_SAFE_BEGIN(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000641 --_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000642 _PyObject_GC_TRACK(self); /* We'll untrack for real later */
643
Guido van Rossum59195fd2003-06-13 20:54:40 +0000644 /* Find the nearest base with a different tp_dealloc */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000645 base = type;
646 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000647 base = base->tp_base;
648 assert(base);
Guido van Rossum14227b42001-12-06 02:35:58 +0000649 }
650
Guido van Rossum1987c662003-05-29 14:29:23 +0000651 /* If we added a weaklist, we clear it. Do this *before* calling
Guido van Rossum59195fd2003-06-13 20:54:40 +0000652 the finalizer (__del__), clearing slots, or clearing the instance
653 dict. */
654
Guido van Rossum1987c662003-05-29 14:29:23 +0000655 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
656 PyObject_ClearWeakRefs(self);
657
658 /* Maybe call finalizer; exit early if resurrected */
659 if (type->tp_del) {
660 type->tp_del(self);
661 if (self->ob_refcnt > 0)
662 goto endlabel;
663 }
664
Guido van Rossum59195fd2003-06-13 20:54:40 +0000665 /* Clear slots up to the nearest base with a different tp_dealloc */
666 base = type;
667 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
668 if (base->ob_size)
669 clear_slots(base, self);
670 base = base->tp_base;
671 assert(base);
672 }
673
Tim Peters6d6c1a32001-08-02 04:15:00 +0000674 /* If we added a dict, DECREF it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000675 if (type->tp_dictoffset && !base->tp_dictoffset) {
676 PyObject **dictptr = _PyObject_GetDictPtr(self);
677 if (dictptr != NULL) {
678 PyObject *dict = *dictptr;
679 if (dict != NULL) {
680 Py_DECREF(dict);
681 *dictptr = NULL;
682 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000683 }
684 }
685
686 /* Finalize GC if the base doesn't do GC and we do */
Guido van Rossum22b13872002-08-06 21:41:44 +0000687 if (!PyType_IS_GC(base))
Guido van Rossum048eb752001-10-02 21:24:57 +0000688 _PyObject_GC_UNTRACK(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000689
690 /* Call the base tp_dealloc() */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000691 assert(basedealloc);
692 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000693
694 /* Can't reference self beyond this point */
Guido van Rossum22b13872002-08-06 21:41:44 +0000695 Py_DECREF(type);
696
Guido van Rossum0906e072002-08-07 20:42:09 +0000697 endlabel:
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000698 ++_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000699 Py_TRASHCAN_SAFE_END(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000700 --_PyTrash_delete_nesting;
701
702 /* Explanation of the weirdness around the trashcan macros:
703
704 Q. What do the trashcan macros do?
705
706 A. Read the comment titled "Trashcan mechanism" in object.h.
707 For one, this explains why there must be a call to GC-untrack
708 before the trashcan begin macro. Without understanding the
709 trashcan code, the answers to the following questions don't make
710 sense.
711
712 Q. Why do we GC-untrack before the trashcan and then immediately
713 GC-track again afterward?
714
715 A. In the case that the base class is GC-aware, the base class
716 probably GC-untracks the object. If it does that using the
717 UNTRACK macro, this will crash when the object is already
718 untracked. Because we don't know what the base class does, the
719 only safe thing is to make sure the object is tracked when we
720 call the base class dealloc. But... The trashcan begin macro
721 requires that the object is *untracked* before it is called. So
722 the dance becomes:
723
724 GC untrack
725 trashcan begin
726 GC track
727
728 Q. Why the bizarre (net-zero) manipulation of
729 _PyTrash_delete_nesting around the trashcan macros?
730
731 A. Some base classes (e.g. list) also use the trashcan mechanism.
732 The following scenario used to be possible:
733
734 - suppose the trashcan level is one below the trashcan limit
735
736 - subtype_dealloc() is called
737
738 - the trashcan limit is not yet reached, so the trashcan level
739 is incremented and the code between trashcan begin and end is
740 executed
741
742 - this destroys much of the object's contents, including its
743 slots and __dict__
744
745 - basedealloc() is called; this is really list_dealloc(), or
746 some other type which also uses the trashcan macros
747
748 - the trashcan limit is now reached, so the object is put on the
749 trashcan's to-be-deleted-later list
750
751 - basedealloc() returns
752
753 - subtype_dealloc() decrefs the object's type
754
755 - subtype_dealloc() returns
756
757 - later, the trashcan code starts deleting the objects from its
758 to-be-deleted-later list
759
760 - subtype_dealloc() is called *AGAIN* for the same object
761
762 - at the very least (if the destroyed slots and __dict__ don't
763 cause problems) the object's type gets decref'ed a second
764 time, which is *BAD*!!!
765
766 The remedy is to make sure that if the code between trashcan
767 begin and end in subtype_dealloc() is called, the code between
768 trashcan begin and end in basedealloc() will also be called.
769 This is done by decrementing the level after passing into the
770 trashcan block, and incrementing it just before leaving the
771 block.
772
773 But now it's possible that a chain of objects consisting solely
774 of objects whose deallocator is subtype_dealloc() will defeat
775 the trashcan mechanism completely: the decremented level means
776 that the effective level never reaches the limit. Therefore, we
777 *increment* the level *before* entering the trashcan block, and
778 matchingly decrement it after leaving. This means the trashcan
779 code will trigger a little early, but that's no big deal.
780
781 Q. Are there any live examples of code in need of all this
782 complexity?
783
784 A. Yes. See SF bug 668433 for code that crashed (when Python was
785 compiled in debug mode) before the trashcan level manipulations
786 were added. For more discussion, see SF patches 581742, 575073
787 and bug 574207.
788 */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000789}
790
Jeremy Hylton938ace62002-07-17 16:30:39 +0000791static PyTypeObject *solid_base(PyTypeObject *type);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000792
Tim Peters6d6c1a32001-08-02 04:15:00 +0000793/* type test with subclassing support */
794
795int
796PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
797{
798 PyObject *mro;
799
Guido van Rossum9478d072001-09-07 18:52:13 +0000800 if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
801 return b == a || b == &PyBaseObject_Type;
802
Tim Peters6d6c1a32001-08-02 04:15:00 +0000803 mro = a->tp_mro;
804 if (mro != NULL) {
805 /* Deal with multiple inheritance without recursion
806 by walking the MRO tuple */
807 int i, n;
808 assert(PyTuple_Check(mro));
809 n = PyTuple_GET_SIZE(mro);
810 for (i = 0; i < n; i++) {
811 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
812 return 1;
813 }
814 return 0;
815 }
816 else {
817 /* a is not completely initilized yet; follow tp_base */
818 do {
819 if (a == b)
820 return 1;
821 a = a->tp_base;
822 } while (a != NULL);
823 return b == &PyBaseObject_Type;
824 }
825}
826
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000827/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +0000828 without looking in the instance dictionary
829 (so we can't use PyObject_GetAttr) but still binding
830 it to the instance. The arguments are the object,
831 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000832 static variable used to cache the interned Python string.
833
834 Two variants:
835
836 - lookup_maybe() returns NULL without raising an exception
837 when the _PyType_Lookup() call fails;
838
839 - lookup_method() always raises an exception upon errors.
840*/
Guido van Rossum60718732001-08-28 17:47:51 +0000841
842static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000843lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +0000844{
845 PyObject *res;
846
847 if (*attrobj == NULL) {
848 *attrobj = PyString_InternFromString(attrstr);
849 if (*attrobj == NULL)
850 return NULL;
851 }
852 res = _PyType_Lookup(self->ob_type, *attrobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000853 if (res != NULL) {
Guido van Rossum60718732001-08-28 17:47:51 +0000854 descrgetfunc f;
855 if ((f = res->ob_type->tp_descr_get) == NULL)
856 Py_INCREF(res);
857 else
858 res = f(res, self, (PyObject *)(self->ob_type));
859 }
860 return res;
861}
862
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000863static PyObject *
864lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
865{
866 PyObject *res = lookup_maybe(self, attrstr, attrobj);
867 if (res == NULL && !PyErr_Occurred())
868 PyErr_SetObject(PyExc_AttributeError, *attrobj);
869 return res;
870}
871
Guido van Rossum2730b132001-08-28 18:22:14 +0000872/* A variation of PyObject_CallMethod that uses lookup_method()
873 instead of PyObject_GetAttrString(). This uses the same convention
874 as lookup_method to cache the interned name string object. */
875
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000876static PyObject *
Guido van Rossum2730b132001-08-28 18:22:14 +0000877call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
878{
879 va_list va;
880 PyObject *args, *func = 0, *retval;
Guido van Rossum2730b132001-08-28 18:22:14 +0000881 va_start(va, format);
882
Guido van Rossumda21c012001-10-03 00:50:18 +0000883 func = lookup_maybe(o, name, nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000884 if (func == NULL) {
885 va_end(va);
886 if (!PyErr_Occurred())
Guido van Rossumda21c012001-10-03 00:50:18 +0000887 PyErr_SetObject(PyExc_AttributeError, *nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000888 return NULL;
889 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000890
891 if (format && *format)
892 args = Py_VaBuildValue(format, va);
893 else
894 args = PyTuple_New(0);
895
896 va_end(va);
897
898 if (args == NULL)
899 return NULL;
900
901 assert(PyTuple_Check(args));
902 retval = PyObject_Call(func, args, NULL);
903
904 Py_DECREF(args);
905 Py_DECREF(func);
906
907 return retval;
908}
909
910/* Clone of call_method() that returns NotImplemented when the lookup fails. */
911
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000912static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000913call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
914{
915 va_list va;
916 PyObject *args, *func = 0, *retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000917 va_start(va, format);
918
Guido van Rossumda21c012001-10-03 00:50:18 +0000919 func = lookup_maybe(o, name, nameobj);
Guido van Rossum2730b132001-08-28 18:22:14 +0000920 if (func == NULL) {
921 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000922 if (!PyErr_Occurred()) {
923 Py_INCREF(Py_NotImplemented);
924 return Py_NotImplemented;
925 }
Guido van Rossum717ce002001-09-14 16:58:08 +0000926 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +0000927 }
928
929 if (format && *format)
930 args = Py_VaBuildValue(format, va);
931 else
932 args = PyTuple_New(0);
933
934 va_end(va);
935
Guido van Rossum717ce002001-09-14 16:58:08 +0000936 if (args == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +0000937 return NULL;
938
Guido van Rossum717ce002001-09-14 16:58:08 +0000939 assert(PyTuple_Check(args));
940 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +0000941
942 Py_DECREF(args);
943 Py_DECREF(func);
944
945 return retval;
946}
947
Tim Petersa91e9642001-11-14 23:32:33 +0000948static int
949fill_classic_mro(PyObject *mro, PyObject *cls)
950{
951 PyObject *bases, *base;
952 int i, n;
953
954 assert(PyList_Check(mro));
955 assert(PyClass_Check(cls));
956 i = PySequence_Contains(mro, cls);
957 if (i < 0)
958 return -1;
959 if (!i) {
960 if (PyList_Append(mro, cls) < 0)
961 return -1;
962 }
963 bases = ((PyClassObject *)cls)->cl_bases;
964 assert(bases && PyTuple_Check(bases));
965 n = PyTuple_GET_SIZE(bases);
966 for (i = 0; i < n; i++) {
967 base = PyTuple_GET_ITEM(bases, i);
968 if (fill_classic_mro(mro, base) < 0)
969 return -1;
970 }
971 return 0;
972}
973
974static PyObject *
975classic_mro(PyObject *cls)
976{
977 PyObject *mro;
978
979 assert(PyClass_Check(cls));
980 mro = PyList_New(0);
981 if (mro != NULL) {
982 if (fill_classic_mro(mro, cls) == 0)
983 return mro;
984 Py_DECREF(mro);
985 }
986 return NULL;
987}
988
Tim Petersea7f75d2002-12-07 21:39:16 +0000989/*
Guido van Rossum1f121312002-11-14 19:49:16 +0000990 Method resolution order algorithm C3 described in
991 "A Monotonic Superclass Linearization for Dylan",
992 by Kim Barrett, Bob Cassel, Paul Haahr,
Tim Petersea7f75d2002-12-07 21:39:16 +0000993 David A. Moon, Keith Playford, and P. Tucker Withington.
Guido van Rossum1f121312002-11-14 19:49:16 +0000994 (OOPSLA 1996)
995
Guido van Rossum98f33732002-11-25 21:36:54 +0000996 Some notes about the rules implied by C3:
997
Tim Petersea7f75d2002-12-07 21:39:16 +0000998 No duplicate bases.
Guido van Rossum98f33732002-11-25 21:36:54 +0000999 It isn't legal to repeat a class in a list of base classes.
1000
1001 The next three properties are the 3 constraints in "C3".
1002
Tim Petersea7f75d2002-12-07 21:39:16 +00001003 Local precendece order.
Guido van Rossum98f33732002-11-25 21:36:54 +00001004 If A precedes B in C's MRO, then A will precede B in the MRO of all
1005 subclasses of C.
1006
1007 Monotonicity.
1008 The MRO of a class must be an extension without reordering of the
1009 MRO of each of its superclasses.
1010
1011 Extended Precedence Graph (EPG).
1012 Linearization is consistent if there is a path in the EPG from
1013 each class to all its successors in the linearization. See
1014 the paper for definition of EPG.
Guido van Rossum1f121312002-11-14 19:49:16 +00001015 */
1016
Tim Petersea7f75d2002-12-07 21:39:16 +00001017static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001018tail_contains(PyObject *list, int whence, PyObject *o) {
1019 int j, size;
1020 size = PyList_GET_SIZE(list);
1021
1022 for (j = whence+1; j < size; j++) {
1023 if (PyList_GET_ITEM(list, j) == o)
1024 return 1;
1025 }
1026 return 0;
1027}
1028
Guido van Rossum98f33732002-11-25 21:36:54 +00001029static PyObject *
1030class_name(PyObject *cls)
1031{
1032 PyObject *name = PyObject_GetAttrString(cls, "__name__");
1033 if (name == NULL) {
1034 PyErr_Clear();
1035 Py_XDECREF(name);
1036 name = PyObject_Repr(cls);
1037 }
1038 if (name == NULL)
1039 return NULL;
1040 if (!PyString_Check(name)) {
1041 Py_DECREF(name);
1042 return NULL;
1043 }
1044 return name;
1045}
1046
1047static int
1048check_duplicates(PyObject *list)
1049{
1050 int i, j, n;
1051 /* Let's use a quadratic time algorithm,
1052 assuming that the bases lists is short.
1053 */
1054 n = PyList_GET_SIZE(list);
1055 for (i = 0; i < n; i++) {
1056 PyObject *o = PyList_GET_ITEM(list, i);
1057 for (j = i + 1; j < n; j++) {
1058 if (PyList_GET_ITEM(list, j) == o) {
1059 o = class_name(o);
1060 PyErr_Format(PyExc_TypeError,
1061 "duplicate base class %s",
1062 o ? PyString_AS_STRING(o) : "?");
1063 Py_XDECREF(o);
1064 return -1;
1065 }
1066 }
1067 }
1068 return 0;
1069}
1070
1071/* Raise a TypeError for an MRO order disagreement.
1072
1073 It's hard to produce a good error message. In the absence of better
1074 insight into error reporting, report the classes that were candidates
1075 to be put next into the MRO. There is some conflict between the
1076 order in which they should be put in the MRO, but it's hard to
1077 diagnose what constraint can't be satisfied.
1078*/
1079
1080static void
1081set_mro_error(PyObject *to_merge, int *remain)
1082{
1083 int i, n, off, to_merge_size;
1084 char buf[1000];
1085 PyObject *k, *v;
1086 PyObject *set = PyDict_New();
1087
1088 to_merge_size = PyList_GET_SIZE(to_merge);
1089 for (i = 0; i < to_merge_size; i++) {
1090 PyObject *L = PyList_GET_ITEM(to_merge, i);
1091 if (remain[i] < PyList_GET_SIZE(L)) {
1092 PyObject *c = PyList_GET_ITEM(L, remain[i]);
1093 if (PyDict_SetItem(set, c, Py_None) < 0)
1094 return;
1095 }
1096 }
1097 n = PyDict_Size(set);
1098
Raymond Hettingerf394df42003-04-06 19:13:41 +00001099 off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \
1100consistent method resolution\norder (MRO) for bases");
Guido van Rossum98f33732002-11-25 21:36:54 +00001101 i = 0;
1102 while (PyDict_Next(set, &i, &k, &v) && off < sizeof(buf)) {
1103 PyObject *name = class_name(k);
1104 off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s",
1105 name ? PyString_AS_STRING(name) : "?");
1106 Py_XDECREF(name);
1107 if (--n && off+1 < sizeof(buf)) {
1108 buf[off++] = ',';
1109 buf[off] = '\0';
1110 }
1111 }
1112 PyErr_SetString(PyExc_TypeError, buf);
1113 Py_DECREF(set);
1114}
1115
Tim Petersea7f75d2002-12-07 21:39:16 +00001116static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001117pmerge(PyObject *acc, PyObject* to_merge) {
1118 int i, j, to_merge_size;
1119 int *remain;
1120 int ok, empty_cnt;
Tim Petersea7f75d2002-12-07 21:39:16 +00001121
Guido van Rossum1f121312002-11-14 19:49:16 +00001122 to_merge_size = PyList_GET_SIZE(to_merge);
1123
Guido van Rossum98f33732002-11-25 21:36:54 +00001124 /* remain stores an index into each sublist of to_merge.
1125 remain[i] is the index of the next base in to_merge[i]
1126 that is not included in acc.
1127 */
Guido van Rossum1f121312002-11-14 19:49:16 +00001128 remain = PyMem_MALLOC(SIZEOF_INT*to_merge_size);
1129 if (remain == NULL)
1130 return -1;
1131 for (i = 0; i < to_merge_size; i++)
1132 remain[i] = 0;
1133
1134 again:
1135 empty_cnt = 0;
1136 for (i = 0; i < to_merge_size; i++) {
1137 PyObject *candidate;
Tim Petersea7f75d2002-12-07 21:39:16 +00001138
Guido van Rossum1f121312002-11-14 19:49:16 +00001139 PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
1140
1141 if (remain[i] >= PyList_GET_SIZE(cur_list)) {
1142 empty_cnt++;
1143 continue;
1144 }
1145
Guido van Rossum98f33732002-11-25 21:36:54 +00001146 /* Choose next candidate for MRO.
1147
1148 The input sequences alone can determine the choice.
1149 If not, choose the class which appears in the MRO
1150 of the earliest direct superclass of the new class.
1151 */
1152
Guido van Rossum1f121312002-11-14 19:49:16 +00001153 candidate = PyList_GET_ITEM(cur_list, remain[i]);
1154 for (j = 0; j < to_merge_size; j++) {
1155 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum98f33732002-11-25 21:36:54 +00001156 if (tail_contains(j_lst, remain[j], candidate)) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001157 goto skip; /* continue outer loop */
Guido van Rossum98f33732002-11-25 21:36:54 +00001158 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001159 }
1160 ok = PyList_Append(acc, candidate);
1161 if (ok < 0) {
1162 PyMem_Free(remain);
1163 return -1;
1164 }
1165 for (j = 0; j < to_merge_size; j++) {
1166 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum768158c2002-12-31 16:33:01 +00001167 if (remain[j] < PyList_GET_SIZE(j_lst) &&
1168 PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001169 remain[j]++;
1170 }
1171 }
1172 goto again;
Tim Peters9a6b8d82002-11-14 23:22:33 +00001173 skip: ;
Guido van Rossum1f121312002-11-14 19:49:16 +00001174 }
1175
Guido van Rossum98f33732002-11-25 21:36:54 +00001176 if (empty_cnt == to_merge_size) {
1177 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001178 return 0;
Guido van Rossum98f33732002-11-25 21:36:54 +00001179 }
1180 set_mro_error(to_merge, remain);
1181 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001182 return -1;
1183}
1184
Tim Peters6d6c1a32001-08-02 04:15:00 +00001185static PyObject *
1186mro_implementation(PyTypeObject *type)
1187{
1188 int i, n, ok;
1189 PyObject *bases, *result;
Guido van Rossum1f121312002-11-14 19:49:16 +00001190 PyObject *to_merge, *bases_aslist;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001191
Guido van Rossum63517572002-06-18 16:44:57 +00001192 if(type->tp_dict == NULL) {
1193 if(PyType_Ready(type) < 0)
1194 return NULL;
1195 }
1196
Guido van Rossum98f33732002-11-25 21:36:54 +00001197 /* Find a superclass linearization that honors the constraints
1198 of the explicit lists of bases and the constraints implied by
Tim Petersea7f75d2002-12-07 21:39:16 +00001199 each base class.
Guido van Rossum98f33732002-11-25 21:36:54 +00001200
1201 to_merge is a list of lists, where each list is a superclass
1202 linearization implied by a base class. The last element of
1203 to_merge is the declared list of bases.
1204 */
1205
Tim Peters6d6c1a32001-08-02 04:15:00 +00001206 bases = type->tp_bases;
1207 n = PyTuple_GET_SIZE(bases);
Guido van Rossum1f121312002-11-14 19:49:16 +00001208
1209 to_merge = PyList_New(n+1);
1210 if (to_merge == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001211 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001212
Tim Peters6d6c1a32001-08-02 04:15:00 +00001213 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001214 PyObject *base = PyTuple_GET_ITEM(bases, i);
1215 PyObject *parentMRO;
1216 if (PyType_Check(base))
1217 parentMRO = PySequence_List(
1218 ((PyTypeObject*)base)->tp_mro);
1219 else
1220 parentMRO = classic_mro(base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001221 if (parentMRO == NULL) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001222 Py_DECREF(to_merge);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001223 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001224 }
1225
1226 PyList_SET_ITEM(to_merge, i, parentMRO);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001227 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001228
1229 bases_aslist = PySequence_List(bases);
1230 if (bases_aslist == NULL) {
1231 Py_DECREF(to_merge);
1232 return NULL;
1233 }
Guido van Rossum98f33732002-11-25 21:36:54 +00001234 /* This is just a basic sanity check. */
1235 if (check_duplicates(bases_aslist) < 0) {
1236 Py_DECREF(to_merge);
1237 Py_DECREF(bases_aslist);
1238 return NULL;
1239 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001240 PyList_SET_ITEM(to_merge, n, bases_aslist);
1241
1242 result = Py_BuildValue("[O]", (PyObject *)type);
1243 if (result == NULL) {
1244 Py_DECREF(to_merge);
1245 return NULL;
1246 }
1247
1248 ok = pmerge(result, to_merge);
1249 Py_DECREF(to_merge);
1250 if (ok < 0) {
1251 Py_DECREF(result);
1252 return NULL;
1253 }
1254
Tim Peters6d6c1a32001-08-02 04:15:00 +00001255 return result;
1256}
1257
1258static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001259mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001260{
1261 PyTypeObject *type = (PyTypeObject *)self;
1262
Tim Peters6d6c1a32001-08-02 04:15:00 +00001263 return mro_implementation(type);
1264}
1265
1266static int
1267mro_internal(PyTypeObject *type)
1268{
1269 PyObject *mro, *result, *tuple;
1270
1271 if (type->ob_type == &PyType_Type) {
1272 result = mro_implementation(type);
1273 }
1274 else {
Guido van Rossum60718732001-08-28 17:47:51 +00001275 static PyObject *mro_str;
1276 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001277 if (mro == NULL)
1278 return -1;
1279 result = PyObject_CallObject(mro, NULL);
1280 Py_DECREF(mro);
1281 }
1282 if (result == NULL)
1283 return -1;
1284 tuple = PySequence_Tuple(result);
1285 Py_DECREF(result);
1286 type->tp_mro = tuple;
1287 return 0;
1288}
1289
1290
1291/* Calculate the best base amongst multiple base classes.
1292 This is the first one that's on the path to the "solid base". */
1293
1294static PyTypeObject *
1295best_base(PyObject *bases)
1296{
1297 int i, n;
1298 PyTypeObject *base, *winner, *candidate, *base_i;
Tim Petersa91e9642001-11-14 23:32:33 +00001299 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001300
1301 assert(PyTuple_Check(bases));
1302 n = PyTuple_GET_SIZE(bases);
1303 assert(n > 0);
Tim Petersa91e9642001-11-14 23:32:33 +00001304 base = NULL;
1305 winner = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001306 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001307 base_proto = PyTuple_GET_ITEM(bases, i);
1308 if (PyClass_Check(base_proto))
1309 continue;
1310 if (!PyType_Check(base_proto)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001311 PyErr_SetString(
1312 PyExc_TypeError,
1313 "bases must be types");
1314 return NULL;
1315 }
Tim Petersa91e9642001-11-14 23:32:33 +00001316 base_i = (PyTypeObject *)base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001317 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001318 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001319 return NULL;
1320 }
1321 candidate = solid_base(base_i);
Tim Petersa91e9642001-11-14 23:32:33 +00001322 if (winner == NULL) {
1323 winner = candidate;
1324 base = base_i;
1325 }
1326 else if (PyType_IsSubtype(winner, candidate))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001327 ;
1328 else if (PyType_IsSubtype(candidate, winner)) {
1329 winner = candidate;
1330 base = base_i;
1331 }
1332 else {
1333 PyErr_SetString(
1334 PyExc_TypeError,
1335 "multiple bases have "
1336 "instance lay-out conflict");
1337 return NULL;
1338 }
1339 }
Guido van Rossume54616c2001-12-14 04:19:56 +00001340 if (base == NULL)
1341 PyErr_SetString(PyExc_TypeError,
1342 "a new-style class can't have only classic bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001343 return base;
1344}
1345
1346static int
1347extra_ivars(PyTypeObject *type, PyTypeObject *base)
1348{
Neil Schemenauerc806c882001-08-29 23:54:54 +00001349 size_t t_size = type->tp_basicsize;
1350 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001351
Guido van Rossum9676b222001-08-17 20:32:36 +00001352 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001353 if (type->tp_itemsize || base->tp_itemsize) {
1354 /* If itemsize is involved, stricter rules */
1355 return t_size != b_size ||
1356 type->tp_itemsize != base->tp_itemsize;
1357 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001358 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
1359 type->tp_weaklistoffset + sizeof(PyObject *) == t_size)
1360 t_size -= sizeof(PyObject *);
1361 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
1362 type->tp_dictoffset + sizeof(PyObject *) == t_size)
1363 t_size -= sizeof(PyObject *);
1364
1365 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001366}
1367
1368static PyTypeObject *
1369solid_base(PyTypeObject *type)
1370{
1371 PyTypeObject *base;
1372
1373 if (type->tp_base)
1374 base = solid_base(type->tp_base);
1375 else
1376 base = &PyBaseObject_Type;
1377 if (extra_ivars(type, base))
1378 return type;
1379 else
1380 return base;
1381}
1382
Jeremy Hylton938ace62002-07-17 16:30:39 +00001383static void object_dealloc(PyObject *);
1384static int object_init(PyObject *, PyObject *, PyObject *);
1385static int update_slot(PyTypeObject *, PyObject *);
1386static void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001387
1388static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001389subtype_dict(PyObject *obj, 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 NULL;
1398 }
1399 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +00001400 if (dict == NULL)
1401 *dictptr = dict = PyDict_New();
1402 Py_XINCREF(dict);
1403 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001404}
1405
Guido van Rossum6661be32001-10-26 04:26:12 +00001406static int
1407subtype_setdict(PyObject *obj, PyObject *value, void *context)
1408{
1409 PyObject **dictptr = _PyObject_GetDictPtr(obj);
1410 PyObject *dict;
1411
1412 if (dictptr == NULL) {
1413 PyErr_SetString(PyExc_AttributeError,
1414 "This object has no __dict__");
1415 return -1;
1416 }
Guido van Rossumd331cb52001-12-05 19:46:42 +00001417 if (value != NULL && !PyDict_Check(value)) {
Guido van Rossum6661be32001-10-26 04:26:12 +00001418 PyErr_SetString(PyExc_TypeError,
1419 "__dict__ must be set to a dictionary");
1420 return -1;
1421 }
1422 dict = *dictptr;
Guido van Rossumd331cb52001-12-05 19:46:42 +00001423 Py_XINCREF(value);
Guido van Rossum6661be32001-10-26 04:26:12 +00001424 *dictptr = value;
1425 Py_XDECREF(dict);
1426 return 0;
1427}
1428
Guido van Rossumad47da02002-08-12 19:05:44 +00001429static PyObject *
1430subtype_getweakref(PyObject *obj, void *context)
1431{
1432 PyObject **weaklistptr;
1433 PyObject *result;
1434
1435 if (obj->ob_type->tp_weaklistoffset == 0) {
1436 PyErr_SetString(PyExc_AttributeError,
1437 "This object has no __weaklist__");
1438 return NULL;
1439 }
1440 assert(obj->ob_type->tp_weaklistoffset > 0);
1441 assert(obj->ob_type->tp_weaklistoffset + sizeof(PyObject *) <=
Guido van Rossum3747a0f2002-08-12 19:25:08 +00001442 (size_t)(obj->ob_type->tp_basicsize));
Guido van Rossumad47da02002-08-12 19:05:44 +00001443 weaklistptr = (PyObject **)
Guido van Rossum3747a0f2002-08-12 19:25:08 +00001444 ((char *)obj + obj->ob_type->tp_weaklistoffset);
Guido van Rossumad47da02002-08-12 19:05:44 +00001445 if (*weaklistptr == NULL)
1446 result = Py_None;
1447 else
1448 result = *weaklistptr;
1449 Py_INCREF(result);
1450 return result;
1451}
1452
Guido van Rossum373c7412003-01-07 13:41:37 +00001453/* Three variants on the subtype_getsets list. */
1454
1455static PyGetSetDef subtype_getsets_full[] = {
Guido van Rossumad47da02002-08-12 19:05:44 +00001456 {"__dict__", subtype_dict, subtype_setdict,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001457 PyDoc_STR("dictionary for instance variables (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001458 {"__weakref__", subtype_getweakref, NULL,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001459 PyDoc_STR("list of weak references to the object (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001460 {0}
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001461};
1462
Guido van Rossum373c7412003-01-07 13:41:37 +00001463static PyGetSetDef subtype_getsets_dict_only[] = {
1464 {"__dict__", subtype_dict, subtype_setdict,
1465 PyDoc_STR("dictionary for instance variables (if defined)")},
1466 {0}
1467};
1468
1469static PyGetSetDef subtype_getsets_weakref_only[] = {
1470 {"__weakref__", subtype_getweakref, NULL,
1471 PyDoc_STR("list of weak references to the object (if defined)")},
1472 {0}
1473};
1474
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001475static int
1476valid_identifier(PyObject *s)
1477{
Guido van Rossum03013a02002-07-16 14:30:28 +00001478 unsigned char *p;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001479 int i, n;
1480
1481 if (!PyString_Check(s)) {
1482 PyErr_SetString(PyExc_TypeError,
1483 "__slots__ must be strings");
1484 return 0;
1485 }
Guido van Rossum03013a02002-07-16 14:30:28 +00001486 p = (unsigned char *) PyString_AS_STRING(s);
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001487 n = PyString_GET_SIZE(s);
1488 /* We must reject an empty name. As a hack, we bump the
1489 length to 1 so that the loop will balk on the trailing \0. */
1490 if (n == 0)
1491 n = 1;
1492 for (i = 0; i < n; i++, p++) {
1493 if (!(i == 0 ? isalpha(*p) : isalnum(*p)) && *p != '_') {
1494 PyErr_SetString(PyExc_TypeError,
1495 "__slots__ must be identifiers");
1496 return 0;
1497 }
1498 }
1499 return 1;
1500}
1501
Martin v. Löwisd919a592002-10-14 21:07:28 +00001502#ifdef Py_USING_UNICODE
1503/* Replace Unicode objects in slots. */
1504
1505static PyObject *
1506_unicode_to_string(PyObject *slots, int nslots)
1507{
1508 PyObject *tmp = slots;
1509 PyObject *o, *o1;
1510 int i;
1511 intintargfunc copy = slots->ob_type->tp_as_sequence->sq_slice;
1512 for (i = 0; i < nslots; i++) {
1513 if (PyUnicode_Check(o = PyTuple_GET_ITEM(tmp, i))) {
1514 if (tmp == slots) {
1515 tmp = copy(slots, 0, PyTuple_GET_SIZE(slots));
1516 if (tmp == NULL)
1517 return NULL;
1518 }
1519 o1 = _PyUnicode_AsDefaultEncodedString
1520 (o, NULL);
1521 if (o1 == NULL) {
1522 Py_DECREF(tmp);
1523 return 0;
1524 }
1525 Py_INCREF(o1);
1526 Py_DECREF(o);
1527 PyTuple_SET_ITEM(tmp, i, o1);
1528 }
1529 }
1530 return tmp;
1531}
1532#endif
1533
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001534static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001535type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
1536{
1537 PyObject *name, *bases, *dict;
1538 static char *kwlist[] = {"name", "bases", "dict", 0};
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001539 PyObject *slots, *tmp, *newslots;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001540 PyTypeObject *type, *base, *tmptype, *winner;
Guido van Rossume5c691a2003-03-07 15:13:17 +00001541 PyHeapTypeObject *et;
Guido van Rossum6f799372001-09-20 20:46:19 +00001542 PyMemberDef *mp;
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001543 int i, nbases, nslots, slotoffset, add_dict, add_weak;
Guido van Rossumad47da02002-08-12 19:05:44 +00001544 int j, may_add_dict, may_add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001545
Tim Peters3abca122001-10-27 19:37:48 +00001546 assert(args != NULL && PyTuple_Check(args));
1547 assert(kwds == NULL || PyDict_Check(kwds));
1548
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001549 /* Special case: type(x) should return x->ob_type */
Tim Peters3abca122001-10-27 19:37:48 +00001550 {
1551 const int nargs = PyTuple_GET_SIZE(args);
1552 const int nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
1553
1554 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
1555 PyObject *x = PyTuple_GET_ITEM(args, 0);
1556 Py_INCREF(x->ob_type);
1557 return (PyObject *) x->ob_type;
1558 }
1559
1560 /* SF bug 475327 -- if that didn't trigger, we need 3
1561 arguments. but PyArg_ParseTupleAndKeywords below may give
1562 a msg saying type() needs exactly 3. */
1563 if (nargs + nkwds != 3) {
1564 PyErr_SetString(PyExc_TypeError,
1565 "type() takes 1 or 3 arguments");
1566 return NULL;
1567 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001568 }
1569
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001570 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001571 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
1572 &name,
1573 &PyTuple_Type, &bases,
1574 &PyDict_Type, &dict))
1575 return NULL;
1576
1577 /* Determine the proper metatype to deal with this,
1578 and check for metatype conflicts while we're at it.
1579 Note that if some other metatype wins to contract,
1580 it's possible that its instances are not types. */
1581 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001582 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001583 for (i = 0; i < nbases; i++) {
1584 tmp = PyTuple_GET_ITEM(bases, i);
1585 tmptype = tmp->ob_type;
Tim Petersa91e9642001-11-14 23:32:33 +00001586 if (tmptype == &PyClass_Type)
1587 continue; /* Special case classic classes */
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001588 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001589 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001590 if (PyType_IsSubtype(tmptype, winner)) {
1591 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001592 continue;
1593 }
1594 PyErr_SetString(PyExc_TypeError,
Guido van Rossum636688d2003-04-23 12:07:22 +00001595 "metaclass conflict: "
1596 "the metaclass of a derived class "
1597 "must be a (non-strict) subclass "
1598 "of the metaclasses of all its bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001599 return NULL;
1600 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001601 if (winner != metatype) {
1602 if (winner->tp_new != type_new) /* Pass it to the winner */
1603 return winner->tp_new(winner, args, kwds);
1604 metatype = winner;
1605 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001606
1607 /* Adjust for empty tuple bases */
1608 if (nbases == 0) {
1609 bases = Py_BuildValue("(O)", &PyBaseObject_Type);
1610 if (bases == NULL)
1611 return NULL;
1612 nbases = 1;
1613 }
1614 else
1615 Py_INCREF(bases);
1616
1617 /* XXX From here until type is allocated, "return NULL" leaks bases! */
1618
1619 /* Calculate best base, and check that all bases are type objects */
1620 base = best_base(bases);
1621 if (base == NULL)
1622 return NULL;
1623 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
1624 PyErr_Format(PyExc_TypeError,
1625 "type '%.100s' is not an acceptable base type",
1626 base->tp_name);
1627 return NULL;
1628 }
1629
Tim Peters6d6c1a32001-08-02 04:15:00 +00001630 /* Check for a __slots__ sequence variable in dict, and count it */
1631 slots = PyDict_GetItemString(dict, "__slots__");
1632 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +00001633 add_dict = 0;
1634 add_weak = 0;
Guido van Rossumad47da02002-08-12 19:05:44 +00001635 may_add_dict = base->tp_dictoffset == 0;
1636 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
1637 if (slots == NULL) {
1638 if (may_add_dict) {
1639 add_dict++;
1640 }
1641 if (may_add_weak) {
1642 add_weak++;
1643 }
1644 }
1645 else {
1646 /* Have slots */
1647
Tim Peters6d6c1a32001-08-02 04:15:00 +00001648 /* Make it into a tuple */
1649 if (PyString_Check(slots))
1650 slots = Py_BuildValue("(O)", slots);
1651 else
1652 slots = PySequence_Tuple(slots);
1653 if (slots == NULL)
1654 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00001655 assert(PyTuple_Check(slots));
1656
1657 /* Are slots allowed? */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001658 nslots = PyTuple_GET_SIZE(slots);
Jeremy Hylton1c7a0ea2003-07-16 16:08:23 +00001659 if (nslots > 0 && base->tp_itemsize != 0) {
Guido van Rossumc4141872001-08-30 04:43:35 +00001660 PyErr_Format(PyExc_TypeError,
1661 "nonempty __slots__ "
1662 "not supported for subtype of '%s'",
1663 base->tp_name);
Guido van Rossumad47da02002-08-12 19:05:44 +00001664 bad_slots:
1665 Py_DECREF(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +00001666 return NULL;
1667 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001668
Martin v. Löwisd919a592002-10-14 21:07:28 +00001669#ifdef Py_USING_UNICODE
1670 tmp = _unicode_to_string(slots, nslots);
Martin v. Löwis13b1a5c2002-10-14 21:11:34 +00001671 if (tmp != slots) {
1672 Py_DECREF(slots);
1673 slots = tmp;
1674 }
Martin v. Löwisd919a592002-10-14 21:07:28 +00001675 if (!tmp)
1676 return NULL;
1677#endif
Guido van Rossumad47da02002-08-12 19:05:44 +00001678 /* Check for valid slot names and two special cases */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001679 for (i = 0; i < nslots; i++) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001680 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
1681 char *s;
1682 if (!valid_identifier(tmp))
1683 goto bad_slots;
1684 assert(PyString_Check(tmp));
1685 s = PyString_AS_STRING(tmp);
1686 if (strcmp(s, "__dict__") == 0) {
1687 if (!may_add_dict || add_dict) {
1688 PyErr_SetString(PyExc_TypeError,
1689 "__dict__ slot disallowed: "
1690 "we already got one");
1691 goto bad_slots;
1692 }
1693 add_dict++;
1694 }
1695 if (strcmp(s, "__weakref__") == 0) {
1696 if (!may_add_weak || add_weak) {
1697 PyErr_SetString(PyExc_TypeError,
1698 "__weakref__ slot disallowed: "
1699 "either we already got one, "
1700 "or __itemsize__ != 0");
1701 goto bad_slots;
1702 }
1703 add_weak++;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001704 }
1705 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001706
Guido van Rossumad47da02002-08-12 19:05:44 +00001707 /* Copy slots into yet another tuple, demangling names */
1708 newslots = PyTuple_New(nslots - add_dict - add_weak);
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001709 if (newslots == NULL)
Guido van Rossumad47da02002-08-12 19:05:44 +00001710 goto bad_slots;
1711 for (i = j = 0; i < nslots; i++) {
1712 char *s;
Guido van Rossum8e829202002-08-16 03:47:49 +00001713 char buffer[256];
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001714 tmp = PyTuple_GET_ITEM(slots, i);
Guido van Rossumad47da02002-08-12 19:05:44 +00001715 s = PyString_AS_STRING(tmp);
1716 if ((add_dict && strcmp(s, "__dict__") == 0) ||
1717 (add_weak && strcmp(s, "__weakref__") == 0))
1718 continue;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001719 if (_Py_Mangle(PyString_AS_STRING(name),
Guido van Rossumad47da02002-08-12 19:05:44 +00001720 PyString_AS_STRING(tmp),
1721 buffer, sizeof(buffer)))
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001722 {
1723 tmp = PyString_FromString(buffer);
1724 } else {
1725 Py_INCREF(tmp);
1726 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001727 PyTuple_SET_ITEM(newslots, j, tmp);
1728 j++;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001729 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001730 assert(j == nslots - add_dict - add_weak);
1731 nslots = j;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001732 Py_DECREF(slots);
1733 slots = newslots;
1734
Guido van Rossumad47da02002-08-12 19:05:44 +00001735 /* Secondary bases may provide weakrefs or dict */
1736 if (nbases > 1 &&
1737 ((may_add_dict && !add_dict) ||
1738 (may_add_weak && !add_weak))) {
1739 for (i = 0; i < nbases; i++) {
1740 tmp = PyTuple_GET_ITEM(bases, i);
1741 if (tmp == (PyObject *)base)
1742 continue; /* Skip primary base */
1743 if (PyClass_Check(tmp)) {
1744 /* Classic base class provides both */
1745 if (may_add_dict && !add_dict)
1746 add_dict++;
1747 if (may_add_weak && !add_weak)
1748 add_weak++;
1749 break;
1750 }
1751 assert(PyType_Check(tmp));
1752 tmptype = (PyTypeObject *)tmp;
1753 if (may_add_dict && !add_dict &&
1754 tmptype->tp_dictoffset != 0)
1755 add_dict++;
1756 if (may_add_weak && !add_weak &&
1757 tmptype->tp_weaklistoffset != 0)
1758 add_weak++;
1759 if (may_add_dict && !add_dict)
1760 continue;
1761 if (may_add_weak && !add_weak)
1762 continue;
1763 /* Nothing more to check */
1764 break;
1765 }
1766 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001767 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001768
1769 /* XXX From here until type is safely allocated,
1770 "return NULL" may leak slots! */
1771
1772 /* Allocate the type object */
1773 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
Guido van Rossumad47da02002-08-12 19:05:44 +00001774 if (type == NULL) {
1775 Py_XDECREF(slots);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001776 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00001777 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001778
1779 /* Keep name and slots alive in the extended type object */
Guido van Rossume5c691a2003-03-07 15:13:17 +00001780 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001781 Py_INCREF(name);
1782 et->name = name;
1783 et->slots = slots;
1784
Guido van Rossumdc91b992001-08-08 22:26:22 +00001785 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001786 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
1787 Py_TPFLAGS_BASETYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00001788 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
1789 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00001790
1791 /* It's a new-style number unless it specifically inherits any
1792 old-style numeric behavior */
1793 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
1794 (base->tp_as_number == NULL))
1795 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
1796
1797 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001798 type->tp_as_number = &et->as_number;
1799 type->tp_as_sequence = &et->as_sequence;
1800 type->tp_as_mapping = &et->as_mapping;
1801 type->tp_as_buffer = &et->as_buffer;
1802 type->tp_name = PyString_AS_STRING(name);
1803
1804 /* Set tp_base and tp_bases */
1805 type->tp_bases = bases;
1806 Py_INCREF(base);
1807 type->tp_base = base;
1808
Guido van Rossum687ae002001-10-15 22:03:32 +00001809 /* Initialize tp_dict from passed-in dict */
1810 type->tp_dict = dict = PyDict_Copy(dict);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001811 if (dict == NULL) {
1812 Py_DECREF(type);
1813 return NULL;
1814 }
1815
Guido van Rossumc3542212001-08-16 09:18:56 +00001816 /* Set __module__ in the dict */
1817 if (PyDict_GetItemString(dict, "__module__") == NULL) {
1818 tmp = PyEval_GetGlobals();
1819 if (tmp != NULL) {
1820 tmp = PyDict_GetItemString(tmp, "__name__");
1821 if (tmp != NULL) {
1822 if (PyDict_SetItemString(dict, "__module__",
1823 tmp) < 0)
1824 return NULL;
1825 }
1826 }
1827 }
1828
Tim Peters2f93e282001-10-04 05:27:00 +00001829 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
Tim Peters24008312002-03-17 18:56:20 +00001830 and is a string. The __doc__ accessor will first look for tp_doc;
1831 if that fails, it will still look into __dict__.
Tim Peters2f93e282001-10-04 05:27:00 +00001832 */
1833 {
1834 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
1835 if (doc != NULL && PyString_Check(doc)) {
1836 const size_t n = (size_t)PyString_GET_SIZE(doc);
Tim Peters59f809d2001-10-04 05:43:02 +00001837 type->tp_doc = (char *)PyObject_MALLOC(n+1);
Tim Peters2f93e282001-10-04 05:27:00 +00001838 if (type->tp_doc == NULL) {
1839 Py_DECREF(type);
1840 return NULL;
1841 }
1842 memcpy(type->tp_doc, PyString_AS_STRING(doc), n+1);
1843 }
1844 }
1845
Tim Peters6d6c1a32001-08-02 04:15:00 +00001846 /* Special-case __new__: if it's a plain function,
1847 make it a static function */
1848 tmp = PyDict_GetItemString(dict, "__new__");
1849 if (tmp != NULL && PyFunction_Check(tmp)) {
1850 tmp = PyStaticMethod_New(tmp);
1851 if (tmp == NULL) {
1852 Py_DECREF(type);
1853 return NULL;
1854 }
1855 PyDict_SetItemString(dict, "__new__", tmp);
1856 Py_DECREF(tmp);
1857 }
1858
1859 /* Add descriptors for custom slots from __slots__, or for __dict__ */
Guido van Rossume5c691a2003-03-07 15:13:17 +00001860 mp = PyHeapType_GET_MEMBERS(et);
Neil Schemenauerc806c882001-08-29 23:54:54 +00001861 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001862 if (slots != NULL) {
1863 for (i = 0; i < nslots; i++, mp++) {
1864 mp->name = PyString_AS_STRING(
1865 PyTuple_GET_ITEM(slots, i));
Guido van Rossum64b206c2001-12-04 17:13:22 +00001866 mp->type = T_OBJECT_EX;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001867 mp->offset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +00001868 if (base->tp_weaklistoffset == 0 &&
Guido van Rossum64b206c2001-12-04 17:13:22 +00001869 strcmp(mp->name, "__weakref__") == 0) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001870 add_weak++;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001871 mp->type = T_OBJECT;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001872 mp->flags = READONLY;
Guido van Rossum9676b222001-08-17 20:32:36 +00001873 type->tp_weaklistoffset = slotoffset;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001874 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001875 slotoffset += sizeof(PyObject *);
1876 }
1877 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001878 if (add_dict) {
1879 if (base->tp_itemsize)
1880 type->tp_dictoffset = -(long)sizeof(PyObject *);
1881 else
1882 type->tp_dictoffset = slotoffset;
1883 slotoffset += sizeof(PyObject *);
1884 }
1885 if (add_weak) {
1886 assert(!base->tp_itemsize);
1887 type->tp_weaklistoffset = slotoffset;
1888 slotoffset += sizeof(PyObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001889 }
1890 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001891 type->tp_itemsize = base->tp_itemsize;
Guido van Rossume5c691a2003-03-07 15:13:17 +00001892 type->tp_members = PyHeapType_GET_MEMBERS(et);
Guido van Rossum373c7412003-01-07 13:41:37 +00001893
1894 if (type->tp_weaklistoffset && type->tp_dictoffset)
1895 type->tp_getset = subtype_getsets_full;
1896 else if (type->tp_weaklistoffset && !type->tp_dictoffset)
1897 type->tp_getset = subtype_getsets_weakref_only;
1898 else if (!type->tp_weaklistoffset && type->tp_dictoffset)
1899 type->tp_getset = subtype_getsets_dict_only;
1900 else
1901 type->tp_getset = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001902
1903 /* Special case some slots */
1904 if (type->tp_dictoffset != 0 || nslots > 0) {
1905 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
1906 type->tp_getattro = PyObject_GenericGetAttr;
1907 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
1908 type->tp_setattro = PyObject_GenericSetAttr;
1909 }
1910 type->tp_dealloc = subtype_dealloc;
1911
Guido van Rossum9475a232001-10-05 20:51:39 +00001912 /* Enable GC unless there are really no instance variables possible */
1913 if (!(type->tp_basicsize == sizeof(PyObject) &&
1914 type->tp_itemsize == 0))
1915 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
1916
Tim Peters6d6c1a32001-08-02 04:15:00 +00001917 /* Always override allocation strategy to use regular heap */
1918 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00001919 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001920 type->tp_free = PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00001921 type->tp_traverse = subtype_traverse;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001922 type->tp_clear = subtype_clear;
Guido van Rossum048eb752001-10-02 21:24:57 +00001923 }
1924 else
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001925 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001926
1927 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001928 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001929 Py_DECREF(type);
1930 return NULL;
1931 }
1932
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001933 /* Put the proper slots in place */
1934 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00001935
Tim Peters6d6c1a32001-08-02 04:15:00 +00001936 return (PyObject *)type;
1937}
1938
1939/* Internal API to look for a name through the MRO.
1940 This returns a borrowed reference, and doesn't set an exception! */
1941PyObject *
1942_PyType_Lookup(PyTypeObject *type, PyObject *name)
1943{
1944 int i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00001945 PyObject *mro, *res, *base, *dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001946
Guido van Rossum687ae002001-10-15 22:03:32 +00001947 /* Look in tp_dict of types in MRO */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001948 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00001949
1950 /* If mro is NULL, the type is either not yet initialized
1951 by PyType_Ready(), or already cleared by type_clear().
1952 Either way the safest thing to do is to return NULL. */
1953 if (mro == NULL)
1954 return NULL;
1955
Tim Peters6d6c1a32001-08-02 04:15:00 +00001956 assert(PyTuple_Check(mro));
1957 n = PyTuple_GET_SIZE(mro);
1958 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001959 base = PyTuple_GET_ITEM(mro, i);
1960 if (PyClass_Check(base))
1961 dict = ((PyClassObject *)base)->cl_dict;
1962 else {
1963 assert(PyType_Check(base));
1964 dict = ((PyTypeObject *)base)->tp_dict;
1965 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001966 assert(dict && PyDict_Check(dict));
1967 res = PyDict_GetItem(dict, name);
1968 if (res != NULL)
1969 return res;
1970 }
1971 return NULL;
1972}
1973
1974/* This is similar to PyObject_GenericGetAttr(),
1975 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
1976static PyObject *
1977type_getattro(PyTypeObject *type, PyObject *name)
1978{
1979 PyTypeObject *metatype = type->ob_type;
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001980 PyObject *meta_attribute, *attribute;
1981 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001982
1983 /* Initialize this type (we'll assume the metatype is initialized) */
1984 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001985 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001986 return NULL;
1987 }
1988
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001989 /* No readable descriptor found yet */
1990 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00001991
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001992 /* Look for the attribute in the metatype */
1993 meta_attribute = _PyType_Lookup(metatype, name);
1994
1995 if (meta_attribute != NULL) {
1996 meta_get = meta_attribute->ob_type->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00001997
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001998 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
1999 /* Data descriptors implement tp_descr_set to intercept
2000 * writes. Assume the attribute is not overridden in
2001 * type's tp_dict (and bases): call the descriptor now.
2002 */
2003 return meta_get(meta_attribute, (PyObject *)type,
2004 (PyObject *)metatype);
2005 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002006 }
2007
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002008 /* No data descriptor found on metatype. Look in tp_dict of this
2009 * type and its bases */
2010 attribute = _PyType_Lookup(type, name);
2011 if (attribute != NULL) {
2012 /* Implement descriptor functionality, if any */
2013 descrgetfunc local_get = attribute->ob_type->tp_descr_get;
2014 if (local_get != NULL) {
2015 /* NULL 2nd argument indicates the descriptor was
2016 * found on the target object itself (or a base) */
2017 return local_get(attribute, (PyObject *)NULL,
2018 (PyObject *)type);
2019 }
Tim Peters34592512002-07-11 06:23:50 +00002020
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002021 Py_INCREF(attribute);
2022 return attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002023 }
2024
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002025 /* No attribute found in local __dict__ (or bases): use the
2026 * descriptor from the metatype, if any */
2027 if (meta_get != NULL)
2028 return meta_get(meta_attribute, (PyObject *)type,
2029 (PyObject *)metatype);
2030
2031 /* If an ordinary attribute was found on the metatype, return it now */
2032 if (meta_attribute != NULL) {
2033 Py_INCREF(meta_attribute);
2034 return meta_attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002035 }
2036
2037 /* Give up */
2038 PyErr_Format(PyExc_AttributeError,
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002039 "type object '%.50s' has no attribute '%.400s'",
2040 type->tp_name, PyString_AS_STRING(name));
Tim Peters6d6c1a32001-08-02 04:15:00 +00002041 return NULL;
2042}
2043
2044static int
2045type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
2046{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002047 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2048 PyErr_Format(
2049 PyExc_TypeError,
2050 "can't set attributes of built-in/extension type '%s'",
2051 type->tp_name);
2052 return -1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002053 }
Guido van Rossum8d24ee92003-03-24 23:49:49 +00002054 /* XXX Example of how I expect this to be used...
2055 if (update_subclasses(type, name, invalidate_cache, NULL) < 0)
2056 return -1;
2057 */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002058 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
2059 return -1;
2060 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002061}
2062
2063static void
2064type_dealloc(PyTypeObject *type)
2065{
Guido van Rossume5c691a2003-03-07 15:13:17 +00002066 PyHeapTypeObject *et;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002067
2068 /* Assert this is a heap-allocated type object */
2069 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002070 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00002071 PyObject_ClearWeakRefs((PyObject *)type);
Guido van Rossume5c691a2003-03-07 15:13:17 +00002072 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002073 Py_XDECREF(type->tp_base);
2074 Py_XDECREF(type->tp_dict);
2075 Py_XDECREF(type->tp_bases);
2076 Py_XDECREF(type->tp_mro);
Guido van Rossum687ae002001-10-15 22:03:32 +00002077 Py_XDECREF(type->tp_cache);
Guido van Rossum1c450732001-10-08 15:18:27 +00002078 Py_XDECREF(type->tp_subclasses);
Neal Norwitzcee5ca02002-07-30 00:42:06 +00002079 PyObject_Free(type->tp_doc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002080 Py_XDECREF(et->name);
2081 Py_XDECREF(et->slots);
2082 type->ob_type->tp_free((PyObject *)type);
2083}
2084
Guido van Rossum1c450732001-10-08 15:18:27 +00002085static PyObject *
2086type_subclasses(PyTypeObject *type, PyObject *args_ignored)
2087{
2088 PyObject *list, *raw, *ref;
2089 int i, n;
2090
2091 list = PyList_New(0);
2092 if (list == NULL)
2093 return NULL;
2094 raw = type->tp_subclasses;
2095 if (raw == NULL)
2096 return list;
2097 assert(PyList_Check(raw));
2098 n = PyList_GET_SIZE(raw);
2099 for (i = 0; i < n; i++) {
2100 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00002101 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00002102 ref = PyWeakref_GET_OBJECT(ref);
2103 if (ref != Py_None) {
2104 if (PyList_Append(list, ref) < 0) {
2105 Py_DECREF(list);
2106 return NULL;
2107 }
2108 }
2109 }
2110 return list;
2111}
2112
Tim Peters6d6c1a32001-08-02 04:15:00 +00002113static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002114 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002115 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
Guido van Rossum1c450732001-10-08 15:18:27 +00002116 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002117 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002118 {0}
2119};
2120
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002121PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002122"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002123"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002124
Guido van Rossum048eb752001-10-02 21:24:57 +00002125static int
2126type_traverse(PyTypeObject *type, visitproc visit, void *arg)
2127{
Guido van Rossum048eb752001-10-02 21:24:57 +00002128 int err;
2129
Guido van Rossuma3862092002-06-10 15:24:42 +00002130 /* Because of type_is_gc(), the collector only calls this
2131 for heaptypes. */
2132 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002133
2134#define VISIT(SLOT) \
2135 if (SLOT) { \
2136 err = visit((PyObject *)(SLOT), arg); \
2137 if (err) \
2138 return err; \
2139 }
2140
2141 VISIT(type->tp_dict);
Guido van Rossum687ae002001-10-15 22:03:32 +00002142 VISIT(type->tp_cache);
Guido van Rossum048eb752001-10-02 21:24:57 +00002143 VISIT(type->tp_mro);
2144 VISIT(type->tp_bases);
2145 VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00002146
2147 /* There's no need to visit type->tp_subclasses or
Guido van Rossume5c691a2003-03-07 15:13:17 +00002148 ((PyHeapTypeObject *)type)->slots, because they can't be involved
Guido van Rossuma3862092002-06-10 15:24:42 +00002149 in cycles; tp_subclasses is a list of weak references,
2150 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00002151
2152#undef VISIT
2153
2154 return 0;
2155}
2156
2157static int
2158type_clear(PyTypeObject *type)
2159{
Guido van Rossum048eb752001-10-02 21:24:57 +00002160 PyObject *tmp;
2161
Guido van Rossuma3862092002-06-10 15:24:42 +00002162 /* Because of type_is_gc(), the collector only calls this
2163 for heaptypes. */
2164 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002165
2166#define CLEAR(SLOT) \
2167 if (SLOT) { \
2168 tmp = (PyObject *)(SLOT); \
2169 SLOT = NULL; \
2170 Py_DECREF(tmp); \
2171 }
2172
Guido van Rossuma3862092002-06-10 15:24:42 +00002173 /* The only field we need to clear is tp_mro, which is part of a
2174 hard cycle (its first element is the class itself) that won't
2175 be broken otherwise (it's a tuple and tuples don't have a
2176 tp_clear handler). None of the other fields need to be
2177 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00002178
Guido van Rossuma3862092002-06-10 15:24:42 +00002179 tp_dict:
2180 It is a dict, so the collector will call its tp_clear.
2181
2182 tp_cache:
2183 Not used; if it were, it would be a dict.
2184
2185 tp_bases, tp_base:
2186 If these are involved in a cycle, there must be at least
2187 one other, mutable object in the cycle, e.g. a base
2188 class's dict; the cycle will be broken that way.
2189
2190 tp_subclasses:
2191 A list of weak references can't be part of a cycle; and
2192 lists have their own tp_clear.
2193
Guido van Rossume5c691a2003-03-07 15:13:17 +00002194 slots (in PyHeapTypeObject):
Guido van Rossuma3862092002-06-10 15:24:42 +00002195 A tuple of strings can't be part of a cycle.
2196 */
2197
2198 CLEAR(type->tp_mro);
Tim Peters2f93e282001-10-04 05:27:00 +00002199
Guido van Rossum048eb752001-10-02 21:24:57 +00002200#undef CLEAR
2201
2202 return 0;
2203}
2204
2205static int
2206type_is_gc(PyTypeObject *type)
2207{
2208 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
2209}
2210
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002211PyTypeObject PyType_Type = {
2212 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002213 0, /* ob_size */
2214 "type", /* tp_name */
Guido van Rossume5c691a2003-03-07 15:13:17 +00002215 sizeof(PyHeapTypeObject), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00002216 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002217 (destructor)type_dealloc, /* tp_dealloc */
2218 0, /* tp_print */
2219 0, /* tp_getattr */
2220 0, /* tp_setattr */
2221 type_compare, /* tp_compare */
2222 (reprfunc)type_repr, /* tp_repr */
2223 0, /* tp_as_number */
2224 0, /* tp_as_sequence */
2225 0, /* tp_as_mapping */
2226 (hashfunc)_Py_HashPointer, /* tp_hash */
2227 (ternaryfunc)type_call, /* tp_call */
2228 0, /* tp_str */
2229 (getattrofunc)type_getattro, /* tp_getattro */
2230 (setattrofunc)type_setattro, /* tp_setattro */
2231 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00002232 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2233 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002234 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00002235 (traverseproc)type_traverse, /* tp_traverse */
2236 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002237 0, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00002238 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002239 0, /* tp_iter */
2240 0, /* tp_iternext */
2241 type_methods, /* tp_methods */
2242 type_members, /* tp_members */
2243 type_getsets, /* tp_getset */
2244 0, /* tp_base */
2245 0, /* tp_dict */
2246 0, /* tp_descr_get */
2247 0, /* tp_descr_set */
2248 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
2249 0, /* tp_init */
2250 0, /* tp_alloc */
2251 type_new, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002252 PyObject_GC_Del, /* tp_free */
Guido van Rossum048eb752001-10-02 21:24:57 +00002253 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002254};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002255
2256
2257/* The base type of all types (eventually)... except itself. */
2258
2259static int
2260object_init(PyObject *self, PyObject *args, PyObject *kwds)
2261{
2262 return 0;
2263}
2264
Guido van Rossum298e4212003-02-13 16:30:16 +00002265/* If we don't have a tp_new for a new-style class, new will use this one.
2266 Therefore this should take no arguments/keywords. However, this new may
2267 also be inherited by objects that define a tp_init but no tp_new. These
2268 objects WILL pass argumets to tp_new, because it gets the same args as
2269 tp_init. So only allow arguments if we aren't using the default init, in
2270 which case we expect init to handle argument parsing. */
2271static PyObject *
2272object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2273{
2274 if (type->tp_init == object_init && (PyTuple_GET_SIZE(args) ||
2275 (kwds && PyDict_Check(kwds) && PyDict_Size(kwds)))) {
2276 PyErr_SetString(PyExc_TypeError,
2277 "default __new__ takes no parameters");
2278 return NULL;
2279 }
2280 return type->tp_alloc(type, 0);
2281}
2282
Tim Peters6d6c1a32001-08-02 04:15:00 +00002283static void
2284object_dealloc(PyObject *self)
2285{
2286 self->ob_type->tp_free(self);
2287}
2288
Guido van Rossum8e248182001-08-12 05:17:56 +00002289static PyObject *
2290object_repr(PyObject *self)
2291{
Guido van Rossum76e69632001-08-16 18:52:43 +00002292 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00002293 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002294
Guido van Rossum76e69632001-08-16 18:52:43 +00002295 type = self->ob_type;
2296 mod = type_module(type, NULL);
2297 if (mod == NULL)
2298 PyErr_Clear();
2299 else if (!PyString_Check(mod)) {
2300 Py_DECREF(mod);
2301 mod = NULL;
2302 }
2303 name = type_name(type, NULL);
2304 if (name == NULL)
2305 return NULL;
2306 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002307 rtn = PyString_FromFormat("<%s.%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002308 PyString_AS_STRING(mod),
2309 PyString_AS_STRING(name),
2310 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002311 else
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002312 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002313 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002314 Py_XDECREF(mod);
2315 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00002316 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002317}
2318
Guido van Rossumb8f63662001-08-15 23:57:02 +00002319static PyObject *
2320object_str(PyObject *self)
2321{
2322 unaryfunc f;
2323
2324 f = self->ob_type->tp_repr;
2325 if (f == NULL)
2326 f = object_repr;
2327 return f(self);
2328}
2329
Guido van Rossum8e248182001-08-12 05:17:56 +00002330static long
2331object_hash(PyObject *self)
2332{
2333 return _Py_HashPointer(self);
2334}
Guido van Rossum8e248182001-08-12 05:17:56 +00002335
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002336static PyObject *
2337object_get_class(PyObject *self, void *closure)
2338{
2339 Py_INCREF(self->ob_type);
2340 return (PyObject *)(self->ob_type);
2341}
2342
2343static int
2344equiv_structs(PyTypeObject *a, PyTypeObject *b)
2345{
2346 return a == b ||
2347 (a != NULL &&
2348 b != NULL &&
2349 a->tp_basicsize == b->tp_basicsize &&
2350 a->tp_itemsize == b->tp_itemsize &&
2351 a->tp_dictoffset == b->tp_dictoffset &&
2352 a->tp_weaklistoffset == b->tp_weaklistoffset &&
2353 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
2354 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
2355}
2356
2357static int
2358same_slots_added(PyTypeObject *a, PyTypeObject *b)
2359{
2360 PyTypeObject *base = a->tp_base;
2361 int size;
2362
2363 if (base != b->tp_base)
2364 return 0;
2365 if (equiv_structs(a, base) && equiv_structs(b, base))
2366 return 1;
2367 size = base->tp_basicsize;
2368 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
2369 size += sizeof(PyObject *);
2370 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
2371 size += sizeof(PyObject *);
2372 return size == a->tp_basicsize && size == b->tp_basicsize;
2373}
2374
2375static int
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002376compatible_for_assignment(PyTypeObject* old, PyTypeObject* new, char* attr)
2377{
2378 PyTypeObject *newbase, *oldbase;
2379
2380 if (new->tp_dealloc != old->tp_dealloc ||
2381 new->tp_free != old->tp_free)
2382 {
2383 PyErr_Format(PyExc_TypeError,
2384 "%s assignment: "
2385 "'%s' deallocator differs from '%s'",
2386 attr,
2387 new->tp_name,
2388 old->tp_name);
2389 return 0;
2390 }
2391 newbase = new;
2392 oldbase = old;
2393 while (equiv_structs(newbase, newbase->tp_base))
2394 newbase = newbase->tp_base;
2395 while (equiv_structs(oldbase, oldbase->tp_base))
2396 oldbase = oldbase->tp_base;
2397 if (newbase != oldbase &&
2398 (newbase->tp_base != oldbase->tp_base ||
2399 !same_slots_added(newbase, oldbase))) {
2400 PyErr_Format(PyExc_TypeError,
2401 "%s assignment: "
2402 "'%s' object layout differs from '%s'",
2403 attr,
2404 new->tp_name,
2405 old->tp_name);
2406 return 0;
2407 }
Tim Petersea7f75d2002-12-07 21:39:16 +00002408
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002409 return 1;
2410}
2411
2412static int
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002413object_set_class(PyObject *self, PyObject *value, void *closure)
2414{
2415 PyTypeObject *old = self->ob_type;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002416 PyTypeObject *new;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002417
Guido van Rossumb6b89422002-04-15 01:03:30 +00002418 if (value == NULL) {
2419 PyErr_SetString(PyExc_TypeError,
2420 "can't delete __class__ attribute");
2421 return -1;
2422 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002423 if (!PyType_Check(value)) {
2424 PyErr_Format(PyExc_TypeError,
2425 "__class__ must be set to new-style class, not '%s' object",
2426 value->ob_type->tp_name);
2427 return -1;
2428 }
2429 new = (PyTypeObject *)value;
Guido van Rossum40af8892002-08-10 05:42:07 +00002430 if (!(new->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
2431 !(old->tp_flags & Py_TPFLAGS_HEAPTYPE))
2432 {
2433 PyErr_Format(PyExc_TypeError,
2434 "__class__ assignment: only for heap types");
2435 return -1;
2436 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002437 if (compatible_for_assignment(new, old, "__class__")) {
2438 Py_INCREF(new);
2439 self->ob_type = new;
2440 Py_DECREF(old);
2441 return 0;
2442 }
2443 else {
Guido van Rossum9ee4b942002-05-24 18:47:47 +00002444 return -1;
2445 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002446}
2447
2448static PyGetSetDef object_getsets[] = {
2449 {"__class__", object_get_class, object_set_class,
Neal Norwitz858e34f2002-08-13 17:18:45 +00002450 PyDoc_STR("the object's class")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002451 {0}
2452};
2453
Guido van Rossumc53f0092003-02-18 22:05:12 +00002454
Guido van Rossum036f9992003-02-21 22:02:54 +00002455/* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
2456 We fall back to helpers in copy_reg for:
2457 - pickle protocols < 2
2458 - calculating the list of slot names (done only once per class)
2459 - the __newobj__ function (which is used as a token but never called)
2460*/
2461
2462static PyObject *
2463import_copy_reg(void)
2464{
2465 static PyObject *copy_reg_str;
Guido van Rossum3926a632001-09-25 16:25:58 +00002466
2467 if (!copy_reg_str) {
2468 copy_reg_str = PyString_InternFromString("copy_reg");
2469 if (copy_reg_str == NULL)
2470 return NULL;
2471 }
Guido van Rossum036f9992003-02-21 22:02:54 +00002472
2473 return PyImport_Import(copy_reg_str);
2474}
2475
2476static PyObject *
2477slotnames(PyObject *cls)
2478{
2479 PyObject *clsdict;
2480 PyObject *copy_reg;
2481 PyObject *slotnames;
2482
2483 if (!PyType_Check(cls)) {
2484 Py_INCREF(Py_None);
2485 return Py_None;
2486 }
2487
2488 clsdict = ((PyTypeObject *)cls)->tp_dict;
2489 slotnames = PyDict_GetItemString(clsdict, "__slotnames__");
2490 if (slotnames != NULL) {
2491 Py_INCREF(slotnames);
2492 return slotnames;
2493 }
2494
2495 copy_reg = import_copy_reg();
2496 if (copy_reg == NULL)
2497 return NULL;
2498
2499 slotnames = PyObject_CallMethod(copy_reg, "_slotnames", "O", cls);
2500 Py_DECREF(copy_reg);
2501 if (slotnames != NULL &&
2502 slotnames != Py_None &&
2503 !PyList_Check(slotnames))
2504 {
2505 PyErr_SetString(PyExc_TypeError,
2506 "copy_reg._slotnames didn't return a list or None");
2507 Py_DECREF(slotnames);
2508 slotnames = NULL;
2509 }
2510
2511 return slotnames;
2512}
2513
2514static PyObject *
2515reduce_2(PyObject *obj)
2516{
2517 PyObject *cls, *getnewargs;
2518 PyObject *args = NULL, *args2 = NULL;
2519 PyObject *getstate = NULL, *state = NULL, *names = NULL;
2520 PyObject *slots = NULL, *listitems = NULL, *dictitems = NULL;
2521 PyObject *copy_reg = NULL, *newobj = NULL, *res = NULL;
2522 int i, n;
2523
2524 cls = PyObject_GetAttrString(obj, "__class__");
2525 if (cls == NULL)
2526 return NULL;
2527
2528 getnewargs = PyObject_GetAttrString(obj, "__getnewargs__");
2529 if (getnewargs != NULL) {
2530 args = PyObject_CallObject(getnewargs, NULL);
2531 Py_DECREF(getnewargs);
2532 if (args != NULL && !PyTuple_Check(args)) {
2533 PyErr_SetString(PyExc_TypeError,
2534 "__getnewargs__ should return a tuple");
2535 goto end;
2536 }
2537 }
2538 else {
2539 PyErr_Clear();
2540 args = PyTuple_New(0);
2541 }
2542 if (args == NULL)
2543 goto end;
2544
2545 getstate = PyObject_GetAttrString(obj, "__getstate__");
2546 if (getstate != NULL) {
2547 state = PyObject_CallObject(getstate, NULL);
2548 Py_DECREF(getstate);
Neal Norwitze2fdc612003-06-08 13:19:58 +00002549 if (state == NULL)
2550 goto end;
Guido van Rossum036f9992003-02-21 22:02:54 +00002551 }
2552 else {
2553 state = PyObject_GetAttrString(obj, "__dict__");
2554 if (state == NULL) {
2555 PyErr_Clear();
2556 state = Py_None;
2557 Py_INCREF(state);
2558 }
2559 names = slotnames(cls);
2560 if (names == NULL)
2561 goto end;
2562 if (names != Py_None) {
2563 assert(PyList_Check(names));
2564 slots = PyDict_New();
2565 if (slots == NULL)
2566 goto end;
2567 n = 0;
2568 /* Can't pre-compute the list size; the list
2569 is stored on the class so accessible to other
2570 threads, which may be run by DECREF */
2571 for (i = 0; i < PyList_GET_SIZE(names); i++) {
2572 PyObject *name, *value;
2573 name = PyList_GET_ITEM(names, i);
2574 value = PyObject_GetAttr(obj, name);
2575 if (value == NULL)
2576 PyErr_Clear();
2577 else {
2578 int err = PyDict_SetItem(slots, name,
2579 value);
2580 Py_DECREF(value);
2581 if (err)
2582 goto end;
2583 n++;
2584 }
2585 }
2586 if (n) {
2587 state = Py_BuildValue("(NO)", state, slots);
2588 if (state == NULL)
2589 goto end;
2590 }
2591 }
2592 }
2593
2594 if (!PyList_Check(obj)) {
2595 listitems = Py_None;
2596 Py_INCREF(listitems);
2597 }
2598 else {
2599 listitems = PyObject_GetIter(obj);
2600 if (listitems == NULL)
2601 goto end;
2602 }
2603
2604 if (!PyDict_Check(obj)) {
2605 dictitems = Py_None;
2606 Py_INCREF(dictitems);
2607 }
2608 else {
2609 dictitems = PyObject_CallMethod(obj, "iteritems", "");
2610 if (dictitems == NULL)
2611 goto end;
2612 }
2613
2614 copy_reg = import_copy_reg();
2615 if (copy_reg == NULL)
2616 goto end;
2617 newobj = PyObject_GetAttrString(copy_reg, "__newobj__");
2618 if (newobj == NULL)
2619 goto end;
2620
2621 n = PyTuple_GET_SIZE(args);
2622 args2 = PyTuple_New(n+1);
2623 if (args2 == NULL)
2624 goto end;
2625 PyTuple_SET_ITEM(args2, 0, cls);
2626 cls = NULL;
2627 for (i = 0; i < n; i++) {
2628 PyObject *v = PyTuple_GET_ITEM(args, i);
2629 Py_INCREF(v);
2630 PyTuple_SET_ITEM(args2, i+1, v);
2631 }
2632
2633 res = Py_BuildValue("(OOOOO)",
2634 newobj, args2, state, listitems, dictitems);
2635
2636 end:
2637 Py_XDECREF(cls);
2638 Py_XDECREF(args);
2639 Py_XDECREF(args2);
Jeremy Hyltond06483c2003-04-09 21:01:42 +00002640 Py_XDECREF(slots);
Guido van Rossum036f9992003-02-21 22:02:54 +00002641 Py_XDECREF(state);
2642 Py_XDECREF(names);
2643 Py_XDECREF(listitems);
2644 Py_XDECREF(dictitems);
2645 Py_XDECREF(copy_reg);
2646 Py_XDECREF(newobj);
2647 return res;
2648}
2649
2650static PyObject *
2651object_reduce_ex(PyObject *self, PyObject *args)
2652{
2653 /* Call copy_reg._reduce_ex(self, proto) */
2654 PyObject *reduce, *copy_reg, *res;
2655 int proto = 0;
2656
2657 if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
2658 return NULL;
2659
2660 reduce = PyObject_GetAttrString(self, "__reduce__");
2661 if (reduce == NULL)
2662 PyErr_Clear();
2663 else {
2664 PyObject *cls, *clsreduce, *objreduce;
2665 int override;
2666 cls = PyObject_GetAttrString(self, "__class__");
2667 if (cls == NULL) {
2668 Py_DECREF(reduce);
2669 return NULL;
2670 }
2671 clsreduce = PyObject_GetAttrString(cls, "__reduce__");
2672 Py_DECREF(cls);
2673 if (clsreduce == NULL) {
2674 Py_DECREF(reduce);
2675 return NULL;
2676 }
2677 objreduce = PyDict_GetItemString(PyBaseObject_Type.tp_dict,
2678 "__reduce__");
2679 override = (clsreduce != objreduce);
2680 Py_DECREF(clsreduce);
2681 if (override) {
2682 res = PyObject_CallObject(reduce, NULL);
2683 Py_DECREF(reduce);
2684 return res;
2685 }
2686 else
2687 Py_DECREF(reduce);
2688 }
2689
2690 if (proto >= 2)
2691 return reduce_2(self);
2692
2693 copy_reg = import_copy_reg();
Guido van Rossum3926a632001-09-25 16:25:58 +00002694 if (!copy_reg)
2695 return NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00002696
Guido van Rossumc53f0092003-02-18 22:05:12 +00002697 res = PyEval_CallMethod(copy_reg, "_reduce_ex", "(Oi)", self, proto);
Guido van Rossum3926a632001-09-25 16:25:58 +00002698 Py_DECREF(copy_reg);
Guido van Rossum036f9992003-02-21 22:02:54 +00002699
Guido van Rossum3926a632001-09-25 16:25:58 +00002700 return res;
2701}
2702
2703static PyMethodDef object_methods[] = {
Guido van Rossumc53f0092003-02-18 22:05:12 +00002704 {"__reduce_ex__", object_reduce_ex, METH_VARARGS,
2705 PyDoc_STR("helper for pickle")},
2706 {"__reduce__", object_reduce_ex, METH_VARARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002707 PyDoc_STR("helper for pickle")},
Guido van Rossum3926a632001-09-25 16:25:58 +00002708 {0}
2709};
2710
Guido van Rossum036f9992003-02-21 22:02:54 +00002711
Tim Peters6d6c1a32001-08-02 04:15:00 +00002712PyTypeObject PyBaseObject_Type = {
2713 PyObject_HEAD_INIT(&PyType_Type)
2714 0, /* ob_size */
2715 "object", /* tp_name */
2716 sizeof(PyObject), /* tp_basicsize */
2717 0, /* tp_itemsize */
2718 (destructor)object_dealloc, /* tp_dealloc */
2719 0, /* tp_print */
2720 0, /* tp_getattr */
2721 0, /* tp_setattr */
2722 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002723 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002724 0, /* tp_as_number */
2725 0, /* tp_as_sequence */
2726 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002727 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002728 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002729 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002730 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002731 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002732 0, /* tp_as_buffer */
2733 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002734 PyDoc_STR("The most base type"), /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002735 0, /* tp_traverse */
2736 0, /* tp_clear */
2737 0, /* tp_richcompare */
2738 0, /* tp_weaklistoffset */
2739 0, /* tp_iter */
2740 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00002741 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002742 0, /* tp_members */
2743 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002744 0, /* tp_base */
2745 0, /* tp_dict */
2746 0, /* tp_descr_get */
2747 0, /* tp_descr_set */
2748 0, /* tp_dictoffset */
2749 object_init, /* tp_init */
2750 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossum298e4212003-02-13 16:30:16 +00002751 object_new, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002752 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002753};
2754
2755
2756/* Initialize the __dict__ in a type object */
2757
2758static int
2759add_methods(PyTypeObject *type, PyMethodDef *meth)
2760{
Guido van Rossum687ae002001-10-15 22:03:32 +00002761 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002762
2763 for (; meth->ml_name != NULL; meth++) {
2764 PyObject *descr;
2765 if (PyDict_GetItemString(dict, meth->ml_name))
2766 continue;
Fred Drake7bf97152002-03-28 05:33:33 +00002767 if (meth->ml_flags & METH_CLASS) {
2768 if (meth->ml_flags & METH_STATIC) {
2769 PyErr_SetString(PyExc_ValueError,
2770 "method cannot be both class and static");
2771 return -1;
2772 }
Tim Petersbca1cbc2002-12-09 22:56:13 +00002773 descr = PyDescr_NewClassMethod(type, meth);
Fred Drake7bf97152002-03-28 05:33:33 +00002774 }
2775 else if (meth->ml_flags & METH_STATIC) {
Guido van Rossum9af48ff2003-02-11 17:12:46 +00002776 PyObject *cfunc = PyCFunction_New(meth, NULL);
2777 if (cfunc == NULL)
2778 return -1;
2779 descr = PyStaticMethod_New(cfunc);
2780 Py_DECREF(cfunc);
Fred Drake7bf97152002-03-28 05:33:33 +00002781 }
2782 else {
2783 descr = PyDescr_NewMethod(type, meth);
2784 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002785 if (descr == NULL)
2786 return -1;
Fred Drake7bf97152002-03-28 05:33:33 +00002787 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002788 return -1;
2789 Py_DECREF(descr);
2790 }
2791 return 0;
2792}
2793
2794static int
Guido van Rossum6f799372001-09-20 20:46:19 +00002795add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002796{
Guido van Rossum687ae002001-10-15 22:03:32 +00002797 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002798
2799 for (; memb->name != NULL; memb++) {
2800 PyObject *descr;
2801 if (PyDict_GetItemString(dict, memb->name))
2802 continue;
2803 descr = PyDescr_NewMember(type, memb);
2804 if (descr == NULL)
2805 return -1;
2806 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
2807 return -1;
2808 Py_DECREF(descr);
2809 }
2810 return 0;
2811}
2812
2813static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00002814add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002815{
Guido van Rossum687ae002001-10-15 22:03:32 +00002816 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002817
2818 for (; gsp->name != NULL; gsp++) {
2819 PyObject *descr;
2820 if (PyDict_GetItemString(dict, gsp->name))
2821 continue;
2822 descr = PyDescr_NewGetSet(type, gsp);
2823
2824 if (descr == NULL)
2825 return -1;
2826 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
2827 return -1;
2828 Py_DECREF(descr);
2829 }
2830 return 0;
2831}
2832
Guido van Rossum13d52f02001-08-10 21:24:08 +00002833static void
2834inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002835{
2836 int oldsize, newsize;
2837
Guido van Rossum13d52f02001-08-10 21:24:08 +00002838 /* Special flag magic */
2839 if (!type->tp_as_buffer && base->tp_as_buffer) {
2840 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
2841 type->tp_flags |=
2842 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
2843 }
2844 if (!type->tp_as_sequence && base->tp_as_sequence) {
2845 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
2846 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
2847 }
2848 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
2849 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
2850 if ((!type->tp_as_number && base->tp_as_number) ||
2851 (!type->tp_as_sequence && base->tp_as_sequence)) {
2852 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
2853 if (!type->tp_as_number && !type->tp_as_sequence) {
2854 type->tp_flags |= base->tp_flags &
2855 Py_TPFLAGS_HAVE_INPLACEOPS;
2856 }
2857 }
2858 /* Wow */
2859 }
2860 if (!type->tp_as_number && base->tp_as_number) {
2861 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
2862 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
2863 }
2864
2865 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00002866 oldsize = base->tp_basicsize;
2867 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
2868 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
2869 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00002870 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
2871 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00002872 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00002873 if (type->tp_traverse == NULL)
2874 type->tp_traverse = base->tp_traverse;
2875 if (type->tp_clear == NULL)
2876 type->tp_clear = base->tp_clear;
2877 }
2878 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
Guido van Rossumf884b742001-12-17 17:14:22 +00002879 /* The condition below could use some explanation.
2880 It appears that tp_new is not inherited for static types
2881 whose base class is 'object'; this seems to be a precaution
2882 so that old extension types don't suddenly become
2883 callable (object.__new__ wouldn't insure the invariants
2884 that the extension type's own factory function ensures).
2885 Heap types, of course, are under our control, so they do
2886 inherit tp_new; static extension types that specify some
2887 other built-in type as the default are considered
2888 new-style-aware so they also inherit object.__new__. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002889 if (base != &PyBaseObject_Type ||
2890 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2891 if (type->tp_new == NULL)
2892 type->tp_new = base->tp_new;
2893 }
2894 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00002895 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00002896
2897 /* Copy other non-function slots */
2898
2899#undef COPYVAL
2900#define COPYVAL(SLOT) \
2901 if (type->SLOT == 0) type->SLOT = base->SLOT
2902
2903 COPYVAL(tp_itemsize);
2904 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
2905 COPYVAL(tp_weaklistoffset);
2906 }
2907 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2908 COPYVAL(tp_dictoffset);
2909 }
Guido van Rossum13d52f02001-08-10 21:24:08 +00002910}
2911
2912static void
2913inherit_slots(PyTypeObject *type, PyTypeObject *base)
2914{
2915 PyTypeObject *basebase;
2916
2917#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00002918#undef COPYSLOT
2919#undef COPYNUM
2920#undef COPYSEQ
2921#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00002922#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00002923
2924#define SLOTDEFINED(SLOT) \
2925 (base->SLOT != 0 && \
2926 (basebase == NULL || base->SLOT != basebase->SLOT))
2927
Tim Peters6d6c1a32001-08-02 04:15:00 +00002928#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00002929 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00002930
2931#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
2932#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
2933#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00002934#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002935
Guido van Rossum13d52f02001-08-10 21:24:08 +00002936 /* This won't inherit indirect slots (from tp_as_number etc.)
2937 if type doesn't provide the space. */
2938
2939 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
2940 basebase = base->tp_base;
2941 if (basebase->tp_as_number == NULL)
2942 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002943 COPYNUM(nb_add);
2944 COPYNUM(nb_subtract);
2945 COPYNUM(nb_multiply);
2946 COPYNUM(nb_divide);
2947 COPYNUM(nb_remainder);
2948 COPYNUM(nb_divmod);
2949 COPYNUM(nb_power);
2950 COPYNUM(nb_negative);
2951 COPYNUM(nb_positive);
2952 COPYNUM(nb_absolute);
2953 COPYNUM(nb_nonzero);
2954 COPYNUM(nb_invert);
2955 COPYNUM(nb_lshift);
2956 COPYNUM(nb_rshift);
2957 COPYNUM(nb_and);
2958 COPYNUM(nb_xor);
2959 COPYNUM(nb_or);
2960 COPYNUM(nb_coerce);
2961 COPYNUM(nb_int);
2962 COPYNUM(nb_long);
2963 COPYNUM(nb_float);
2964 COPYNUM(nb_oct);
2965 COPYNUM(nb_hex);
2966 COPYNUM(nb_inplace_add);
2967 COPYNUM(nb_inplace_subtract);
2968 COPYNUM(nb_inplace_multiply);
2969 COPYNUM(nb_inplace_divide);
2970 COPYNUM(nb_inplace_remainder);
2971 COPYNUM(nb_inplace_power);
2972 COPYNUM(nb_inplace_lshift);
2973 COPYNUM(nb_inplace_rshift);
2974 COPYNUM(nb_inplace_and);
2975 COPYNUM(nb_inplace_xor);
2976 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00002977 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
2978 COPYNUM(nb_true_divide);
2979 COPYNUM(nb_floor_divide);
2980 COPYNUM(nb_inplace_true_divide);
2981 COPYNUM(nb_inplace_floor_divide);
2982 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002983 }
2984
Guido van Rossum13d52f02001-08-10 21:24:08 +00002985 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
2986 basebase = base->tp_base;
2987 if (basebase->tp_as_sequence == NULL)
2988 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002989 COPYSEQ(sq_length);
2990 COPYSEQ(sq_concat);
2991 COPYSEQ(sq_repeat);
2992 COPYSEQ(sq_item);
2993 COPYSEQ(sq_slice);
2994 COPYSEQ(sq_ass_item);
2995 COPYSEQ(sq_ass_slice);
2996 COPYSEQ(sq_contains);
2997 COPYSEQ(sq_inplace_concat);
2998 COPYSEQ(sq_inplace_repeat);
2999 }
3000
Guido van Rossum13d52f02001-08-10 21:24:08 +00003001 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
3002 basebase = base->tp_base;
3003 if (basebase->tp_as_mapping == NULL)
3004 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003005 COPYMAP(mp_length);
3006 COPYMAP(mp_subscript);
3007 COPYMAP(mp_ass_subscript);
3008 }
3009
Tim Petersfc57ccb2001-10-12 02:38:24 +00003010 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
3011 basebase = base->tp_base;
3012 if (basebase->tp_as_buffer == NULL)
3013 basebase = NULL;
3014 COPYBUF(bf_getreadbuffer);
3015 COPYBUF(bf_getwritebuffer);
3016 COPYBUF(bf_getsegcount);
3017 COPYBUF(bf_getcharbuffer);
3018 }
3019
Guido van Rossum13d52f02001-08-10 21:24:08 +00003020 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003021
Tim Peters6d6c1a32001-08-02 04:15:00 +00003022 COPYSLOT(tp_dealloc);
3023 COPYSLOT(tp_print);
3024 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
3025 type->tp_getattr = base->tp_getattr;
3026 type->tp_getattro = base->tp_getattro;
3027 }
3028 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
3029 type->tp_setattr = base->tp_setattr;
3030 type->tp_setattro = base->tp_setattro;
3031 }
3032 /* tp_compare see tp_richcompare */
3033 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003034 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003035 COPYSLOT(tp_call);
3036 COPYSLOT(tp_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003037 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003038 if (type->tp_compare == NULL &&
3039 type->tp_richcompare == NULL &&
3040 type->tp_hash == NULL)
3041 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003042 type->tp_compare = base->tp_compare;
3043 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003044 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003045 }
3046 }
3047 else {
3048 COPYSLOT(tp_compare);
3049 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003050 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
3051 COPYSLOT(tp_iter);
3052 COPYSLOT(tp_iternext);
3053 }
3054 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
3055 COPYSLOT(tp_descr_get);
3056 COPYSLOT(tp_descr_set);
3057 COPYSLOT(tp_dictoffset);
3058 COPYSLOT(tp_init);
3059 COPYSLOT(tp_alloc);
Guido van Rossumcc8fe042002-04-05 17:10:16 +00003060 COPYSLOT(tp_is_gc);
Tim Peters3cfe7542003-05-21 21:29:48 +00003061 if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) ==
3062 (base->tp_flags & Py_TPFLAGS_HAVE_GC)) {
3063 /* They agree about gc. */
3064 COPYSLOT(tp_free);
3065 }
3066 else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3067 type->tp_free == NULL &&
3068 base->tp_free == _PyObject_Del) {
3069 /* A bit of magic to plug in the correct default
3070 * tp_free function when a derived class adds gc,
3071 * didn't define tp_free, and the base uses the
3072 * default non-gc tp_free.
3073 */
3074 type->tp_free = PyObject_GC_Del;
3075 }
3076 /* else they didn't agree about gc, and there isn't something
3077 * obvious to be done -- the type is on its own.
3078 */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003079 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003080}
3081
Jeremy Hylton938ace62002-07-17 16:30:39 +00003082static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00003083
Tim Peters6d6c1a32001-08-02 04:15:00 +00003084int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00003085PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003086{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003087 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003088 PyTypeObject *base;
3089 int i, n;
3090
Guido van Rossumcab05802002-06-10 15:29:03 +00003091 if (type->tp_flags & Py_TPFLAGS_READY) {
3092 assert(type->tp_dict != NULL);
Guido van Rossumd614f972001-08-10 17:39:49 +00003093 return 0;
Guido van Rossumcab05802002-06-10 15:29:03 +00003094 }
Guido van Rossumd614f972001-08-10 17:39:49 +00003095 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00003096
3097 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003098
Tim Peters36eb4df2003-03-23 03:33:13 +00003099#ifdef Py_TRACE_REFS
3100 /* PyType_Ready is the closest thing we have to a choke point
3101 * for type objects, so is the best place I can think of to try
3102 * to get type objects into the doubly-linked list of all objects.
3103 * Still, not all type objects go thru PyType_Ready.
3104 */
Tim Peters7571a0f2003-03-23 17:52:28 +00003105 _Py_AddToAllObjects((PyObject *)type, 0);
Tim Peters36eb4df2003-03-23 03:33:13 +00003106#endif
3107
Tim Peters6d6c1a32001-08-02 04:15:00 +00003108 /* Initialize tp_base (defaults to BaseObject unless that's us) */
3109 base = type->tp_base;
3110 if (base == NULL && type != &PyBaseObject_Type)
3111 base = type->tp_base = &PyBaseObject_Type;
3112
Guido van Rossum323a9cf2002-08-14 17:26:30 +00003113 /* Initialize the base class */
3114 if (base && base->tp_dict == NULL) {
3115 if (PyType_Ready(base) < 0)
3116 goto error;
3117 }
3118
Guido van Rossum0986d822002-04-08 01:38:42 +00003119 /* Initialize ob_type if NULL. This means extensions that want to be
3120 compilable separately on Windows can call PyType_Ready() instead of
3121 initializing the ob_type field of their type objects. */
3122 if (type->ob_type == NULL)
3123 type->ob_type = base->ob_type;
3124
Tim Peters6d6c1a32001-08-02 04:15:00 +00003125 /* Initialize tp_bases */
3126 bases = type->tp_bases;
3127 if (bases == NULL) {
3128 if (base == NULL)
3129 bases = PyTuple_New(0);
3130 else
3131 bases = Py_BuildValue("(O)", base);
3132 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003133 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003134 type->tp_bases = bases;
3135 }
3136
Guido van Rossum687ae002001-10-15 22:03:32 +00003137 /* Initialize tp_dict */
3138 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003139 if (dict == NULL) {
3140 dict = PyDict_New();
3141 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003142 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00003143 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003144 }
3145
Guido van Rossum687ae002001-10-15 22:03:32 +00003146 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003147 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003148 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003149 if (type->tp_methods != NULL) {
3150 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003151 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003152 }
3153 if (type->tp_members != NULL) {
3154 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003155 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003156 }
3157 if (type->tp_getset != NULL) {
3158 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003159 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003160 }
3161
Tim Peters6d6c1a32001-08-02 04:15:00 +00003162 /* Calculate method resolution order */
3163 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00003164 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003165 }
3166
Guido van Rossum13d52f02001-08-10 21:24:08 +00003167 /* Inherit special flags from dominant base */
3168 if (type->tp_base != NULL)
3169 inherit_special(type, type->tp_base);
3170
Tim Peters6d6c1a32001-08-02 04:15:00 +00003171 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003172 bases = type->tp_mro;
3173 assert(bases != NULL);
3174 assert(PyTuple_Check(bases));
3175 n = PyTuple_GET_SIZE(bases);
3176 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003177 PyObject *b = PyTuple_GET_ITEM(bases, i);
3178 if (PyType_Check(b))
3179 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003180 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003181
Tim Peters3cfe7542003-05-21 21:29:48 +00003182 /* Sanity check for tp_free. */
3183 if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) &&
3184 (type->tp_free == NULL || type->tp_free == PyObject_Del)) {
3185 /* This base class needs to call tp_free, but doesn't have
3186 * one, or its tp_free is for non-gc'ed objects.
3187 */
3188 PyErr_Format(PyExc_TypeError, "type '%.100s' participates in "
3189 "gc and is a base type but has inappropriate "
3190 "tp_free slot",
3191 type->tp_name);
3192 goto error;
3193 }
3194
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003195 /* if the type dictionary doesn't contain a __doc__, set it from
3196 the tp_doc slot.
3197 */
3198 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
3199 if (type->tp_doc != NULL) {
3200 PyObject *doc = PyString_FromString(type->tp_doc);
3201 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
3202 Py_DECREF(doc);
3203 } else {
Guido van Rossumd4641072002-04-03 02:13:37 +00003204 PyDict_SetItemString(type->tp_dict,
3205 "__doc__", Py_None);
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003206 }
3207 }
3208
Guido van Rossum13d52f02001-08-10 21:24:08 +00003209 /* Some more special stuff */
3210 base = type->tp_base;
3211 if (base != NULL) {
3212 if (type->tp_as_number == NULL)
3213 type->tp_as_number = base->tp_as_number;
3214 if (type->tp_as_sequence == NULL)
3215 type->tp_as_sequence = base->tp_as_sequence;
3216 if (type->tp_as_mapping == NULL)
3217 type->tp_as_mapping = base->tp_as_mapping;
Guido van Rossumeea47182003-02-11 20:39:59 +00003218 if (type->tp_as_buffer == NULL)
3219 type->tp_as_buffer = base->tp_as_buffer;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003220 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003221
Guido van Rossum1c450732001-10-08 15:18:27 +00003222 /* Link into each base class's list of subclasses */
3223 bases = type->tp_bases;
3224 n = PyTuple_GET_SIZE(bases);
3225 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003226 PyObject *b = PyTuple_GET_ITEM(bases, i);
3227 if (PyType_Check(b) &&
3228 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00003229 goto error;
3230 }
3231
Guido van Rossum13d52f02001-08-10 21:24:08 +00003232 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00003233 assert(type->tp_dict != NULL);
3234 type->tp_flags =
3235 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003236 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00003237
3238 error:
3239 type->tp_flags &= ~Py_TPFLAGS_READYING;
3240 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003241}
3242
Guido van Rossum1c450732001-10-08 15:18:27 +00003243static int
3244add_subclass(PyTypeObject *base, PyTypeObject *type)
3245{
3246 int i;
3247 PyObject *list, *ref, *new;
3248
3249 list = base->tp_subclasses;
3250 if (list == NULL) {
3251 base->tp_subclasses = list = PyList_New(0);
3252 if (list == NULL)
3253 return -1;
3254 }
3255 assert(PyList_Check(list));
3256 new = PyWeakref_NewRef((PyObject *)type, NULL);
3257 i = PyList_GET_SIZE(list);
3258 while (--i >= 0) {
3259 ref = PyList_GET_ITEM(list, i);
3260 assert(PyWeakref_CheckRef(ref));
Guido van Rossum3930bc32002-10-18 13:51:49 +00003261 if (PyWeakref_GET_OBJECT(ref) == Py_None)
3262 return PyList_SetItem(list, i, new);
Guido van Rossum1c450732001-10-08 15:18:27 +00003263 }
3264 i = PyList_Append(list, new);
3265 Py_DECREF(new);
3266 return i;
3267}
3268
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003269static void
3270remove_subclass(PyTypeObject *base, PyTypeObject *type)
3271{
3272 int i;
3273 PyObject *list, *ref;
3274
3275 list = base->tp_subclasses;
3276 if (list == NULL) {
3277 return;
3278 }
3279 assert(PyList_Check(list));
3280 i = PyList_GET_SIZE(list);
3281 while (--i >= 0) {
3282 ref = PyList_GET_ITEM(list, i);
3283 assert(PyWeakref_CheckRef(ref));
3284 if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
3285 /* this can't fail, right? */
3286 PySequence_DelItem(list, i);
3287 return;
3288 }
3289 }
3290}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003291
3292/* Generic wrappers for overloadable 'operators' such as __getitem__ */
3293
3294/* There's a wrapper *function* for each distinct function typedef used
3295 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
3296 wrapper *table* for each distinct operation (e.g. __len__, __add__).
3297 Most tables have only one entry; the tables for binary operators have two
3298 entries, one regular and one with reversed arguments. */
3299
3300static PyObject *
3301wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
3302{
3303 inquiry func = (inquiry)wrapped;
3304 int res;
3305
3306 if (!PyArg_ParseTuple(args, ""))
3307 return NULL;
3308 res = (*func)(self);
3309 if (res == -1 && PyErr_Occurred())
3310 return NULL;
3311 return PyInt_FromLong((long)res);
3312}
3313
Tim Peters6d6c1a32001-08-02 04:15:00 +00003314static PyObject *
3315wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
3316{
3317 binaryfunc func = (binaryfunc)wrapped;
3318 PyObject *other;
3319
3320 if (!PyArg_ParseTuple(args, "O", &other))
3321 return NULL;
3322 return (*func)(self, other);
3323}
3324
3325static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003326wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
3327{
3328 binaryfunc func = (binaryfunc)wrapped;
3329 PyObject *other;
3330
3331 if (!PyArg_ParseTuple(args, "O", &other))
3332 return NULL;
3333 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003334 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003335 Py_INCREF(Py_NotImplemented);
3336 return Py_NotImplemented;
3337 }
3338 return (*func)(self, other);
3339}
3340
3341static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003342wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3343{
3344 binaryfunc func = (binaryfunc)wrapped;
3345 PyObject *other;
3346
3347 if (!PyArg_ParseTuple(args, "O", &other))
3348 return NULL;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003349 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003350 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003351 Py_INCREF(Py_NotImplemented);
3352 return Py_NotImplemented;
3353 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003354 return (*func)(other, self);
3355}
3356
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003357static PyObject *
3358wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
3359{
3360 coercion func = (coercion)wrapped;
3361 PyObject *other, *res;
3362 int ok;
3363
3364 if (!PyArg_ParseTuple(args, "O", &other))
3365 return NULL;
3366 ok = func(&self, &other);
3367 if (ok < 0)
3368 return NULL;
3369 if (ok > 0) {
3370 Py_INCREF(Py_NotImplemented);
3371 return Py_NotImplemented;
3372 }
3373 res = PyTuple_New(2);
3374 if (res == NULL) {
3375 Py_DECREF(self);
3376 Py_DECREF(other);
3377 return NULL;
3378 }
3379 PyTuple_SET_ITEM(res, 0, self);
3380 PyTuple_SET_ITEM(res, 1, other);
3381 return res;
3382}
3383
Tim Peters6d6c1a32001-08-02 04:15:00 +00003384static PyObject *
3385wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
3386{
3387 ternaryfunc func = (ternaryfunc)wrapped;
3388 PyObject *other;
3389 PyObject *third = Py_None;
3390
3391 /* Note: This wrapper only works for __pow__() */
3392
3393 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
3394 return NULL;
3395 return (*func)(self, other, third);
3396}
3397
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00003398static PyObject *
3399wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3400{
3401 ternaryfunc func = (ternaryfunc)wrapped;
3402 PyObject *other;
3403 PyObject *third = Py_None;
3404
3405 /* Note: This wrapper only works for __pow__() */
3406
3407 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
3408 return NULL;
3409 return (*func)(other, self, third);
3410}
3411
Tim Peters6d6c1a32001-08-02 04:15:00 +00003412static PyObject *
3413wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
3414{
3415 unaryfunc func = (unaryfunc)wrapped;
3416
3417 if (!PyArg_ParseTuple(args, ""))
3418 return NULL;
3419 return (*func)(self);
3420}
3421
Tim Peters6d6c1a32001-08-02 04:15:00 +00003422static PyObject *
3423wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
3424{
3425 intargfunc func = (intargfunc)wrapped;
3426 int i;
3427
3428 if (!PyArg_ParseTuple(args, "i", &i))
3429 return NULL;
3430 return (*func)(self, i);
3431}
3432
Guido van Rossum5d815f32001-08-17 21:57:47 +00003433static int
3434getindex(PyObject *self, PyObject *arg)
3435{
3436 int i;
3437
3438 i = PyInt_AsLong(arg);
3439 if (i == -1 && PyErr_Occurred())
3440 return -1;
3441 if (i < 0) {
3442 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
3443 if (sq && sq->sq_length) {
3444 int n = (*sq->sq_length)(self);
3445 if (n < 0)
3446 return -1;
3447 i += n;
3448 }
3449 }
3450 return i;
3451}
3452
3453static PyObject *
3454wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
3455{
3456 intargfunc func = (intargfunc)wrapped;
3457 PyObject *arg;
3458 int i;
3459
Guido van Rossumf4593e02001-10-03 12:09:30 +00003460 if (PyTuple_GET_SIZE(args) == 1) {
3461 arg = PyTuple_GET_ITEM(args, 0);
3462 i = getindex(self, arg);
3463 if (i == -1 && PyErr_Occurred())
3464 return NULL;
3465 return (*func)(self, i);
3466 }
3467 PyArg_ParseTuple(args, "O", &arg);
3468 assert(PyErr_Occurred());
3469 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003470}
3471
Tim Peters6d6c1a32001-08-02 04:15:00 +00003472static PyObject *
3473wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
3474{
3475 intintargfunc func = (intintargfunc)wrapped;
3476 int i, j;
3477
3478 if (!PyArg_ParseTuple(args, "ii", &i, &j))
3479 return NULL;
3480 return (*func)(self, i, j);
3481}
3482
Tim Peters6d6c1a32001-08-02 04:15:00 +00003483static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003484wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003485{
3486 intobjargproc func = (intobjargproc)wrapped;
3487 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003488 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003489
Guido van Rossum5d815f32001-08-17 21:57:47 +00003490 if (!PyArg_ParseTuple(args, "OO", &arg, &value))
3491 return NULL;
3492 i = getindex(self, arg);
3493 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00003494 return NULL;
3495 res = (*func)(self, i, value);
3496 if (res == -1 && PyErr_Occurred())
3497 return NULL;
3498 Py_INCREF(Py_None);
3499 return Py_None;
3500}
3501
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003502static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003503wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003504{
3505 intobjargproc func = (intobjargproc)wrapped;
3506 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003507 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003508
Guido van Rossum5d815f32001-08-17 21:57:47 +00003509 if (!PyArg_ParseTuple(args, "O", &arg))
3510 return NULL;
3511 i = getindex(self, arg);
3512 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003513 return NULL;
3514 res = (*func)(self, i, NULL);
3515 if (res == -1 && PyErr_Occurred())
3516 return NULL;
3517 Py_INCREF(Py_None);
3518 return Py_None;
3519}
3520
Tim Peters6d6c1a32001-08-02 04:15:00 +00003521static PyObject *
3522wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
3523{
3524 intintobjargproc func = (intintobjargproc)wrapped;
3525 int i, j, res;
3526 PyObject *value;
3527
3528 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
3529 return NULL;
3530 res = (*func)(self, i, j, value);
3531 if (res == -1 && PyErr_Occurred())
3532 return NULL;
3533 Py_INCREF(Py_None);
3534 return Py_None;
3535}
3536
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003537static PyObject *
3538wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
3539{
3540 intintobjargproc func = (intintobjargproc)wrapped;
3541 int i, j, res;
3542
3543 if (!PyArg_ParseTuple(args, "ii", &i, &j))
3544 return NULL;
3545 res = (*func)(self, i, j, NULL);
3546 if (res == -1 && PyErr_Occurred())
3547 return NULL;
3548 Py_INCREF(Py_None);
3549 return Py_None;
3550}
3551
Tim Peters6d6c1a32001-08-02 04:15:00 +00003552/* XXX objobjproc is a misnomer; should be objargpred */
3553static PyObject *
3554wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
3555{
3556 objobjproc func = (objobjproc)wrapped;
3557 int res;
3558 PyObject *value;
3559
3560 if (!PyArg_ParseTuple(args, "O", &value))
3561 return NULL;
3562 res = (*func)(self, value);
3563 if (res == -1 && PyErr_Occurred())
3564 return NULL;
3565 return PyInt_FromLong((long)res);
3566}
3567
Tim Peters6d6c1a32001-08-02 04:15:00 +00003568static PyObject *
3569wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
3570{
3571 objobjargproc func = (objobjargproc)wrapped;
3572 int res;
3573 PyObject *key, *value;
3574
3575 if (!PyArg_ParseTuple(args, "OO", &key, &value))
3576 return NULL;
3577 res = (*func)(self, key, value);
3578 if (res == -1 && PyErr_Occurred())
3579 return NULL;
3580 Py_INCREF(Py_None);
3581 return Py_None;
3582}
3583
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003584static PyObject *
3585wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
3586{
3587 objobjargproc func = (objobjargproc)wrapped;
3588 int res;
3589 PyObject *key;
3590
3591 if (!PyArg_ParseTuple(args, "O", &key))
3592 return NULL;
3593 res = (*func)(self, key, NULL);
3594 if (res == -1 && PyErr_Occurred())
3595 return NULL;
3596 Py_INCREF(Py_None);
3597 return Py_None;
3598}
3599
Tim Peters6d6c1a32001-08-02 04:15:00 +00003600static PyObject *
3601wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
3602{
3603 cmpfunc func = (cmpfunc)wrapped;
3604 int res;
3605 PyObject *other;
3606
3607 if (!PyArg_ParseTuple(args, "O", &other))
3608 return NULL;
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00003609 if (other->ob_type->tp_compare != func &&
3610 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00003611 PyErr_Format(
3612 PyExc_TypeError,
3613 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
3614 self->ob_type->tp_name,
3615 self->ob_type->tp_name,
3616 other->ob_type->tp_name);
3617 return NULL;
3618 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003619 res = (*func)(self, other);
3620 if (PyErr_Occurred())
3621 return NULL;
3622 return PyInt_FromLong((long)res);
3623}
3624
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003625/* Helper to check for object.__setattr__ or __delattr__ applied to a type.
Guido van Rossum52b27052003-04-15 20:05:10 +00003626 This is called the Carlo Verre hack after its discoverer. */
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003627static int
3628hackcheck(PyObject *self, setattrofunc func, char *what)
3629{
3630 PyTypeObject *type = self->ob_type;
3631 while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE)
3632 type = type->tp_base;
3633 if (type->tp_setattro != func) {
3634 PyErr_Format(PyExc_TypeError,
3635 "can't apply this %s to %s object",
3636 what,
3637 type->tp_name);
3638 return 0;
3639 }
3640 return 1;
3641}
3642
Tim Peters6d6c1a32001-08-02 04:15:00 +00003643static PyObject *
3644wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
3645{
3646 setattrofunc func = (setattrofunc)wrapped;
3647 int res;
3648 PyObject *name, *value;
3649
3650 if (!PyArg_ParseTuple(args, "OO", &name, &value))
3651 return NULL;
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003652 if (!hackcheck(self, func, "__setattr__"))
3653 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003654 res = (*func)(self, name, value);
3655 if (res < 0)
3656 return NULL;
3657 Py_INCREF(Py_None);
3658 return Py_None;
3659}
3660
3661static PyObject *
3662wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
3663{
3664 setattrofunc func = (setattrofunc)wrapped;
3665 int res;
3666 PyObject *name;
3667
3668 if (!PyArg_ParseTuple(args, "O", &name))
3669 return NULL;
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003670 if (!hackcheck(self, func, "__delattr__"))
3671 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003672 res = (*func)(self, name, NULL);
3673 if (res < 0)
3674 return NULL;
3675 Py_INCREF(Py_None);
3676 return Py_None;
3677}
3678
Tim Peters6d6c1a32001-08-02 04:15:00 +00003679static PyObject *
3680wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
3681{
3682 hashfunc func = (hashfunc)wrapped;
3683 long res;
3684
3685 if (!PyArg_ParseTuple(args, ""))
3686 return NULL;
3687 res = (*func)(self);
3688 if (res == -1 && PyErr_Occurred())
3689 return NULL;
3690 return PyInt_FromLong(res);
3691}
3692
Tim Peters6d6c1a32001-08-02 04:15:00 +00003693static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00003694wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003695{
3696 ternaryfunc func = (ternaryfunc)wrapped;
3697
Guido van Rossumc8e56452001-10-22 00:43:43 +00003698 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003699}
3700
Tim Peters6d6c1a32001-08-02 04:15:00 +00003701static PyObject *
3702wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
3703{
3704 richcmpfunc func = (richcmpfunc)wrapped;
3705 PyObject *other;
3706
3707 if (!PyArg_ParseTuple(args, "O", &other))
3708 return NULL;
3709 return (*func)(self, other, op);
3710}
3711
3712#undef RICHCMP_WRAPPER
3713#define RICHCMP_WRAPPER(NAME, OP) \
3714static PyObject * \
3715richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
3716{ \
3717 return wrap_richcmpfunc(self, args, wrapped, OP); \
3718}
3719
Jack Jansen8e938b42001-08-08 15:29:49 +00003720RICHCMP_WRAPPER(lt, Py_LT)
3721RICHCMP_WRAPPER(le, Py_LE)
3722RICHCMP_WRAPPER(eq, Py_EQ)
3723RICHCMP_WRAPPER(ne, Py_NE)
3724RICHCMP_WRAPPER(gt, Py_GT)
3725RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003726
Tim Peters6d6c1a32001-08-02 04:15:00 +00003727static PyObject *
3728wrap_next(PyObject *self, PyObject *args, void *wrapped)
3729{
3730 unaryfunc func = (unaryfunc)wrapped;
3731 PyObject *res;
3732
3733 if (!PyArg_ParseTuple(args, ""))
3734 return NULL;
3735 res = (*func)(self);
3736 if (res == NULL && !PyErr_Occurred())
3737 PyErr_SetNone(PyExc_StopIteration);
3738 return res;
3739}
3740
Tim Peters6d6c1a32001-08-02 04:15:00 +00003741static PyObject *
3742wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
3743{
3744 descrgetfunc func = (descrgetfunc)wrapped;
3745 PyObject *obj;
3746 PyObject *type = NULL;
3747
3748 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
3749 return NULL;
Guido van Rossum82ed25c2003-02-11 16:25:43 +00003750 if (obj == Py_None)
3751 obj = NULL;
3752 if (type == Py_None)
3753 type = NULL;
3754 if (type == NULL &&obj == NULL) {
3755 PyErr_SetString(PyExc_TypeError,
3756 "__get__(None, None) is invalid");
3757 return NULL;
3758 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003759 return (*func)(self, obj, type);
3760}
3761
Tim Peters6d6c1a32001-08-02 04:15:00 +00003762static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003763wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003764{
3765 descrsetfunc func = (descrsetfunc)wrapped;
3766 PyObject *obj, *value;
3767 int ret;
3768
3769 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
3770 return NULL;
3771 ret = (*func)(self, obj, value);
3772 if (ret < 0)
3773 return NULL;
3774 Py_INCREF(Py_None);
3775 return Py_None;
3776}
Guido van Rossum22b13872002-08-06 21:41:44 +00003777
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00003778static PyObject *
3779wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
3780{
3781 descrsetfunc func = (descrsetfunc)wrapped;
3782 PyObject *obj;
3783 int ret;
3784
3785 if (!PyArg_ParseTuple(args, "O", &obj))
3786 return NULL;
3787 ret = (*func)(self, obj, NULL);
3788 if (ret < 0)
3789 return NULL;
3790 Py_INCREF(Py_None);
3791 return Py_None;
3792}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003793
Tim Peters6d6c1a32001-08-02 04:15:00 +00003794static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00003795wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003796{
3797 initproc func = (initproc)wrapped;
3798
Guido van Rossumc8e56452001-10-22 00:43:43 +00003799 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003800 return NULL;
3801 Py_INCREF(Py_None);
3802 return Py_None;
3803}
3804
Tim Peters6d6c1a32001-08-02 04:15:00 +00003805static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003806tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003807{
Barry Warsaw60f01882001-08-22 19:24:42 +00003808 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003809 PyObject *arg0, *res;
3810
3811 if (self == NULL || !PyType_Check(self))
3812 Py_FatalError("__new__() called with non-type 'self'");
3813 type = (PyTypeObject *)self;
3814 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003815 PyErr_Format(PyExc_TypeError,
3816 "%s.__new__(): not enough arguments",
3817 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003818 return NULL;
3819 }
3820 arg0 = PyTuple_GET_ITEM(args, 0);
3821 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003822 PyErr_Format(PyExc_TypeError,
3823 "%s.__new__(X): X is not a type object (%s)",
3824 type->tp_name,
3825 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003826 return NULL;
3827 }
3828 subtype = (PyTypeObject *)arg0;
3829 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003830 PyErr_Format(PyExc_TypeError,
3831 "%s.__new__(%s): %s is not a subtype of %s",
3832 type->tp_name,
3833 subtype->tp_name,
3834 subtype->tp_name,
3835 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003836 return NULL;
3837 }
Barry Warsaw60f01882001-08-22 19:24:42 +00003838
3839 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00003840 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00003841 most derived base that's not a heap type is this type. */
3842 staticbase = subtype;
3843 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
3844 staticbase = staticbase->tp_base;
Guido van Rossuma8c60f42001-09-14 19:43:36 +00003845 if (staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003846 PyErr_Format(PyExc_TypeError,
3847 "%s.__new__(%s) is not safe, use %s.__new__()",
3848 type->tp_name,
3849 subtype->tp_name,
3850 staticbase == NULL ? "?" : staticbase->tp_name);
3851 return NULL;
3852 }
3853
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003854 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
3855 if (args == NULL)
3856 return NULL;
3857 res = type->tp_new(subtype, args, kwds);
3858 Py_DECREF(args);
3859 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003860}
3861
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003862static struct PyMethodDef tp_new_methoddef[] = {
3863 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00003864 PyDoc_STR("T.__new__(S, ...) -> "
3865 "a new object with type S, a subtype of T")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00003866 {0}
3867};
3868
3869static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003870add_tp_new_wrapper(PyTypeObject *type)
3871{
Guido van Rossumf040ede2001-08-07 16:40:56 +00003872 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003873
Guido van Rossum687ae002001-10-15 22:03:32 +00003874 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00003875 return 0;
3876 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003877 if (func == NULL)
3878 return -1;
Guido van Rossum687ae002001-10-15 22:03:32 +00003879 return PyDict_SetItemString(type->tp_dict, "__new__", func);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003880}
3881
Guido van Rossumf040ede2001-08-07 16:40:56 +00003882/* Slot wrappers that call the corresponding __foo__ slot. See comments
3883 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003884
Guido van Rossumdc91b992001-08-08 22:26:22 +00003885#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003886static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003887FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003888{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00003889 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003890 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003891}
3892
Guido van Rossumdc91b992001-08-08 22:26:22 +00003893#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003894static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003895FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003896{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003897 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003898 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003899}
3900
Guido van Rossumcd118802003-01-06 22:57:47 +00003901/* Boolean helper for SLOT1BINFULL().
3902 right.__class__ is a nontrivial subclass of left.__class__. */
3903static int
3904method_is_overloaded(PyObject *left, PyObject *right, char *name)
3905{
3906 PyObject *a, *b;
3907 int ok;
3908
3909 b = PyObject_GetAttrString((PyObject *)(right->ob_type), name);
3910 if (b == NULL) {
3911 PyErr_Clear();
3912 /* If right doesn't have it, it's not overloaded */
3913 return 0;
3914 }
3915
3916 a = PyObject_GetAttrString((PyObject *)(left->ob_type), name);
3917 if (a == NULL) {
3918 PyErr_Clear();
3919 Py_DECREF(b);
3920 /* If right has it but left doesn't, it's overloaded */
3921 return 1;
3922 }
3923
3924 ok = PyObject_RichCompareBool(a, b, Py_NE);
3925 Py_DECREF(a);
3926 Py_DECREF(b);
3927 if (ok < 0) {
3928 PyErr_Clear();
3929 return 0;
3930 }
3931
3932 return ok;
3933}
3934
Guido van Rossumdc91b992001-08-08 22:26:22 +00003935
3936#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003937static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003938FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003939{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003940 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00003941 int do_other = self->ob_type != other->ob_type && \
3942 other->ob_type->tp_as_number != NULL && \
3943 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003944 if (self->ob_type->tp_as_number != NULL && \
3945 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
3946 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00003947 if (do_other && \
Guido van Rossumcd118802003-01-06 22:57:47 +00003948 PyType_IsSubtype(other->ob_type, self->ob_type) && \
3949 method_is_overloaded(self, other, ROPSTR)) { \
Guido van Rossum55f20992001-10-01 17:18:22 +00003950 r = call_maybe( \
3951 other, ROPSTR, &rcache_str, "(O)", self); \
3952 if (r != Py_NotImplemented) \
3953 return r; \
3954 Py_DECREF(r); \
3955 do_other = 0; \
3956 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00003957 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00003958 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003959 if (r != Py_NotImplemented || \
3960 other->ob_type == self->ob_type) \
3961 return r; \
3962 Py_DECREF(r); \
3963 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00003964 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00003965 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00003966 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003967 } \
3968 Py_INCREF(Py_NotImplemented); \
3969 return Py_NotImplemented; \
3970}
3971
3972#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
3973 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
3974
3975#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
3976static PyObject * \
3977FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
3978{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003979 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003980 return call_method(self, OPSTR, &cache_str, \
3981 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003982}
3983
3984static int
3985slot_sq_length(PyObject *self)
3986{
Guido van Rossum2730b132001-08-28 18:22:14 +00003987 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00003988 PyObject *res = call_method(self, "__len__", &len_str, "()");
Guido van Rossum26111622001-10-01 16:42:49 +00003989 int len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003990
3991 if (res == NULL)
3992 return -1;
Guido van Rossum26111622001-10-01 16:42:49 +00003993 len = (int)PyInt_AsLong(res);
3994 Py_DECREF(res);
Jeremy Hylton73a088e2002-07-25 16:43:29 +00003995 if (len == -1 && PyErr_Occurred())
3996 return -1;
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00003997 if (len < 0) {
Guido van Rossum22b13872002-08-06 21:41:44 +00003998 PyErr_SetString(PyExc_ValueError,
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00003999 "__len__() should return >= 0");
4000 return -1;
4001 }
Guido van Rossum26111622001-10-01 16:42:49 +00004002 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004003}
4004
Guido van Rossumdc91b992001-08-08 22:26:22 +00004005SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
4006SLOT1(slot_sq_repeat, "__mul__", int, "i")
Guido van Rossumf4593e02001-10-03 12:09:30 +00004007
4008/* Super-optimized version of slot_sq_item.
4009 Other slots could do the same... */
4010static PyObject *
4011slot_sq_item(PyObject *self, int i)
4012{
4013 static PyObject *getitem_str;
4014 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
4015 descrgetfunc f;
4016
4017 if (getitem_str == NULL) {
4018 getitem_str = PyString_InternFromString("__getitem__");
4019 if (getitem_str == NULL)
4020 return NULL;
4021 }
4022 func = _PyType_Lookup(self->ob_type, getitem_str);
4023 if (func != NULL) {
Guido van Rossumf4593e02001-10-03 12:09:30 +00004024 if ((f = func->ob_type->tp_descr_get) == NULL)
4025 Py_INCREF(func);
Neal Norwitz673cd822002-10-18 16:33:13 +00004026 else {
Guido van Rossumf4593e02001-10-03 12:09:30 +00004027 func = f(func, self, (PyObject *)(self->ob_type));
Neal Norwitz673cd822002-10-18 16:33:13 +00004028 if (func == NULL) {
4029 return NULL;
4030 }
4031 }
Guido van Rossumf4593e02001-10-03 12:09:30 +00004032 ival = PyInt_FromLong(i);
4033 if (ival != NULL) {
4034 args = PyTuple_New(1);
4035 if (args != NULL) {
4036 PyTuple_SET_ITEM(args, 0, ival);
4037 retval = PyObject_Call(func, args, NULL);
4038 Py_XDECREF(args);
4039 Py_XDECREF(func);
4040 return retval;
4041 }
4042 }
4043 }
4044 else {
4045 PyErr_SetObject(PyExc_AttributeError, getitem_str);
4046 }
4047 Py_XDECREF(args);
4048 Py_XDECREF(ival);
4049 Py_XDECREF(func);
4050 return NULL;
4051}
4052
Guido van Rossumdc91b992001-08-08 22:26:22 +00004053SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004054
4055static int
4056slot_sq_ass_item(PyObject *self, int index, PyObject *value)
4057{
4058 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004059 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004060
4061 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004062 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004063 "(i)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004064 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004065 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004066 "(iO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004067 if (res == NULL)
4068 return -1;
4069 Py_DECREF(res);
4070 return 0;
4071}
4072
4073static int
4074slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
4075{
4076 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004077 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004078
4079 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004080 res = call_method(self, "__delslice__", &delslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004081 "(ii)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004082 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004083 res = call_method(self, "__setslice__", &setslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004084 "(iiO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004085 if (res == NULL)
4086 return -1;
4087 Py_DECREF(res);
4088 return 0;
4089}
4090
4091static int
4092slot_sq_contains(PyObject *self, PyObject *value)
4093{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004094 PyObject *func, *res, *args;
Tim Petersbf9b2442003-03-23 05:35:36 +00004095 int result = -1;
4096
Guido van Rossum60718732001-08-28 17:47:51 +00004097 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004098
Guido van Rossum55f20992001-10-01 17:18:22 +00004099 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004100 if (func != NULL) {
4101 args = Py_BuildValue("(O)", value);
4102 if (args == NULL)
4103 res = NULL;
4104 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004105 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004106 Py_DECREF(args);
4107 }
4108 Py_DECREF(func);
Tim Petersbf9b2442003-03-23 05:35:36 +00004109 if (res != NULL) {
4110 result = PyObject_IsTrue(res);
4111 Py_DECREF(res);
4112 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004113 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004114 else if (! PyErr_Occurred()) {
4115 result = _PySequence_IterSearch(self, value,
4116 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004117 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004118 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004119}
4120
Guido van Rossumdc91b992001-08-08 22:26:22 +00004121SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
4122SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004123
4124#define slot_mp_length slot_sq_length
4125
Guido van Rossumdc91b992001-08-08 22:26:22 +00004126SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004127
4128static int
4129slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
4130{
4131 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004132 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004133
4134 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004135 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004136 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004137 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004138 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004139 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004140 if (res == NULL)
4141 return -1;
4142 Py_DECREF(res);
4143 return 0;
4144}
4145
Guido van Rossumdc91b992001-08-08 22:26:22 +00004146SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
4147SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
4148SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
4149SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
4150SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
4151SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
4152
Jeremy Hylton938ace62002-07-17 16:30:39 +00004153static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00004154
4155SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
4156 nb_power, "__pow__", "__rpow__")
4157
4158static PyObject *
4159slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
4160{
Guido van Rossum2730b132001-08-28 18:22:14 +00004161 static PyObject *pow_str;
4162
Guido van Rossumdc91b992001-08-08 22:26:22 +00004163 if (modulus == Py_None)
4164 return slot_nb_power_binary(self, other);
Guido van Rossum23094982002-06-10 14:30:43 +00004165 /* Three-arg power doesn't use __rpow__. But ternary_op
4166 can call this when the second argument's type uses
4167 slot_nb_power, so check before calling self.__pow__. */
4168 if (self->ob_type->tp_as_number != NULL &&
4169 self->ob_type->tp_as_number->nb_power == slot_nb_power) {
4170 return call_method(self, "__pow__", &pow_str,
4171 "(OO)", other, modulus);
4172 }
4173 Py_INCREF(Py_NotImplemented);
4174 return Py_NotImplemented;
Guido van Rossumdc91b992001-08-08 22:26:22 +00004175}
4176
4177SLOT0(slot_nb_negative, "__neg__")
4178SLOT0(slot_nb_positive, "__pos__")
4179SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004180
4181static int
4182slot_nb_nonzero(PyObject *self)
4183{
Tim Petersea7f75d2002-12-07 21:39:16 +00004184 PyObject *func, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00004185 static PyObject *nonzero_str, *len_str;
Tim Petersea7f75d2002-12-07 21:39:16 +00004186 int result = -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004187
Guido van Rossum55f20992001-10-01 17:18:22 +00004188 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004189 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00004190 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00004191 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00004192 func = lookup_maybe(self, "__len__", &len_str);
Tim Petersea7f75d2002-12-07 21:39:16 +00004193 if (func == NULL)
4194 return PyErr_Occurred() ? -1 : 1;
4195 }
4196 args = PyTuple_New(0);
4197 if (args != NULL) {
4198 PyObject *temp = PyObject_Call(func, args, NULL);
4199 Py_DECREF(args);
4200 if (temp != NULL) {
Jeremy Hylton3e3159c2003-06-27 17:38:27 +00004201 if (PyInt_CheckExact(temp) || PyBool_Check(temp))
Jeremy Hylton090a3492003-06-27 16:46:45 +00004202 result = PyObject_IsTrue(temp);
4203 else {
4204 PyErr_Format(PyExc_TypeError,
4205 "__nonzero__ should return "
4206 "bool or int, returned %s",
4207 temp->ob_type->tp_name);
Jeremy Hylton3e3159c2003-06-27 17:38:27 +00004208 result = -1;
Jeremy Hylton090a3492003-06-27 16:46:45 +00004209 }
Tim Petersea7f75d2002-12-07 21:39:16 +00004210 Py_DECREF(temp);
Guido van Rossum55f20992001-10-01 17:18:22 +00004211 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004212 }
Guido van Rossum55f20992001-10-01 17:18:22 +00004213 Py_DECREF(func);
Tim Petersea7f75d2002-12-07 21:39:16 +00004214 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004215}
4216
Guido van Rossumdc91b992001-08-08 22:26:22 +00004217SLOT0(slot_nb_invert, "__invert__")
4218SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
4219SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
4220SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
4221SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
4222SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004223
4224static int
4225slot_nb_coerce(PyObject **a, PyObject **b)
4226{
4227 static PyObject *coerce_str;
4228 PyObject *self = *a, *other = *b;
4229
4230 if (self->ob_type->tp_as_number != NULL &&
4231 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
4232 PyObject *r;
4233 r = call_maybe(
4234 self, "__coerce__", &coerce_str, "(O)", other);
4235 if (r == NULL)
4236 return -1;
4237 if (r == Py_NotImplemented) {
4238 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004239 }
Guido van Rossum55f20992001-10-01 17:18:22 +00004240 else {
4241 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
4242 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004243 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00004244 Py_DECREF(r);
4245 return -1;
4246 }
4247 *a = PyTuple_GET_ITEM(r, 0);
4248 Py_INCREF(*a);
4249 *b = PyTuple_GET_ITEM(r, 1);
4250 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004251 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00004252 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004253 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004254 }
4255 if (other->ob_type->tp_as_number != NULL &&
4256 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
4257 PyObject *r;
4258 r = call_maybe(
4259 other, "__coerce__", &coerce_str, "(O)", self);
4260 if (r == NULL)
4261 return -1;
4262 if (r == Py_NotImplemented) {
4263 Py_DECREF(r);
4264 return 1;
4265 }
4266 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
4267 PyErr_SetString(PyExc_TypeError,
4268 "__coerce__ didn't return a 2-tuple");
4269 Py_DECREF(r);
4270 return -1;
4271 }
4272 *a = PyTuple_GET_ITEM(r, 1);
4273 Py_INCREF(*a);
4274 *b = PyTuple_GET_ITEM(r, 0);
4275 Py_INCREF(*b);
4276 Py_DECREF(r);
4277 return 0;
4278 }
4279 return 1;
4280}
4281
Guido van Rossumdc91b992001-08-08 22:26:22 +00004282SLOT0(slot_nb_int, "__int__")
4283SLOT0(slot_nb_long, "__long__")
4284SLOT0(slot_nb_float, "__float__")
4285SLOT0(slot_nb_oct, "__oct__")
4286SLOT0(slot_nb_hex, "__hex__")
4287SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
4288SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
4289SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
4290SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
4291SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Guido van Rossum6e5680f2002-10-15 01:01:53 +00004292SLOT1(slot_nb_inplace_power, "__ipow__", PyObject *, "O")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004293SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
4294SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
4295SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
4296SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
4297SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
4298SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
4299 "__floordiv__", "__rfloordiv__")
4300SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
4301SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
4302SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004303
4304static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00004305half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004306{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004307 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004308 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004309 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004310
Guido van Rossum60718732001-08-28 17:47:51 +00004311 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004312 if (func == NULL) {
4313 PyErr_Clear();
4314 }
4315 else {
4316 args = Py_BuildValue("(O)", other);
4317 if (args == NULL)
4318 res = NULL;
4319 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004320 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004321 Py_DECREF(args);
4322 }
Raymond Hettingerab5dae32002-06-24 13:08:16 +00004323 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004324 if (res != Py_NotImplemented) {
4325 if (res == NULL)
4326 return -2;
4327 c = PyInt_AsLong(res);
4328 Py_DECREF(res);
4329 if (c == -1 && PyErr_Occurred())
4330 return -2;
4331 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
4332 }
4333 Py_DECREF(res);
4334 }
4335 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004336}
4337
Guido van Rossumab3b0342001-09-18 20:38:53 +00004338/* This slot is published for the benefit of try_3way_compare in object.c */
4339int
4340_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00004341{
4342 int c;
4343
Guido van Rossumab3b0342001-09-18 20:38:53 +00004344 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004345 c = half_compare(self, other);
4346 if (c <= 1)
4347 return c;
4348 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00004349 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004350 c = half_compare(other, self);
4351 if (c < -1)
4352 return -2;
4353 if (c <= 1)
4354 return -c;
4355 }
4356 return (void *)self < (void *)other ? -1 :
4357 (void *)self > (void *)other ? 1 : 0;
4358}
4359
4360static PyObject *
4361slot_tp_repr(PyObject *self)
4362{
4363 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004364 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004365
Guido van Rossum60718732001-08-28 17:47:51 +00004366 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004367 if (func != NULL) {
4368 res = PyEval_CallObject(func, NULL);
4369 Py_DECREF(func);
4370 return res;
4371 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00004372 PyErr_Clear();
4373 return PyString_FromFormat("<%s object at %p>",
4374 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004375}
4376
4377static PyObject *
4378slot_tp_str(PyObject *self)
4379{
4380 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004381 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004382
Guido van Rossum60718732001-08-28 17:47:51 +00004383 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004384 if (func != NULL) {
4385 res = PyEval_CallObject(func, NULL);
4386 Py_DECREF(func);
4387 return res;
4388 }
4389 else {
4390 PyErr_Clear();
4391 return slot_tp_repr(self);
4392 }
4393}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004394
4395static long
4396slot_tp_hash(PyObject *self)
4397{
Tim Peters61ce0a92002-12-06 23:38:02 +00004398 PyObject *func;
Guido van Rossum60718732001-08-28 17:47:51 +00004399 static PyObject *hash_str, *eq_str, *cmp_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004400 long h;
4401
Guido van Rossum60718732001-08-28 17:47:51 +00004402 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004403
4404 if (func != NULL) {
Tim Peters61ce0a92002-12-06 23:38:02 +00004405 PyObject *res = PyEval_CallObject(func, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004406 Py_DECREF(func);
4407 if (res == NULL)
4408 return -1;
4409 h = PyInt_AsLong(res);
Tim Peters61ce0a92002-12-06 23:38:02 +00004410 Py_DECREF(res);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004411 }
4412 else {
4413 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004414 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004415 if (func == NULL) {
4416 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004417 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004418 }
4419 if (func != NULL) {
4420 Py_DECREF(func);
4421 PyErr_SetString(PyExc_TypeError, "unhashable type");
4422 return -1;
4423 }
4424 PyErr_Clear();
4425 h = _Py_HashPointer((void *)self);
4426 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004427 if (h == -1 && !PyErr_Occurred())
4428 h = -2;
4429 return h;
4430}
4431
4432static PyObject *
4433slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
4434{
Guido van Rossum60718732001-08-28 17:47:51 +00004435 static PyObject *call_str;
4436 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004437 PyObject *res;
4438
4439 if (meth == NULL)
4440 return NULL;
4441 res = PyObject_Call(meth, args, kwds);
4442 Py_DECREF(meth);
4443 return res;
4444}
4445
Guido van Rossum14a6f832001-10-17 13:59:09 +00004446/* There are two slot dispatch functions for tp_getattro.
4447
4448 - slot_tp_getattro() is used when __getattribute__ is overridden
4449 but no __getattr__ hook is present;
4450
4451 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
4452
Guido van Rossumc334df52002-04-04 23:44:47 +00004453 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
4454 detects the absence of __getattr__ and then installs the simpler slot if
4455 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00004456
Tim Peters6d6c1a32001-08-02 04:15:00 +00004457static PyObject *
4458slot_tp_getattro(PyObject *self, PyObject *name)
4459{
Guido van Rossum14a6f832001-10-17 13:59:09 +00004460 static PyObject *getattribute_str = NULL;
4461 return call_method(self, "__getattribute__", &getattribute_str,
4462 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004463}
4464
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004465static PyObject *
4466slot_tp_getattr_hook(PyObject *self, PyObject *name)
4467{
4468 PyTypeObject *tp = self->ob_type;
4469 PyObject *getattr, *getattribute, *res;
4470 static PyObject *getattribute_str = NULL;
4471 static PyObject *getattr_str = NULL;
4472
4473 if (getattr_str == NULL) {
4474 getattr_str = PyString_InternFromString("__getattr__");
4475 if (getattr_str == NULL)
4476 return NULL;
4477 }
4478 if (getattribute_str == NULL) {
4479 getattribute_str =
4480 PyString_InternFromString("__getattribute__");
4481 if (getattribute_str == NULL)
4482 return NULL;
4483 }
4484 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004485 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004486 /* No __getattr__ hook: use a simpler dispatcher */
4487 tp->tp_getattro = slot_tp_getattro;
4488 return slot_tp_getattro(self, name);
4489 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004490 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004491 if (getattribute == NULL ||
4492 (getattribute->ob_type == &PyWrapperDescr_Type &&
4493 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
4494 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004495 res = PyObject_GenericGetAttr(self, name);
4496 else
4497 res = PyObject_CallFunction(getattribute, "OO", self, name);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004498 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004499 PyErr_Clear();
4500 res = PyObject_CallFunction(getattr, "OO", self, name);
4501 }
4502 return res;
4503}
4504
Tim Peters6d6c1a32001-08-02 04:15:00 +00004505static int
4506slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
4507{
4508 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004509 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004510
4511 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004512 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004513 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004514 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004515 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004516 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004517 if (res == NULL)
4518 return -1;
4519 Py_DECREF(res);
4520 return 0;
4521}
4522
4523/* Map rich comparison operators to their __xx__ namesakes */
4524static char *name_op[] = {
4525 "__lt__",
4526 "__le__",
4527 "__eq__",
4528 "__ne__",
4529 "__gt__",
4530 "__ge__",
4531};
4532
4533static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00004534half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004535{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004536 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004537 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00004538
Guido van Rossum60718732001-08-28 17:47:51 +00004539 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004540 if (func == NULL) {
4541 PyErr_Clear();
4542 Py_INCREF(Py_NotImplemented);
4543 return Py_NotImplemented;
4544 }
4545 args = Py_BuildValue("(O)", other);
4546 if (args == NULL)
4547 res = NULL;
4548 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004549 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004550 Py_DECREF(args);
4551 }
4552 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004553 return res;
4554}
4555
Guido van Rossumb8f63662001-08-15 23:57:02 +00004556/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
4557static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
4558
4559static PyObject *
4560slot_tp_richcompare(PyObject *self, PyObject *other, int op)
4561{
4562 PyObject *res;
4563
4564 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
4565 res = half_richcompare(self, other, op);
4566 if (res != Py_NotImplemented)
4567 return res;
4568 Py_DECREF(res);
4569 }
4570 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
4571 res = half_richcompare(other, self, swapped_op[op]);
4572 if (res != Py_NotImplemented) {
4573 return res;
4574 }
4575 Py_DECREF(res);
4576 }
4577 Py_INCREF(Py_NotImplemented);
4578 return Py_NotImplemented;
4579}
4580
4581static PyObject *
4582slot_tp_iter(PyObject *self)
4583{
4584 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004585 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004586
Guido van Rossum60718732001-08-28 17:47:51 +00004587 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004588 if (func != NULL) {
Guido van Rossum84b2bed2002-08-16 17:01:09 +00004589 PyObject *args;
4590 args = res = PyTuple_New(0);
4591 if (args != NULL) {
4592 res = PyObject_Call(func, args, NULL);
4593 Py_DECREF(args);
4594 }
4595 Py_DECREF(func);
4596 return res;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004597 }
4598 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004599 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004600 if (func == NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00004601 PyErr_SetString(PyExc_TypeError,
4602 "iteration over non-sequence");
Guido van Rossumb8f63662001-08-15 23:57:02 +00004603 return NULL;
4604 }
4605 Py_DECREF(func);
4606 return PySeqIter_New(self);
4607}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004608
4609static PyObject *
4610slot_tp_iternext(PyObject *self)
4611{
Guido van Rossum2730b132001-08-28 18:22:14 +00004612 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00004613 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004614}
4615
Guido van Rossum1a493502001-08-17 16:47:50 +00004616static PyObject *
4617slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4618{
4619 PyTypeObject *tp = self->ob_type;
4620 PyObject *get;
4621 static PyObject *get_str = NULL;
4622
4623 if (get_str == NULL) {
4624 get_str = PyString_InternFromString("__get__");
4625 if (get_str == NULL)
4626 return NULL;
4627 }
4628 get = _PyType_Lookup(tp, get_str);
4629 if (get == NULL) {
4630 /* Avoid further slowdowns */
4631 if (tp->tp_descr_get == slot_tp_descr_get)
4632 tp->tp_descr_get = NULL;
4633 Py_INCREF(self);
4634 return self;
4635 }
Guido van Rossum2c252392001-08-24 10:13:31 +00004636 if (obj == NULL)
4637 obj = Py_None;
4638 if (type == NULL)
4639 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00004640 return PyObject_CallFunction(get, "OOO", self, obj, type);
4641}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004642
4643static int
4644slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
4645{
Guido van Rossum2c252392001-08-24 10:13:31 +00004646 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004647 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00004648
4649 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00004650 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004651 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00004652 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004653 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004654 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004655 if (res == NULL)
4656 return -1;
4657 Py_DECREF(res);
4658 return 0;
4659}
4660
4661static int
4662slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
4663{
Guido van Rossum60718732001-08-28 17:47:51 +00004664 static PyObject *init_str;
4665 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004666 PyObject *res;
4667
4668 if (meth == NULL)
4669 return -1;
4670 res = PyObject_Call(meth, args, kwds);
4671 Py_DECREF(meth);
4672 if (res == NULL)
4673 return -1;
4674 Py_DECREF(res);
4675 return 0;
4676}
4677
4678static PyObject *
4679slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4680{
Guido van Rossum7bed2132002-08-08 21:57:53 +00004681 static PyObject *new_str;
4682 PyObject *func;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004683 PyObject *newargs, *x;
4684 int i, n;
4685
Guido van Rossum7bed2132002-08-08 21:57:53 +00004686 if (new_str == NULL) {
4687 new_str = PyString_InternFromString("__new__");
4688 if (new_str == NULL)
4689 return NULL;
4690 }
4691 func = PyObject_GetAttr((PyObject *)type, new_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004692 if (func == NULL)
4693 return NULL;
4694 assert(PyTuple_Check(args));
4695 n = PyTuple_GET_SIZE(args);
4696 newargs = PyTuple_New(n+1);
4697 if (newargs == NULL)
4698 return NULL;
4699 Py_INCREF(type);
4700 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
4701 for (i = 0; i < n; i++) {
4702 x = PyTuple_GET_ITEM(args, i);
4703 Py_INCREF(x);
4704 PyTuple_SET_ITEM(newargs, i+1, x);
4705 }
4706 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00004707 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004708 Py_DECREF(func);
4709 return x;
4710}
4711
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004712static void
4713slot_tp_del(PyObject *self)
4714{
4715 static PyObject *del_str = NULL;
4716 PyObject *del, *res;
4717 PyObject *error_type, *error_value, *error_traceback;
4718
4719 /* Temporarily resurrect the object. */
4720 assert(self->ob_refcnt == 0);
4721 self->ob_refcnt = 1;
4722
4723 /* Save the current exception, if any. */
4724 PyErr_Fetch(&error_type, &error_value, &error_traceback);
4725
4726 /* Execute __del__ method, if any. */
4727 del = lookup_maybe(self, "__del__", &del_str);
4728 if (del != NULL) {
4729 res = PyEval_CallObject(del, NULL);
4730 if (res == NULL)
4731 PyErr_WriteUnraisable(del);
4732 else
4733 Py_DECREF(res);
4734 Py_DECREF(del);
4735 }
4736
4737 /* Restore the saved exception. */
4738 PyErr_Restore(error_type, error_value, error_traceback);
4739
4740 /* Undo the temporary resurrection; can't use DECREF here, it would
4741 * cause a recursive call.
4742 */
4743 assert(self->ob_refcnt > 0);
4744 if (--self->ob_refcnt == 0)
4745 return; /* this is the normal path out */
4746
4747 /* __del__ resurrected it! Make it look like the original Py_DECREF
4748 * never happened.
4749 */
4750 {
4751 int refcnt = self->ob_refcnt;
4752 _Py_NewReference(self);
4753 self->ob_refcnt = refcnt;
4754 }
4755 assert(!PyType_IS_GC(self->ob_type) ||
4756 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
4757 /* If Py_REF_DEBUG, the original decref dropped _Py_RefTotal, but
4758 * _Py_NewReference bumped it again, so that's a wash.
4759 * If Py_TRACE_REFS, _Py_NewReference re-added self to the object
4760 * chain, so no more to do there either.
4761 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
4762 * _Py_NewReference bumped tp_allocs: both of those need to be
4763 * undone.
4764 */
4765#ifdef COUNT_ALLOCS
4766 --self->ob_type->tp_frees;
4767 --self->ob_type->tp_allocs;
4768#endif
4769}
4770
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004771
4772/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
Tim Petersbf9b2442003-03-23 05:35:36 +00004773 functions. The offsets here are relative to the 'PyHeapTypeObject'
Guido van Rossume5c691a2003-03-07 15:13:17 +00004774 structure, which incorporates the additional structures used for numbers,
4775 sequences and mappings.
4776 Note that multiple names may map to the same slot (e.g. __eq__,
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004777 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00004778 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
4779 terminated with an all-zero entry. (This table is further initialized and
4780 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004781
Guido van Rossum6d204072001-10-21 00:44:31 +00004782typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004783
4784#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00004785#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004786#undef ETSLOT
4787#undef SQSLOT
4788#undef MPSLOT
4789#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00004790#undef UNSLOT
4791#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004792#undef BINSLOT
4793#undef RBINSLOT
4794
Guido van Rossum6d204072001-10-21 00:44:31 +00004795#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004796 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
4797 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00004798#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
4799 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004800 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00004801#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Guido van Rossume5c691a2003-03-07 15:13:17 +00004802 {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004803 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00004804#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4805 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
4806#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4807 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
4808#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4809 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
4810#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4811 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
4812 "x." NAME "() <==> " DOC)
4813#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4814 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
4815 "x." NAME "(y) <==> x" DOC "y")
4816#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
4817 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
4818 "x." NAME "(y) <==> x" DOC "y")
4819#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
4820 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
4821 "x." NAME "(y) <==> y" DOC "x")
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004822
4823static slotdef slotdefs[] = {
Guido van Rossum6d204072001-10-21 00:44:31 +00004824 SQSLOT("__len__", sq_length, slot_sq_length, wrap_inquiry,
4825 "x.__len__() <==> len(x)"),
4826 SQSLOT("__add__", sq_concat, slot_sq_concat, wrap_binaryfunc,
4827 "x.__add__(y) <==> x+y"),
4828 SQSLOT("__mul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
4829 "x.__mul__(n) <==> x*n"),
4830 SQSLOT("__rmul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
4831 "x.__rmul__(n) <==> n*x"),
4832 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
4833 "x.__getitem__(y) <==> x[y]"),
4834 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_intintargfunc,
Brett Cannon154da9b2003-05-20 02:30:04 +00004835 "x.__getslice__(i, j) <==> x[i:j]\n\
4836 \n\
4837 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00004838 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
Brett Cannonbe67d872003-05-20 02:40:12 +00004839 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum6d204072001-10-21 00:44:31 +00004840 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
Brett Cannonbe67d872003-05-20 02:40:12 +00004841 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004842 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Guido van Rossum6d204072001-10-21 00:44:31 +00004843 wrap_intintobjargproc,
Brett Cannonbe67d872003-05-20 02:40:12 +00004844 "x.__setslice__(i, j, y) <==> x[i:j]=y\n\
4845 \n\
4846 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00004847 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
Brett Cannonbe67d872003-05-20 02:40:12 +00004848 "x.__delslice__(i, j) <==> del x[i:j]\n\
4849 \n\
4850 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00004851 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
4852 "x.__contains__(y) <==> y in x"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004853 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat,
Guido van Rossum6d204072001-10-21 00:44:31 +00004854 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004855 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat,
Guido van Rossum6d204072001-10-21 00:44:31 +00004856 wrap_intargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004857
Guido van Rossum6d204072001-10-21 00:44:31 +00004858 MPSLOT("__len__", mp_length, slot_mp_length, wrap_inquiry,
4859 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00004860 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004861 wrap_binaryfunc,
4862 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004863 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004864 wrap_objobjargproc,
4865 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004866 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004867 wrap_delitem,
4868 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004869
Guido van Rossum6d204072001-10-21 00:44:31 +00004870 BINSLOT("__add__", nb_add, slot_nb_add,
4871 "+"),
4872 RBINSLOT("__radd__", nb_add, slot_nb_add,
4873 "+"),
4874 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
4875 "-"),
4876 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
4877 "-"),
4878 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
4879 "*"),
4880 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
4881 "*"),
4882 BINSLOT("__div__", nb_divide, slot_nb_divide,
4883 "/"),
4884 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
4885 "/"),
4886 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
4887 "%"),
4888 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
4889 "%"),
4890 BINSLOT("__divmod__", nb_divmod, slot_nb_divmod,
4891 "divmod(x, y)"),
4892 RBINSLOT("__rdivmod__", nb_divmod, slot_nb_divmod,
4893 "divmod(y, x)"),
4894 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
4895 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
4896 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
4897 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
4898 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
4899 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
4900 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
4901 "abs(x)"),
Guido van Rossumdfce3bf2002-03-10 14:11:16 +00004902 UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquiry,
Guido van Rossum6d204072001-10-21 00:44:31 +00004903 "x != 0"),
4904 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
4905 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
4906 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
4907 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
4908 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
4909 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
4910 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
4911 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
4912 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
4913 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
4914 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
4915 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
4916 "x.__coerce__(y) <==> coerce(x, y)"),
4917 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
4918 "int(x)"),
4919 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
4920 "long(x)"),
4921 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
4922 "float(x)"),
4923 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
4924 "oct(x)"),
4925 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
4926 "hex(x)"),
4927 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
4928 wrap_binaryfunc, "+"),
4929 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
4930 wrap_binaryfunc, "-"),
4931 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
4932 wrap_binaryfunc, "*"),
4933 IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
4934 wrap_binaryfunc, "/"),
4935 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
4936 wrap_binaryfunc, "%"),
4937 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
Guido van Rossum6e5680f2002-10-15 01:01:53 +00004938 wrap_binaryfunc, "**"),
Guido van Rossum6d204072001-10-21 00:44:31 +00004939 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
4940 wrap_binaryfunc, "<<"),
4941 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
4942 wrap_binaryfunc, ">>"),
4943 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
4944 wrap_binaryfunc, "&"),
4945 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
4946 wrap_binaryfunc, "^"),
4947 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
4948 wrap_binaryfunc, "|"),
4949 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
4950 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
4951 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
4952 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
4953 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
4954 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
4955 IBSLOT("__itruediv__", nb_inplace_true_divide,
4956 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004957
Guido van Rossum6d204072001-10-21 00:44:31 +00004958 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
4959 "x.__str__() <==> str(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00004960 TPSLOT("__str__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00004961 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
4962 "x.__repr__() <==> repr(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00004963 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00004964 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
4965 "x.__cmp__(y) <==> cmp(x,y)"),
4966 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
4967 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00004968 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
4969 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004970 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00004971 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
4972 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
4973 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
4974 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
4975 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
4976 "x.__setattr__('name', value) <==> x.name = value"),
4977 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
4978 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
4979 "x.__delattr__('name') <==> del x.name"),
4980 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
4981 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
4982 "x.__lt__(y) <==> x<y"),
4983 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
4984 "x.__le__(y) <==> x<=y"),
4985 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
4986 "x.__eq__(y) <==> x==y"),
4987 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
4988 "x.__ne__(y) <==> x!=y"),
4989 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
4990 "x.__gt__(y) <==> x>y"),
4991 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
4992 "x.__ge__(y) <==> x>=y"),
4993 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
4994 "x.__iter__() <==> iter(x)"),
4995 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
4996 "x.next() -> the next value, or raise StopIteration"),
4997 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
4998 "descr.__get__(obj[, type]) -> value"),
4999 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
5000 "descr.__set__(obj, value)"),
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00005001 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
5002 wrap_descr_delete, "descr.__delete__(obj)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00005003 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00005004 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00005005 "see x.__class__.__doc__ for signature",
5006 PyWrapperFlag_KEYWORDS),
5007 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005008 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005009 {NULL}
5010};
5011
Guido van Rossumc334df52002-04-04 23:44:47 +00005012/* Given a type pointer and an offset gotten from a slotdef entry, return a
5013 pointer to the actual slot. This is not quite the same as simply adding
5014 the offset to the type pointer, since it takes care to indirect through the
5015 proper indirection pointer (as_buffer, etc.); it returns NULL if the
5016 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005017static void **
5018slotptr(PyTypeObject *type, int offset)
5019{
5020 char *ptr;
5021
Guido van Rossume5c691a2003-03-07 15:13:17 +00005022 /* Note: this depends on the order of the members of PyHeapTypeObject! */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005023 assert(offset >= 0);
Guido van Rossume5c691a2003-03-07 15:13:17 +00005024 assert(offset < offsetof(PyHeapTypeObject, as_buffer));
5025 if (offset >= offsetof(PyHeapTypeObject, as_sequence)) {
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005026 ptr = (void *)type->tp_as_sequence;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005027 offset -= offsetof(PyHeapTypeObject, as_sequence);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005028 }
Guido van Rossume5c691a2003-03-07 15:13:17 +00005029 else if (offset >= offsetof(PyHeapTypeObject, as_mapping)) {
Guido van Rossum09638c12002-06-13 19:17:46 +00005030 ptr = (void *)type->tp_as_mapping;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005031 offset -= offsetof(PyHeapTypeObject, as_mapping);
Guido van Rossum09638c12002-06-13 19:17:46 +00005032 }
Guido van Rossume5c691a2003-03-07 15:13:17 +00005033 else if (offset >= offsetof(PyHeapTypeObject, as_number)) {
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005034 ptr = (void *)type->tp_as_number;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005035 offset -= offsetof(PyHeapTypeObject, as_number);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005036 }
5037 else {
5038 ptr = (void *)type;
5039 }
5040 if (ptr != NULL)
5041 ptr += offset;
5042 return (void **)ptr;
5043}
Guido van Rossumf040ede2001-08-07 16:40:56 +00005044
Guido van Rossumc334df52002-04-04 23:44:47 +00005045/* Length of array of slotdef pointers used to store slots with the
5046 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
5047 the same __name__, for any __name__. Since that's a static property, it is
5048 appropriate to declare fixed-size arrays for this. */
5049#define MAX_EQUIV 10
5050
5051/* Return a slot pointer for a given name, but ONLY if the attribute has
5052 exactly one slot function. The name must be an interned string. */
5053static void **
5054resolve_slotdups(PyTypeObject *type, PyObject *name)
5055{
5056 /* XXX Maybe this could be optimized more -- but is it worth it? */
5057
5058 /* pname and ptrs act as a little cache */
5059 static PyObject *pname;
5060 static slotdef *ptrs[MAX_EQUIV];
5061 slotdef *p, **pp;
5062 void **res, **ptr;
5063
5064 if (pname != name) {
5065 /* Collect all slotdefs that match name into ptrs. */
5066 pname = name;
5067 pp = ptrs;
5068 for (p = slotdefs; p->name_strobj; p++) {
5069 if (p->name_strobj == name)
5070 *pp++ = p;
5071 }
5072 *pp = NULL;
5073 }
5074
5075 /* Look in all matching slots of the type; if exactly one of these has
5076 a filled-in slot, return its value. Otherwise return NULL. */
5077 res = NULL;
5078 for (pp = ptrs; *pp; pp++) {
5079 ptr = slotptr(type, (*pp)->offset);
5080 if (ptr == NULL || *ptr == NULL)
5081 continue;
5082 if (res != NULL)
5083 return NULL;
5084 res = ptr;
5085 }
5086 return res;
5087}
5088
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005089/* Common code for update_slots_callback() and fixup_slot_dispatchers(). This
Guido van Rossumc334df52002-04-04 23:44:47 +00005090 does some incredibly complex thinking and then sticks something into the
5091 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
5092 interests, and then stores a generic wrapper or a specific function into
5093 the slot.) Return a pointer to the next slotdef with a different offset,
5094 because that's convenient for fixup_slot_dispatchers(). */
5095static slotdef *
5096update_one_slot(PyTypeObject *type, slotdef *p)
5097{
5098 PyObject *descr;
5099 PyWrapperDescrObject *d;
5100 void *generic = NULL, *specific = NULL;
5101 int use_generic = 0;
5102 int offset = p->offset;
5103 void **ptr = slotptr(type, offset);
5104
5105 if (ptr == NULL) {
5106 do {
5107 ++p;
5108 } while (p->offset == offset);
5109 return p;
5110 }
5111 do {
5112 descr = _PyType_Lookup(type, p->name_strobj);
5113 if (descr == NULL)
5114 continue;
5115 if (descr->ob_type == &PyWrapperDescr_Type) {
5116 void **tptr = resolve_slotdups(type, p->name_strobj);
5117 if (tptr == NULL || tptr == ptr)
5118 generic = p->function;
5119 d = (PyWrapperDescrObject *)descr;
5120 if (d->d_base->wrapper == p->wrapper &&
5121 PyType_IsSubtype(type, d->d_type))
5122 {
5123 if (specific == NULL ||
5124 specific == d->d_wrapped)
5125 specific = d->d_wrapped;
5126 else
5127 use_generic = 1;
5128 }
5129 }
Guido van Rossum721f62e2002-08-09 02:14:34 +00005130 else if (descr->ob_type == &PyCFunction_Type &&
5131 PyCFunction_GET_FUNCTION(descr) ==
5132 (PyCFunction)tp_new_wrapper &&
5133 strcmp(p->name, "__new__") == 0)
5134 {
5135 /* The __new__ wrapper is not a wrapper descriptor,
5136 so must be special-cased differently.
5137 If we don't do this, creating an instance will
5138 always use slot_tp_new which will look up
5139 __new__ in the MRO which will call tp_new_wrapper
5140 which will look through the base classes looking
5141 for a static base and call its tp_new (usually
5142 PyType_GenericNew), after performing various
5143 sanity checks and constructing a new argument
5144 list. Cut all that nonsense short -- this speeds
5145 up instance creation tremendously. */
Martin v. Löwisa94568a2003-05-10 07:36:56 +00005146 specific = (void *)type->tp_new;
Guido van Rossum721f62e2002-08-09 02:14:34 +00005147 /* XXX I'm not 100% sure that there isn't a hole
5148 in this reasoning that requires additional
5149 sanity checks. I'll buy the first person to
5150 point out a bug in this reasoning a beer. */
5151 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005152 else {
5153 use_generic = 1;
5154 generic = p->function;
5155 }
5156 } while ((++p)->offset == offset);
5157 if (specific && !use_generic)
5158 *ptr = specific;
5159 else
5160 *ptr = generic;
5161 return p;
5162}
5163
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005164/* In the type, update the slots whose slotdefs are gathered in the pp array.
5165 This is a callback for update_subclasses(). */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005166static int
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005167update_slots_callback(PyTypeObject *type, void *data)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005168{
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005169 slotdef **pp = (slotdef **)data;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005170
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005171 for (; *pp; pp++)
Guido van Rossumc334df52002-04-04 23:44:47 +00005172 update_one_slot(type, *pp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005173 return 0;
5174}
5175
Guido van Rossumc334df52002-04-04 23:44:47 +00005176/* Comparison function for qsort() to compare slotdefs by their offset, and
5177 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005178static int
5179slotdef_cmp(const void *aa, const void *bb)
5180{
5181 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
5182 int c = a->offset - b->offset;
5183 if (c != 0)
5184 return c;
5185 else
5186 return a - b;
5187}
5188
Guido van Rossumc334df52002-04-04 23:44:47 +00005189/* Initialize the slotdefs table by adding interned string objects for the
5190 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005191static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005192init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005193{
5194 slotdef *p;
5195 static int initialized = 0;
5196
5197 if (initialized)
5198 return;
5199 for (p = slotdefs; p->name; p++) {
5200 p->name_strobj = PyString_InternFromString(p->name);
5201 if (!p->name_strobj)
Guido van Rossumc334df52002-04-04 23:44:47 +00005202 Py_FatalError("Out of memory interning slotdef names");
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005203 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005204 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
5205 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005206 initialized = 1;
5207}
5208
Guido van Rossumc334df52002-04-04 23:44:47 +00005209/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005210static int
5211update_slot(PyTypeObject *type, PyObject *name)
5212{
Guido van Rossumc334df52002-04-04 23:44:47 +00005213 slotdef *ptrs[MAX_EQUIV];
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005214 slotdef *p;
5215 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005216 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005217
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005218 init_slotdefs();
5219 pp = ptrs;
5220 for (p = slotdefs; p->name; p++) {
5221 /* XXX assume name is interned! */
5222 if (p->name_strobj == name)
5223 *pp++ = p;
5224 }
5225 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005226 for (pp = ptrs; *pp; pp++) {
5227 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005228 offset = p->offset;
5229 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005230 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005231 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005232 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005233 if (ptrs[0] == NULL)
5234 return 0; /* Not an attribute that affects any slots */
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005235 return update_subclasses(type, name,
5236 update_slots_callback, (void *)ptrs);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005237}
5238
Guido van Rossumc334df52002-04-04 23:44:47 +00005239/* Store the proper functions in the slot dispatches at class (type)
5240 definition time, based upon which operations the class overrides in its
5241 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00005242static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005243fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005244{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005245 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005246
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005247 init_slotdefs();
Guido van Rossumc334df52002-04-04 23:44:47 +00005248 for (p = slotdefs; p->name; )
5249 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005250}
Guido van Rossum705f0f52001-08-24 16:47:00 +00005251
Michael W. Hudson98bbc492002-11-26 14:47:27 +00005252static void
5253update_all_slots(PyTypeObject* type)
5254{
5255 slotdef *p;
5256
5257 init_slotdefs();
5258 for (p = slotdefs; p->name; p++) {
5259 /* update_slot returns int but can't actually fail */
5260 update_slot(type, p->name_strobj);
5261 }
5262}
5263
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005264/* recurse_down_subclasses() and update_subclasses() are mutually
5265 recursive functions to call a callback for all subclasses,
5266 but refraining from recursing into subclasses that define 'name'. */
5267
5268static int
5269update_subclasses(PyTypeObject *type, PyObject *name,
5270 update_callback callback, void *data)
5271{
5272 if (callback(type, data) < 0)
5273 return -1;
5274 return recurse_down_subclasses(type, name, callback, data);
5275}
5276
5277static int
5278recurse_down_subclasses(PyTypeObject *type, PyObject *name,
5279 update_callback callback, void *data)
5280{
5281 PyTypeObject *subclass;
5282 PyObject *ref, *subclasses, *dict;
5283 int i, n;
5284
5285 subclasses = type->tp_subclasses;
5286 if (subclasses == NULL)
5287 return 0;
5288 assert(PyList_Check(subclasses));
5289 n = PyList_GET_SIZE(subclasses);
5290 for (i = 0; i < n; i++) {
5291 ref = PyList_GET_ITEM(subclasses, i);
5292 assert(PyWeakref_CheckRef(ref));
5293 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
5294 assert(subclass != NULL);
5295 if ((PyObject *)subclass == Py_None)
5296 continue;
5297 assert(PyType_Check(subclass));
5298 /* Avoid recursing down into unaffected classes */
5299 dict = subclass->tp_dict;
5300 if (dict != NULL && PyDict_Check(dict) &&
5301 PyDict_GetItem(dict, name) != NULL)
5302 continue;
5303 if (update_subclasses(subclass, name, callback, data) < 0)
5304 return -1;
5305 }
5306 return 0;
5307}
5308
Guido van Rossum6d204072001-10-21 00:44:31 +00005309/* This function is called by PyType_Ready() to populate the type's
5310 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00005311 function slot (like tp_repr) that's defined in the type, one or more
5312 corresponding descriptors are added in the type's tp_dict dictionary
5313 under the appropriate name (like __repr__). Some function slots
5314 cause more than one descriptor to be added (for example, the nb_add
5315 slot adds both __add__ and __radd__ descriptors) and some function
5316 slots compete for the same descriptor (for example both sq_item and
5317 mp_subscript generate a __getitem__ descriptor).
5318
5319 In the latter case, the first slotdef entry encoutered wins. Since
Tim Petersbf9b2442003-03-23 05:35:36 +00005320 slotdef entries are sorted by the offset of the slot in the
Guido van Rossume5c691a2003-03-07 15:13:17 +00005321 PyHeapTypeObject, this gives us some control over disambiguating
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005322 between competing slots: the members of PyHeapTypeObject are listed
5323 from most general to least general, so the most general slot is
5324 preferred. In particular, because as_mapping comes before as_sequence,
5325 for a type that defines both mp_subscript and sq_item, mp_subscript
5326 wins.
Guido van Rossum09638c12002-06-13 19:17:46 +00005327
5328 This only adds new descriptors and doesn't overwrite entries in
5329 tp_dict that were previously defined. The descriptors contain a
5330 reference to the C function they must call, so that it's safe if they
5331 are copied into a subtype's __dict__ and the subtype has a different
5332 C function in its slot -- calling the method defined by the
5333 descriptor will call the C function that was used to create it,
5334 rather than the C function present in the slot when it is called.
5335 (This is important because a subtype may have a C function in the
5336 slot that calls the method from the dictionary, and we want to avoid
5337 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00005338
5339static int
5340add_operators(PyTypeObject *type)
5341{
5342 PyObject *dict = type->tp_dict;
5343 slotdef *p;
5344 PyObject *descr;
5345 void **ptr;
5346
5347 init_slotdefs();
5348 for (p = slotdefs; p->name; p++) {
5349 if (p->wrapper == NULL)
5350 continue;
5351 ptr = slotptr(type, p->offset);
5352 if (!ptr || !*ptr)
5353 continue;
5354 if (PyDict_GetItem(dict, p->name_strobj))
5355 continue;
5356 descr = PyDescr_NewWrapper(type, p, *ptr);
5357 if (descr == NULL)
5358 return -1;
5359 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
5360 return -1;
5361 Py_DECREF(descr);
5362 }
5363 if (type->tp_new != NULL) {
5364 if (add_tp_new_wrapper(type) < 0)
5365 return -1;
5366 }
5367 return 0;
5368}
5369
Guido van Rossum705f0f52001-08-24 16:47:00 +00005370
5371/* Cooperative 'super' */
5372
5373typedef struct {
5374 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00005375 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005376 PyObject *obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005377 PyTypeObject *obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005378} superobject;
5379
Guido van Rossum6f799372001-09-20 20:46:19 +00005380static PyMemberDef super_members[] = {
5381 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
5382 "the class invoking super()"},
5383 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
5384 "the instance invoking super(); may be None"},
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005385 {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
5386 "the type of the the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005387 {0}
5388};
5389
Guido van Rossum705f0f52001-08-24 16:47:00 +00005390static void
5391super_dealloc(PyObject *self)
5392{
5393 superobject *su = (superobject *)self;
5394
Guido van Rossum048eb752001-10-02 21:24:57 +00005395 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005396 Py_XDECREF(su->obj);
5397 Py_XDECREF(su->type);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005398 Py_XDECREF(su->obj_type);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005399 self->ob_type->tp_free(self);
5400}
5401
5402static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005403super_repr(PyObject *self)
5404{
5405 superobject *su = (superobject *)self;
5406
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005407 if (su->obj_type)
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005408 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005409 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005410 su->type ? su->type->tp_name : "NULL",
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005411 su->obj_type->tp_name);
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005412 else
5413 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005414 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005415 su->type ? su->type->tp_name : "NULL");
5416}
5417
5418static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00005419super_getattro(PyObject *self, PyObject *name)
5420{
5421 superobject *su = (superobject *)self;
Guido van Rossum76ba09f2003-04-16 19:40:58 +00005422 int skip = su->obj_type == NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005423
Guido van Rossum76ba09f2003-04-16 19:40:58 +00005424 if (!skip) {
5425 /* We want __class__ to return the class of the super object
5426 (i.e. super, or a subclass), not the class of su->obj. */
5427 skip = (PyString_Check(name) &&
5428 PyString_GET_SIZE(name) == 9 &&
5429 strcmp(PyString_AS_STRING(name), "__class__") == 0);
5430 }
5431
5432 if (!skip) {
Tim Petersa91e9642001-11-14 23:32:33 +00005433 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005434 PyTypeObject *starttype;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005435 descrgetfunc f;
5436 int i, n;
5437
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005438 starttype = su->obj_type;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005439 mro = starttype->tp_mro;
5440
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005441 if (mro == NULL)
5442 n = 0;
5443 else {
5444 assert(PyTuple_Check(mro));
5445 n = PyTuple_GET_SIZE(mro);
5446 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005447 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00005448 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00005449 break;
5450 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005451 i++;
5452 res = NULL;
5453 for (; i < n; i++) {
5454 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00005455 if (PyType_Check(tmp))
5456 dict = ((PyTypeObject *)tmp)->tp_dict;
5457 else if (PyClass_Check(tmp))
5458 dict = ((PyClassObject *)tmp)->cl_dict;
5459 else
5460 continue;
5461 res = PyDict_GetItem(dict, name);
Guido van Rossum6cc5bb62003-04-16 20:01:36 +00005462 if (res != NULL) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00005463 Py_INCREF(res);
5464 f = res->ob_type->tp_descr_get;
5465 if (f != NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00005466 tmp = f(res, su->obj,
5467 (PyObject *)starttype);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005468 Py_DECREF(res);
5469 res = tmp;
5470 }
5471 return res;
5472 }
5473 }
5474 }
5475 return PyObject_GenericGetAttr(self, name);
5476}
5477
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005478static PyTypeObject *
Guido van Rossum5b443c62001-12-03 15:38:28 +00005479supercheck(PyTypeObject *type, PyObject *obj)
5480{
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005481 /* Check that a super() call makes sense. Return a type object.
5482
5483 obj can be a new-style class, or an instance of one:
5484
5485 - If it is a class, it must be a subclass of 'type'. This case is
5486 used for class methods; the return value is obj.
5487
5488 - If it is an instance, it must be an instance of 'type'. This is
5489 the normal case; the return value is obj.__class__.
5490
5491 But... when obj is an instance, we want to allow for the case where
5492 obj->ob_type is not a subclass of type, but obj.__class__ is!
5493 This will allow using super() with a proxy for obj.
5494 */
5495
Guido van Rossum8e80a722003-02-18 19:22:22 +00005496 /* Check for first bullet above (special case) */
5497 if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
5498 Py_INCREF(obj);
5499 return (PyTypeObject *)obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005500 }
Guido van Rossum8e80a722003-02-18 19:22:22 +00005501
5502 /* Normal case */
5503 if (PyType_IsSubtype(obj->ob_type, type)) {
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005504 Py_INCREF(obj->ob_type);
5505 return obj->ob_type;
5506 }
5507 else {
5508 /* Try the slow way */
5509 static PyObject *class_str = NULL;
5510 PyObject *class_attr;
5511
5512 if (class_str == NULL) {
5513 class_str = PyString_FromString("__class__");
5514 if (class_str == NULL)
5515 return NULL;
5516 }
5517
5518 class_attr = PyObject_GetAttr(obj, class_str);
5519
5520 if (class_attr != NULL &&
5521 PyType_Check(class_attr) &&
5522 (PyTypeObject *)class_attr != obj->ob_type)
5523 {
5524 int ok = PyType_IsSubtype(
5525 (PyTypeObject *)class_attr, type);
5526 if (ok)
5527 return (PyTypeObject *)class_attr;
5528 }
5529
5530 if (class_attr == NULL)
5531 PyErr_Clear();
5532 else
5533 Py_DECREF(class_attr);
5534 }
5535
Tim Peters97e5ff52003-02-18 19:32:50 +00005536 PyErr_SetString(PyExc_TypeError,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005537 "super(type, obj): "
5538 "obj must be an instance or subtype of type");
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005539 return NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005540}
5541
Guido van Rossum705f0f52001-08-24 16:47:00 +00005542static PyObject *
5543super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5544{
5545 superobject *su = (superobject *)self;
5546 superobject *new;
5547
5548 if (obj == NULL || obj == Py_None || su->obj != NULL) {
5549 /* Not binding to an object, or already bound */
5550 Py_INCREF(self);
5551 return self;
5552 }
Guido van Rossum5b443c62001-12-03 15:38:28 +00005553 if (su->ob_type != &PySuper_Type)
Brett Cannon10147f72003-06-11 20:50:33 +00005554 /* If su is not an instance of a subclass of super,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005555 call its type */
5556 return PyObject_CallFunction((PyObject *)su->ob_type,
5557 "OO", su->type, obj);
5558 else {
5559 /* Inline the common case */
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005560 PyTypeObject *obj_type = supercheck(su->type, obj);
5561 if (obj_type == NULL)
Guido van Rossum5b443c62001-12-03 15:38:28 +00005562 return NULL;
5563 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
5564 NULL, NULL);
5565 if (new == NULL)
5566 return NULL;
5567 Py_INCREF(su->type);
5568 Py_INCREF(obj);
5569 new->type = su->type;
5570 new->obj = obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005571 new->obj_type = obj_type;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005572 return (PyObject *)new;
5573 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005574}
5575
5576static int
5577super_init(PyObject *self, PyObject *args, PyObject *kwds)
5578{
5579 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00005580 PyTypeObject *type;
5581 PyObject *obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005582 PyTypeObject *obj_type = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005583
5584 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
5585 return -1;
5586 if (obj == Py_None)
5587 obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005588 if (obj != NULL) {
5589 obj_type = supercheck(type, obj);
5590 if (obj_type == NULL)
5591 return -1;
5592 Py_INCREF(obj);
5593 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005594 Py_INCREF(type);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005595 su->type = type;
5596 su->obj = obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005597 su->obj_type = obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005598 return 0;
5599}
5600
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005601PyDoc_STRVAR(super_doc,
Guido van Rossum705f0f52001-08-24 16:47:00 +00005602"super(type) -> unbound super object\n"
5603"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00005604"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00005605"Typical use to call a cooperative superclass method:\n"
5606"class C(B):\n"
5607" def meth(self, arg):\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005608" super(C, self).meth(arg)");
Guido van Rossum705f0f52001-08-24 16:47:00 +00005609
Guido van Rossum048eb752001-10-02 21:24:57 +00005610static int
5611super_traverse(PyObject *self, visitproc visit, void *arg)
5612{
5613 superobject *su = (superobject *)self;
5614 int err;
5615
5616#define VISIT(SLOT) \
5617 if (SLOT) { \
5618 err = visit((PyObject *)(SLOT), arg); \
5619 if (err) \
5620 return err; \
5621 }
5622
5623 VISIT(su->obj);
5624 VISIT(su->type);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005625 VISIT(su->obj_type);
Guido van Rossum048eb752001-10-02 21:24:57 +00005626
5627#undef VISIT
5628
5629 return 0;
5630}
5631
Guido van Rossum705f0f52001-08-24 16:47:00 +00005632PyTypeObject PySuper_Type = {
5633 PyObject_HEAD_INIT(&PyType_Type)
5634 0, /* ob_size */
5635 "super", /* tp_name */
5636 sizeof(superobject), /* tp_basicsize */
5637 0, /* tp_itemsize */
5638 /* methods */
5639 super_dealloc, /* tp_dealloc */
5640 0, /* tp_print */
5641 0, /* tp_getattr */
5642 0, /* tp_setattr */
5643 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005644 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005645 0, /* tp_as_number */
5646 0, /* tp_as_sequence */
5647 0, /* tp_as_mapping */
5648 0, /* tp_hash */
5649 0, /* tp_call */
5650 0, /* tp_str */
5651 super_getattro, /* tp_getattro */
5652 0, /* tp_setattro */
5653 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00005654 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
5655 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005656 super_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00005657 super_traverse, /* tp_traverse */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005658 0, /* tp_clear */
5659 0, /* tp_richcompare */
5660 0, /* tp_weaklistoffset */
5661 0, /* tp_iter */
5662 0, /* tp_iternext */
5663 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005664 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005665 0, /* tp_getset */
5666 0, /* tp_base */
5667 0, /* tp_dict */
5668 super_descr_get, /* tp_descr_get */
5669 0, /* tp_descr_set */
5670 0, /* tp_dictoffset */
5671 super_init, /* tp_init */
5672 PyType_GenericAlloc, /* tp_alloc */
5673 PyType_GenericNew, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00005674 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005675};