blob: 4a13928c214c5690d1bd25371c83d8fdeb5b8feb [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);
167 if (!tuple)
168 return -1;
169 if (PyList_Append(temp, tuple) < 0)
170 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000171 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000172 if (mro_subclasses(subclass, temp) < 0)
173 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000174 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000175 return 0;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000176}
177
178static int
179type_set_bases(PyTypeObject *type, PyObject *value, void *context)
180{
181 int i, r = 0;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000182 PyObject *ob, *temp;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000183 PyTypeObject *new_base, *old_base;
184 PyObject *old_bases, *old_mro;
185
186 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
187 PyErr_Format(PyExc_TypeError,
188 "can't set %s.__bases__", type->tp_name);
189 return -1;
190 }
191 if (!value) {
192 PyErr_Format(PyExc_TypeError,
193 "can't delete %s.__bases__", type->tp_name);
194 return -1;
195 }
196 if (!PyTuple_Check(value)) {
197 PyErr_Format(PyExc_TypeError,
198 "can only assign tuple to %s.__bases__, not %s",
199 type->tp_name, value->ob_type->tp_name);
200 return -1;
201 }
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +0000202 if (PyTuple_GET_SIZE(value) == 0) {
203 PyErr_Format(PyExc_TypeError,
204 "can only assign non-empty tuple to %s.__bases__, not ()",
205 type->tp_name);
206 return -1;
207 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000208 for (i = 0; i < PyTuple_GET_SIZE(value); i++) {
209 ob = PyTuple_GET_ITEM(value, i);
210 if (!PyClass_Check(ob) && !PyType_Check(ob)) {
211 PyErr_Format(
212 PyExc_TypeError,
213 "%s.__bases__ must be tuple of old- or new-style classes, not '%s'",
214 type->tp_name, ob->ob_type->tp_name);
215 return -1;
216 }
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +0000217 if (PyType_Check(ob)) {
218 if (PyType_IsSubtype((PyTypeObject*)ob, type)) {
219 PyErr_SetString(PyExc_TypeError,
220 "a __bases__ item causes an inheritance cycle");
221 return -1;
222 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000223 }
224 }
225
226 new_base = best_base(value);
227
228 if (!new_base) {
229 return -1;
230 }
231
232 if (!compatible_for_assignment(type->tp_base, new_base, "__bases__"))
233 return -1;
234
235 Py_INCREF(new_base);
236 Py_INCREF(value);
237
238 old_bases = type->tp_bases;
239 old_base = type->tp_base;
240 old_mro = type->tp_mro;
241
242 type->tp_bases = value;
243 type->tp_base = new_base;
244
245 if (mro_internal(type) < 0) {
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000246 goto bail;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000247 }
248
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000249 temp = PyList_New(0);
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000250 if (!temp)
251 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000252
253 r = mro_subclasses(type, temp);
254
255 if (r < 0) {
256 for (i = 0; i < PyList_Size(temp); i++) {
257 PyTypeObject* cls;
258 PyObject* mro;
259 PyArg_ParseTuple(PyList_GetItem(temp, i),
260 "OO", &cls, &mro);
261 Py_DECREF(cls->tp_mro);
262 cls->tp_mro = mro;
263 Py_INCREF(cls->tp_mro);
264 }
265 Py_DECREF(temp);
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000266 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000267 }
268
269 Py_DECREF(temp);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000270
271 /* any base that was in __bases__ but now isn't, we
Raymond Hettingera8285862002-12-14 17:17:56 +0000272 need to remove |type| from its tp_subclasses.
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000273 conversely, any class now in __bases__ that wasn't
Raymond Hettingera8285862002-12-14 17:17:56 +0000274 needs to have |type| added to its subclasses. */
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000275
276 /* for now, sod that: just remove from all old_bases,
277 add to all new_bases */
278
279 for (i = PyTuple_GET_SIZE(old_bases) - 1; i >= 0; i--) {
280 ob = PyTuple_GET_ITEM(old_bases, i);
281 if (PyType_Check(ob)) {
282 remove_subclass(
283 (PyTypeObject*)ob, type);
284 }
285 }
286
287 for (i = PyTuple_GET_SIZE(value) - 1; i >= 0; i--) {
288 ob = PyTuple_GET_ITEM(value, i);
289 if (PyType_Check(ob)) {
290 if (add_subclass((PyTypeObject*)ob, type) < 0)
291 r = -1;
292 }
293 }
294
295 update_all_slots(type);
296
297 Py_DECREF(old_bases);
298 Py_DECREF(old_base);
299 Py_DECREF(old_mro);
300
301 return r;
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000302
303 bail:
304 type->tp_bases = old_bases;
305 type->tp_base = old_base;
306 type->tp_mro = old_mro;
Tim Petersea7f75d2002-12-07 21:39:16 +0000307
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000308 Py_DECREF(value);
309 Py_DECREF(new_base);
Tim Petersea7f75d2002-12-07 21:39:16 +0000310
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000311 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000312}
313
314static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000315type_dict(PyTypeObject *type, void *context)
316{
317 if (type->tp_dict == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000318 Py_INCREF(Py_None);
319 return Py_None;
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000320 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000321 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000322}
323
Tim Peters24008312002-03-17 18:56:20 +0000324static PyObject *
325type_get_doc(PyTypeObject *type, void *context)
326{
327 PyObject *result;
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000328 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL)
Tim Peters24008312002-03-17 18:56:20 +0000329 return PyString_FromString(type->tp_doc);
Tim Peters24008312002-03-17 18:56:20 +0000330 result = PyDict_GetItemString(type->tp_dict, "__doc__");
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000331 if (result == NULL) {
332 result = Py_None;
333 Py_INCREF(result);
334 }
335 else if (result->ob_type->tp_descr_get) {
Tim Peters2b858972002-04-18 04:12:28 +0000336 result = result->ob_type->tp_descr_get(result, NULL,
337 (PyObject *)type);
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000338 }
339 else {
340 Py_INCREF(result);
341 }
Tim Peters24008312002-03-17 18:56:20 +0000342 return result;
343}
344
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000345static PyGetSetDef type_getsets[] = {
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000346 {"__name__", (getter)type_name, (setter)type_set_name, NULL},
347 {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL},
Guido van Rossum3926a632001-09-25 16:25:58 +0000348 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000349 {"__dict__", (getter)type_dict, NULL, NULL},
Tim Peters24008312002-03-17 18:56:20 +0000350 {"__doc__", (getter)type_get_doc, NULL, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000351 {0}
352};
353
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000354static int
355type_compare(PyObject *v, PyObject *w)
356{
357 /* This is called with type objects only. So we
358 can just compare the addresses. */
359 Py_uintptr_t vv = (Py_uintptr_t)v;
360 Py_uintptr_t ww = (Py_uintptr_t)w;
361 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
362}
363
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000364static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000365type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000366{
Barry Warsaw7ce36942001-08-24 18:34:26 +0000367 PyObject *mod, *name, *rtn;
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000368 char *kind;
Guido van Rossumc3542212001-08-16 09:18:56 +0000369
370 mod = type_module(type, NULL);
371 if (mod == NULL)
372 PyErr_Clear();
373 else if (!PyString_Check(mod)) {
374 Py_DECREF(mod);
375 mod = NULL;
376 }
377 name = type_name(type, NULL);
378 if (name == NULL)
379 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000380
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000381 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
382 kind = "class";
383 else
384 kind = "type";
385
Barry Warsaw7ce36942001-08-24 18:34:26 +0000386 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__")) {
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000387 rtn = PyString_FromFormat("<%s '%s.%s'>",
388 kind,
Barry Warsaw7ce36942001-08-24 18:34:26 +0000389 PyString_AS_STRING(mod),
390 PyString_AS_STRING(name));
391 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000392 else
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000393 rtn = PyString_FromFormat("<%s '%s'>", kind, type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000394
Guido van Rossumc3542212001-08-16 09:18:56 +0000395 Py_XDECREF(mod);
396 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000397 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000398}
399
Tim Peters6d6c1a32001-08-02 04:15:00 +0000400static PyObject *
401type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
402{
403 PyObject *obj;
404
405 if (type->tp_new == NULL) {
406 PyErr_Format(PyExc_TypeError,
407 "cannot create '%.100s' instances",
408 type->tp_name);
409 return NULL;
410 }
411
Tim Peters3f996e72001-09-13 19:18:27 +0000412 obj = type->tp_new(type, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000413 if (obj != NULL) {
Guido van Rossumf76de622001-10-18 15:49:21 +0000414 /* Ugly exception: when the call was type(something),
415 don't call tp_init on the result. */
416 if (type == &PyType_Type &&
417 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
418 (kwds == NULL ||
419 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
420 return obj;
Guido van Rossum8ace1ab2002-04-06 01:05:01 +0000421 /* If the returned object is not an instance of type,
422 it won't be initialized. */
423 if (!PyType_IsSubtype(obj->ob_type, type))
424 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000425 type = obj->ob_type;
Jeremy Hylton719841e2002-07-16 19:39:38 +0000426 if (PyType_HasFeature(type, Py_TPFLAGS_HAVE_CLASS) &&
427 type->tp_init != NULL &&
Tim Peters6d6c1a32001-08-02 04:15:00 +0000428 type->tp_init(obj, args, kwds) < 0) {
429 Py_DECREF(obj);
430 obj = NULL;
431 }
432 }
433 return obj;
434}
435
436PyObject *
437PyType_GenericAlloc(PyTypeObject *type, int nitems)
438{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000439 PyObject *obj;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000440 const size_t size = _PyObject_VAR_SIZE(type, nitems+1);
441 /* note that we need to add one, for the sentinel */
Tim Peters406fe3b2001-10-06 19:04:01 +0000442
443 if (PyType_IS_GC(type))
Neil Schemenauer09a2ae52002-04-12 03:06:53 +0000444 obj = _PyObject_GC_Malloc(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000445 else
Neil Schemenauerc806c882001-08-29 23:54:54 +0000446 obj = PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000447
Neil Schemenauerc806c882001-08-29 23:54:54 +0000448 if (obj == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000449 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000450
Neil Schemenauerc806c882001-08-29 23:54:54 +0000451 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000452
Tim Peters6d6c1a32001-08-02 04:15:00 +0000453 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
454 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000455
Tim Peters6d6c1a32001-08-02 04:15:00 +0000456 if (type->tp_itemsize == 0)
457 PyObject_INIT(obj, type);
458 else
459 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000460
Tim Peters6d6c1a32001-08-02 04:15:00 +0000461 if (PyType_IS_GC(type))
Neil Schemenauerc806c882001-08-29 23:54:54 +0000462 _PyObject_GC_TRACK(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000463 return obj;
464}
465
466PyObject *
467PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
468{
469 return type->tp_alloc(type, 0);
470}
471
Guido van Rossum9475a232001-10-05 20:51:39 +0000472/* Helpers for subtyping */
473
474static int
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000475traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
476{
477 int i, n;
478 PyMemberDef *mp;
479
480 n = type->ob_size;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000481 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000482 for (i = 0; i < n; i++, mp++) {
483 if (mp->type == T_OBJECT_EX) {
484 char *addr = (char *)self + mp->offset;
485 PyObject *obj = *(PyObject **)addr;
486 if (obj != NULL) {
487 int err = visit(obj, arg);
488 if (err)
489 return err;
490 }
491 }
492 }
493 return 0;
494}
495
496static int
Guido van Rossum9475a232001-10-05 20:51:39 +0000497subtype_traverse(PyObject *self, visitproc visit, void *arg)
498{
499 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000500 traverseproc basetraverse;
Guido van Rossum9475a232001-10-05 20:51:39 +0000501
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000502 /* Find the nearest base with a different tp_traverse,
503 and traverse slots while we're at it */
Guido van Rossum9475a232001-10-05 20:51:39 +0000504 type = self->ob_type;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000505 base = type;
506 while ((basetraverse = base->tp_traverse) == subtype_traverse) {
507 if (base->ob_size) {
508 int err = traverse_slots(base, self, visit, arg);
509 if (err)
510 return err;
511 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000512 base = base->tp_base;
513 assert(base);
514 }
515
516 if (type->tp_dictoffset != base->tp_dictoffset) {
517 PyObject **dictptr = _PyObject_GetDictPtr(self);
518 if (dictptr && *dictptr) {
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000519 int err = visit(*dictptr, arg);
Guido van Rossum9475a232001-10-05 20:51:39 +0000520 if (err)
521 return err;
522 }
523 }
524
Guido van Rossuma3862092002-06-10 15:24:42 +0000525 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
526 /* For a heaptype, the instances count as references
527 to the type. Traverse the type so the collector
528 can find cycles involving this link. */
529 int err = visit((PyObject *)type, arg);
530 if (err)
531 return err;
532 }
533
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000534 if (basetraverse)
535 return basetraverse(self, visit, arg);
536 return 0;
537}
538
539static void
540clear_slots(PyTypeObject *type, PyObject *self)
541{
542 int i, n;
543 PyMemberDef *mp;
544
545 n = type->ob_size;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000546 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000547 for (i = 0; i < n; i++, mp++) {
548 if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
549 char *addr = (char *)self + mp->offset;
550 PyObject *obj = *(PyObject **)addr;
551 if (obj != NULL) {
552 Py_DECREF(obj);
553 *(PyObject **)addr = NULL;
554 }
555 }
556 }
557}
558
559static int
560subtype_clear(PyObject *self)
561{
562 PyTypeObject *type, *base;
563 inquiry baseclear;
564
565 /* Find the nearest base with a different tp_clear
566 and clear slots while we're at it */
567 type = self->ob_type;
568 base = type;
569 while ((baseclear = base->tp_clear) == subtype_clear) {
570 if (base->ob_size)
571 clear_slots(base, self);
572 base = base->tp_base;
573 assert(base);
574 }
575
Guido van Rossuma3862092002-06-10 15:24:42 +0000576 /* There's no need to clear the instance dict (if any);
577 the collector will call its tp_clear handler. */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000578
579 if (baseclear)
580 return baseclear(self);
Guido van Rossum9475a232001-10-05 20:51:39 +0000581 return 0;
582}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000583
584static void
585subtype_dealloc(PyObject *self)
586{
Guido van Rossum14227b42001-12-06 02:35:58 +0000587 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000588 destructor basedealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000589
Guido van Rossum22b13872002-08-06 21:41:44 +0000590 /* Extract the type; we expect it to be a heap type */
591 type = self->ob_type;
592 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000593
Guido van Rossum22b13872002-08-06 21:41:44 +0000594 /* Test whether the type has GC exactly once */
595
596 if (!PyType_IS_GC(type)) {
597 /* It's really rare to find a dynamic type that doesn't have
598 GC; it can only happen when deriving from 'object' and not
599 adding any slots or instance variables. This allows
600 certain simplifications: there's no need to call
601 clear_slots(), or DECREF the dict, or clear weakrefs. */
602
603 /* Maybe call finalizer; exit early if resurrected */
Guido van Rossumfebd61d2002-08-08 20:55:20 +0000604 if (type->tp_del) {
605 type->tp_del(self);
606 if (self->ob_refcnt > 0)
607 return;
608 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000609
610 /* Find the nearest base with a different tp_dealloc */
611 base = type;
612 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
613 assert(base->ob_size == 0);
614 base = base->tp_base;
615 assert(base);
616 }
617
618 /* Call the base tp_dealloc() */
619 assert(basedealloc);
620 basedealloc(self);
621
622 /* Can't reference self beyond this point */
623 Py_DECREF(type);
624
625 /* Done */
626 return;
627 }
628
629 /* We get here only if the type has GC */
630
631 /* UnTrack and re-Track around the trashcan macro, alas */
Andrew M. Kuchlingc9172d32003-02-06 15:22:49 +0000632 /* See explanation at end of function for full disclosure */
Guido van Rossum0906e072002-08-07 20:42:09 +0000633 PyObject_GC_UnTrack(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000634 ++_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000635 Py_TRASHCAN_SAFE_BEGIN(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000636 --_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000637 _PyObject_GC_TRACK(self); /* We'll untrack for real later */
638
639 /* Maybe call finalizer; exit early if resurrected */
Guido van Rossumfebd61d2002-08-08 20:55:20 +0000640 if (type->tp_del) {
641 type->tp_del(self);
642 if (self->ob_refcnt > 0)
643 goto endlabel;
644 }
Guido van Rossum7ad2d1e2001-10-29 22:11:00 +0000645
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000646 /* Find the nearest base with a different tp_dealloc
647 and clear slots while we're at it */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000648 base = type;
649 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
650 if (base->ob_size)
651 clear_slots(base, self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000652 base = base->tp_base;
653 assert(base);
Guido van Rossum14227b42001-12-06 02:35:58 +0000654 }
655
Tim Peters6d6c1a32001-08-02 04:15:00 +0000656 /* If we added a dict, DECREF it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000657 if (type->tp_dictoffset && !base->tp_dictoffset) {
658 PyObject **dictptr = _PyObject_GetDictPtr(self);
659 if (dictptr != NULL) {
660 PyObject *dict = *dictptr;
661 if (dict != NULL) {
662 Py_DECREF(dict);
663 *dictptr = NULL;
664 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000665 }
666 }
667
Guido van Rossum9676b222001-08-17 20:32:36 +0000668 /* If we added weaklist, we clear it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000669 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
Guido van Rossum9676b222001-08-17 20:32:36 +0000670 PyObject_ClearWeakRefs(self);
671
Tim Peters6d6c1a32001-08-02 04:15:00 +0000672 /* Finalize GC if the base doesn't do GC and we do */
Guido van Rossum22b13872002-08-06 21:41:44 +0000673 if (!PyType_IS_GC(base))
Guido van Rossum048eb752001-10-02 21:24:57 +0000674 _PyObject_GC_UNTRACK(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000675
676 /* Call the base tp_dealloc() */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000677 assert(basedealloc);
678 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000679
680 /* Can't reference self beyond this point */
Guido van Rossum22b13872002-08-06 21:41:44 +0000681 Py_DECREF(type);
682
Guido van Rossum0906e072002-08-07 20:42:09 +0000683 endlabel:
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000684 ++_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000685 Py_TRASHCAN_SAFE_END(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000686 --_PyTrash_delete_nesting;
687
688 /* Explanation of the weirdness around the trashcan macros:
689
690 Q. What do the trashcan macros do?
691
692 A. Read the comment titled "Trashcan mechanism" in object.h.
693 For one, this explains why there must be a call to GC-untrack
694 before the trashcan begin macro. Without understanding the
695 trashcan code, the answers to the following questions don't make
696 sense.
697
698 Q. Why do we GC-untrack before the trashcan and then immediately
699 GC-track again afterward?
700
701 A. In the case that the base class is GC-aware, the base class
702 probably GC-untracks the object. If it does that using the
703 UNTRACK macro, this will crash when the object is already
704 untracked. Because we don't know what the base class does, the
705 only safe thing is to make sure the object is tracked when we
706 call the base class dealloc. But... The trashcan begin macro
707 requires that the object is *untracked* before it is called. So
708 the dance becomes:
709
710 GC untrack
711 trashcan begin
712 GC track
713
714 Q. Why the bizarre (net-zero) manipulation of
715 _PyTrash_delete_nesting around the trashcan macros?
716
717 A. Some base classes (e.g. list) also use the trashcan mechanism.
718 The following scenario used to be possible:
719
720 - suppose the trashcan level is one below the trashcan limit
721
722 - subtype_dealloc() is called
723
724 - the trashcan limit is not yet reached, so the trashcan level
725 is incremented and the code between trashcan begin and end is
726 executed
727
728 - this destroys much of the object's contents, including its
729 slots and __dict__
730
731 - basedealloc() is called; this is really list_dealloc(), or
732 some other type which also uses the trashcan macros
733
734 - the trashcan limit is now reached, so the object is put on the
735 trashcan's to-be-deleted-later list
736
737 - basedealloc() returns
738
739 - subtype_dealloc() decrefs the object's type
740
741 - subtype_dealloc() returns
742
743 - later, the trashcan code starts deleting the objects from its
744 to-be-deleted-later list
745
746 - subtype_dealloc() is called *AGAIN* for the same object
747
748 - at the very least (if the destroyed slots and __dict__ don't
749 cause problems) the object's type gets decref'ed a second
750 time, which is *BAD*!!!
751
752 The remedy is to make sure that if the code between trashcan
753 begin and end in subtype_dealloc() is called, the code between
754 trashcan begin and end in basedealloc() will also be called.
755 This is done by decrementing the level after passing into the
756 trashcan block, and incrementing it just before leaving the
757 block.
758
759 But now it's possible that a chain of objects consisting solely
760 of objects whose deallocator is subtype_dealloc() will defeat
761 the trashcan mechanism completely: the decremented level means
762 that the effective level never reaches the limit. Therefore, we
763 *increment* the level *before* entering the trashcan block, and
764 matchingly decrement it after leaving. This means the trashcan
765 code will trigger a little early, but that's no big deal.
766
767 Q. Are there any live examples of code in need of all this
768 complexity?
769
770 A. Yes. See SF bug 668433 for code that crashed (when Python was
771 compiled in debug mode) before the trashcan level manipulations
772 were added. For more discussion, see SF patches 581742, 575073
773 and bug 574207.
774 */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000775}
776
Jeremy Hylton938ace62002-07-17 16:30:39 +0000777static PyTypeObject *solid_base(PyTypeObject *type);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000778
Tim Peters6d6c1a32001-08-02 04:15:00 +0000779/* type test with subclassing support */
780
781int
782PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
783{
784 PyObject *mro;
785
Guido van Rossum9478d072001-09-07 18:52:13 +0000786 if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
787 return b == a || b == &PyBaseObject_Type;
788
Tim Peters6d6c1a32001-08-02 04:15:00 +0000789 mro = a->tp_mro;
790 if (mro != NULL) {
791 /* Deal with multiple inheritance without recursion
792 by walking the MRO tuple */
793 int i, n;
794 assert(PyTuple_Check(mro));
795 n = PyTuple_GET_SIZE(mro);
796 for (i = 0; i < n; i++) {
797 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
798 return 1;
799 }
800 return 0;
801 }
802 else {
803 /* a is not completely initilized yet; follow tp_base */
804 do {
805 if (a == b)
806 return 1;
807 a = a->tp_base;
808 } while (a != NULL);
809 return b == &PyBaseObject_Type;
810 }
811}
812
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000813/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +0000814 without looking in the instance dictionary
815 (so we can't use PyObject_GetAttr) but still binding
816 it to the instance. The arguments are the object,
817 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000818 static variable used to cache the interned Python string.
819
820 Two variants:
821
822 - lookup_maybe() returns NULL without raising an exception
823 when the _PyType_Lookup() call fails;
824
825 - lookup_method() always raises an exception upon errors.
826*/
Guido van Rossum60718732001-08-28 17:47:51 +0000827
828static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000829lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +0000830{
831 PyObject *res;
832
833 if (*attrobj == NULL) {
834 *attrobj = PyString_InternFromString(attrstr);
835 if (*attrobj == NULL)
836 return NULL;
837 }
838 res = _PyType_Lookup(self->ob_type, *attrobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000839 if (res != NULL) {
Guido van Rossum60718732001-08-28 17:47:51 +0000840 descrgetfunc f;
841 if ((f = res->ob_type->tp_descr_get) == NULL)
842 Py_INCREF(res);
843 else
844 res = f(res, self, (PyObject *)(self->ob_type));
845 }
846 return res;
847}
848
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000849static PyObject *
850lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
851{
852 PyObject *res = lookup_maybe(self, attrstr, attrobj);
853 if (res == NULL && !PyErr_Occurred())
854 PyErr_SetObject(PyExc_AttributeError, *attrobj);
855 return res;
856}
857
Guido van Rossum2730b132001-08-28 18:22:14 +0000858/* A variation of PyObject_CallMethod that uses lookup_method()
859 instead of PyObject_GetAttrString(). This uses the same convention
860 as lookup_method to cache the interned name string object. */
861
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000862static PyObject *
Guido van Rossum2730b132001-08-28 18:22:14 +0000863call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
864{
865 va_list va;
866 PyObject *args, *func = 0, *retval;
Guido van Rossum2730b132001-08-28 18:22:14 +0000867 va_start(va, format);
868
Guido van Rossumda21c012001-10-03 00:50:18 +0000869 func = lookup_maybe(o, name, nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000870 if (func == NULL) {
871 va_end(va);
872 if (!PyErr_Occurred())
Guido van Rossumda21c012001-10-03 00:50:18 +0000873 PyErr_SetObject(PyExc_AttributeError, *nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000874 return NULL;
875 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000876
877 if (format && *format)
878 args = Py_VaBuildValue(format, va);
879 else
880 args = PyTuple_New(0);
881
882 va_end(va);
883
884 if (args == NULL)
885 return NULL;
886
887 assert(PyTuple_Check(args));
888 retval = PyObject_Call(func, args, NULL);
889
890 Py_DECREF(args);
891 Py_DECREF(func);
892
893 return retval;
894}
895
896/* Clone of call_method() that returns NotImplemented when the lookup fails. */
897
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000898static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000899call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
900{
901 va_list va;
902 PyObject *args, *func = 0, *retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000903 va_start(va, format);
904
Guido van Rossumda21c012001-10-03 00:50:18 +0000905 func = lookup_maybe(o, name, nameobj);
Guido van Rossum2730b132001-08-28 18:22:14 +0000906 if (func == NULL) {
907 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000908 if (!PyErr_Occurred()) {
909 Py_INCREF(Py_NotImplemented);
910 return Py_NotImplemented;
911 }
Guido van Rossum717ce002001-09-14 16:58:08 +0000912 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +0000913 }
914
915 if (format && *format)
916 args = Py_VaBuildValue(format, va);
917 else
918 args = PyTuple_New(0);
919
920 va_end(va);
921
Guido van Rossum717ce002001-09-14 16:58:08 +0000922 if (args == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +0000923 return NULL;
924
Guido van Rossum717ce002001-09-14 16:58:08 +0000925 assert(PyTuple_Check(args));
926 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +0000927
928 Py_DECREF(args);
929 Py_DECREF(func);
930
931 return retval;
932}
933
Tim Petersa91e9642001-11-14 23:32:33 +0000934static int
935fill_classic_mro(PyObject *mro, PyObject *cls)
936{
937 PyObject *bases, *base;
938 int i, n;
939
940 assert(PyList_Check(mro));
941 assert(PyClass_Check(cls));
942 i = PySequence_Contains(mro, cls);
943 if (i < 0)
944 return -1;
945 if (!i) {
946 if (PyList_Append(mro, cls) < 0)
947 return -1;
948 }
949 bases = ((PyClassObject *)cls)->cl_bases;
950 assert(bases && PyTuple_Check(bases));
951 n = PyTuple_GET_SIZE(bases);
952 for (i = 0; i < n; i++) {
953 base = PyTuple_GET_ITEM(bases, i);
954 if (fill_classic_mro(mro, base) < 0)
955 return -1;
956 }
957 return 0;
958}
959
960static PyObject *
961classic_mro(PyObject *cls)
962{
963 PyObject *mro;
964
965 assert(PyClass_Check(cls));
966 mro = PyList_New(0);
967 if (mro != NULL) {
968 if (fill_classic_mro(mro, cls) == 0)
969 return mro;
970 Py_DECREF(mro);
971 }
972 return NULL;
973}
974
Tim Petersea7f75d2002-12-07 21:39:16 +0000975/*
Guido van Rossum1f121312002-11-14 19:49:16 +0000976 Method resolution order algorithm C3 described in
977 "A Monotonic Superclass Linearization for Dylan",
978 by Kim Barrett, Bob Cassel, Paul Haahr,
Tim Petersea7f75d2002-12-07 21:39:16 +0000979 David A. Moon, Keith Playford, and P. Tucker Withington.
Guido van Rossum1f121312002-11-14 19:49:16 +0000980 (OOPSLA 1996)
981
Guido van Rossum98f33732002-11-25 21:36:54 +0000982 Some notes about the rules implied by C3:
983
Tim Petersea7f75d2002-12-07 21:39:16 +0000984 No duplicate bases.
Guido van Rossum98f33732002-11-25 21:36:54 +0000985 It isn't legal to repeat a class in a list of base classes.
986
987 The next three properties are the 3 constraints in "C3".
988
Tim Petersea7f75d2002-12-07 21:39:16 +0000989 Local precendece order.
Guido van Rossum98f33732002-11-25 21:36:54 +0000990 If A precedes B in C's MRO, then A will precede B in the MRO of all
991 subclasses of C.
992
993 Monotonicity.
994 The MRO of a class must be an extension without reordering of the
995 MRO of each of its superclasses.
996
997 Extended Precedence Graph (EPG).
998 Linearization is consistent if there is a path in the EPG from
999 each class to all its successors in the linearization. See
1000 the paper for definition of EPG.
Guido van Rossum1f121312002-11-14 19:49:16 +00001001 */
1002
Tim Petersea7f75d2002-12-07 21:39:16 +00001003static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001004tail_contains(PyObject *list, int whence, PyObject *o) {
1005 int j, size;
1006 size = PyList_GET_SIZE(list);
1007
1008 for (j = whence+1; j < size; j++) {
1009 if (PyList_GET_ITEM(list, j) == o)
1010 return 1;
1011 }
1012 return 0;
1013}
1014
Guido van Rossum98f33732002-11-25 21:36:54 +00001015static PyObject *
1016class_name(PyObject *cls)
1017{
1018 PyObject *name = PyObject_GetAttrString(cls, "__name__");
1019 if (name == NULL) {
1020 PyErr_Clear();
1021 Py_XDECREF(name);
1022 name = PyObject_Repr(cls);
1023 }
1024 if (name == NULL)
1025 return NULL;
1026 if (!PyString_Check(name)) {
1027 Py_DECREF(name);
1028 return NULL;
1029 }
1030 return name;
1031}
1032
1033static int
1034check_duplicates(PyObject *list)
1035{
1036 int i, j, n;
1037 /* Let's use a quadratic time algorithm,
1038 assuming that the bases lists is short.
1039 */
1040 n = PyList_GET_SIZE(list);
1041 for (i = 0; i < n; i++) {
1042 PyObject *o = PyList_GET_ITEM(list, i);
1043 for (j = i + 1; j < n; j++) {
1044 if (PyList_GET_ITEM(list, j) == o) {
1045 o = class_name(o);
1046 PyErr_Format(PyExc_TypeError,
1047 "duplicate base class %s",
1048 o ? PyString_AS_STRING(o) : "?");
1049 Py_XDECREF(o);
1050 return -1;
1051 }
1052 }
1053 }
1054 return 0;
1055}
1056
1057/* Raise a TypeError for an MRO order disagreement.
1058
1059 It's hard to produce a good error message. In the absence of better
1060 insight into error reporting, report the classes that were candidates
1061 to be put next into the MRO. There is some conflict between the
1062 order in which they should be put in the MRO, but it's hard to
1063 diagnose what constraint can't be satisfied.
1064*/
1065
1066static void
1067set_mro_error(PyObject *to_merge, int *remain)
1068{
1069 int i, n, off, to_merge_size;
1070 char buf[1000];
1071 PyObject *k, *v;
1072 PyObject *set = PyDict_New();
1073
1074 to_merge_size = PyList_GET_SIZE(to_merge);
1075 for (i = 0; i < to_merge_size; i++) {
1076 PyObject *L = PyList_GET_ITEM(to_merge, i);
1077 if (remain[i] < PyList_GET_SIZE(L)) {
1078 PyObject *c = PyList_GET_ITEM(L, remain[i]);
1079 if (PyDict_SetItem(set, c, Py_None) < 0)
1080 return;
1081 }
1082 }
1083 n = PyDict_Size(set);
1084
Raymond Hettinger83245b52003-03-12 04:25:42 +00001085 off = PyOS_snprintf(buf, sizeof(buf), "Cannot create class.\
1086The superclasses have conflicting\n\
1087inheritance trees which leave the method resolution order (MRO)\n\
1088undefined for bases");
Guido van Rossum98f33732002-11-25 21:36:54 +00001089 i = 0;
1090 while (PyDict_Next(set, &i, &k, &v) && off < sizeof(buf)) {
1091 PyObject *name = class_name(k);
1092 off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s",
1093 name ? PyString_AS_STRING(name) : "?");
1094 Py_XDECREF(name);
1095 if (--n && off+1 < sizeof(buf)) {
1096 buf[off++] = ',';
1097 buf[off] = '\0';
1098 }
1099 }
1100 PyErr_SetString(PyExc_TypeError, buf);
1101 Py_DECREF(set);
1102}
1103
Tim Petersea7f75d2002-12-07 21:39:16 +00001104static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001105pmerge(PyObject *acc, PyObject* to_merge) {
1106 int i, j, to_merge_size;
1107 int *remain;
1108 int ok, empty_cnt;
Tim Petersea7f75d2002-12-07 21:39:16 +00001109
Guido van Rossum1f121312002-11-14 19:49:16 +00001110 to_merge_size = PyList_GET_SIZE(to_merge);
1111
Guido van Rossum98f33732002-11-25 21:36:54 +00001112 /* remain stores an index into each sublist of to_merge.
1113 remain[i] is the index of the next base in to_merge[i]
1114 that is not included in acc.
1115 */
Guido van Rossum1f121312002-11-14 19:49:16 +00001116 remain = PyMem_MALLOC(SIZEOF_INT*to_merge_size);
1117 if (remain == NULL)
1118 return -1;
1119 for (i = 0; i < to_merge_size; i++)
1120 remain[i] = 0;
1121
1122 again:
1123 empty_cnt = 0;
1124 for (i = 0; i < to_merge_size; i++) {
1125 PyObject *candidate;
Tim Petersea7f75d2002-12-07 21:39:16 +00001126
Guido van Rossum1f121312002-11-14 19:49:16 +00001127 PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
1128
1129 if (remain[i] >= PyList_GET_SIZE(cur_list)) {
1130 empty_cnt++;
1131 continue;
1132 }
1133
Guido van Rossum98f33732002-11-25 21:36:54 +00001134 /* Choose next candidate for MRO.
1135
1136 The input sequences alone can determine the choice.
1137 If not, choose the class which appears in the MRO
1138 of the earliest direct superclass of the new class.
1139 */
1140
Guido van Rossum1f121312002-11-14 19:49:16 +00001141 candidate = PyList_GET_ITEM(cur_list, remain[i]);
1142 for (j = 0; j < to_merge_size; j++) {
1143 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum98f33732002-11-25 21:36:54 +00001144 if (tail_contains(j_lst, remain[j], candidate)) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001145 goto skip; /* continue outer loop */
Guido van Rossum98f33732002-11-25 21:36:54 +00001146 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001147 }
1148 ok = PyList_Append(acc, candidate);
1149 if (ok < 0) {
1150 PyMem_Free(remain);
1151 return -1;
1152 }
1153 for (j = 0; j < to_merge_size; j++) {
1154 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum768158c2002-12-31 16:33:01 +00001155 if (remain[j] < PyList_GET_SIZE(j_lst) &&
1156 PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001157 remain[j]++;
1158 }
1159 }
1160 goto again;
Tim Peters9a6b8d82002-11-14 23:22:33 +00001161 skip: ;
Guido van Rossum1f121312002-11-14 19:49:16 +00001162 }
1163
Guido van Rossum98f33732002-11-25 21:36:54 +00001164 if (empty_cnt == to_merge_size) {
1165 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001166 return 0;
Guido van Rossum98f33732002-11-25 21:36:54 +00001167 }
1168 set_mro_error(to_merge, remain);
1169 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001170 return -1;
1171}
1172
Tim Peters6d6c1a32001-08-02 04:15:00 +00001173static PyObject *
1174mro_implementation(PyTypeObject *type)
1175{
1176 int i, n, ok;
1177 PyObject *bases, *result;
Guido van Rossum1f121312002-11-14 19:49:16 +00001178 PyObject *to_merge, *bases_aslist;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001179
Guido van Rossum63517572002-06-18 16:44:57 +00001180 if(type->tp_dict == NULL) {
1181 if(PyType_Ready(type) < 0)
1182 return NULL;
1183 }
1184
Guido van Rossum98f33732002-11-25 21:36:54 +00001185 /* Find a superclass linearization that honors the constraints
1186 of the explicit lists of bases and the constraints implied by
Tim Petersea7f75d2002-12-07 21:39:16 +00001187 each base class.
Guido van Rossum98f33732002-11-25 21:36:54 +00001188
1189 to_merge is a list of lists, where each list is a superclass
1190 linearization implied by a base class. The last element of
1191 to_merge is the declared list of bases.
1192 */
1193
Tim Peters6d6c1a32001-08-02 04:15:00 +00001194 bases = type->tp_bases;
1195 n = PyTuple_GET_SIZE(bases);
Guido van Rossum1f121312002-11-14 19:49:16 +00001196
1197 to_merge = PyList_New(n+1);
1198 if (to_merge == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001199 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001200
Tim Peters6d6c1a32001-08-02 04:15:00 +00001201 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001202 PyObject *base = PyTuple_GET_ITEM(bases, i);
1203 PyObject *parentMRO;
1204 if (PyType_Check(base))
1205 parentMRO = PySequence_List(
1206 ((PyTypeObject*)base)->tp_mro);
1207 else
1208 parentMRO = classic_mro(base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001209 if (parentMRO == NULL) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001210 Py_DECREF(to_merge);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001211 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001212 }
1213
1214 PyList_SET_ITEM(to_merge, i, parentMRO);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001215 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001216
1217 bases_aslist = PySequence_List(bases);
1218 if (bases_aslist == NULL) {
1219 Py_DECREF(to_merge);
1220 return NULL;
1221 }
Guido van Rossum98f33732002-11-25 21:36:54 +00001222 /* This is just a basic sanity check. */
1223 if (check_duplicates(bases_aslist) < 0) {
1224 Py_DECREF(to_merge);
1225 Py_DECREF(bases_aslist);
1226 return NULL;
1227 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001228 PyList_SET_ITEM(to_merge, n, bases_aslist);
1229
1230 result = Py_BuildValue("[O]", (PyObject *)type);
1231 if (result == NULL) {
1232 Py_DECREF(to_merge);
1233 return NULL;
1234 }
1235
1236 ok = pmerge(result, to_merge);
1237 Py_DECREF(to_merge);
1238 if (ok < 0) {
1239 Py_DECREF(result);
1240 return NULL;
1241 }
1242
Tim Peters6d6c1a32001-08-02 04:15:00 +00001243 return result;
1244}
1245
1246static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001247mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001248{
1249 PyTypeObject *type = (PyTypeObject *)self;
1250
Tim Peters6d6c1a32001-08-02 04:15:00 +00001251 return mro_implementation(type);
1252}
1253
1254static int
1255mro_internal(PyTypeObject *type)
1256{
1257 PyObject *mro, *result, *tuple;
1258
1259 if (type->ob_type == &PyType_Type) {
1260 result = mro_implementation(type);
1261 }
1262 else {
Guido van Rossum60718732001-08-28 17:47:51 +00001263 static PyObject *mro_str;
1264 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001265 if (mro == NULL)
1266 return -1;
1267 result = PyObject_CallObject(mro, NULL);
1268 Py_DECREF(mro);
1269 }
1270 if (result == NULL)
1271 return -1;
1272 tuple = PySequence_Tuple(result);
1273 Py_DECREF(result);
1274 type->tp_mro = tuple;
1275 return 0;
1276}
1277
1278
1279/* Calculate the best base amongst multiple base classes.
1280 This is the first one that's on the path to the "solid base". */
1281
1282static PyTypeObject *
1283best_base(PyObject *bases)
1284{
1285 int i, n;
1286 PyTypeObject *base, *winner, *candidate, *base_i;
Tim Petersa91e9642001-11-14 23:32:33 +00001287 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001288
1289 assert(PyTuple_Check(bases));
1290 n = PyTuple_GET_SIZE(bases);
1291 assert(n > 0);
Tim Petersa91e9642001-11-14 23:32:33 +00001292 base = NULL;
1293 winner = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001294 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001295 base_proto = PyTuple_GET_ITEM(bases, i);
1296 if (PyClass_Check(base_proto))
1297 continue;
1298 if (!PyType_Check(base_proto)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001299 PyErr_SetString(
1300 PyExc_TypeError,
1301 "bases must be types");
1302 return NULL;
1303 }
Tim Petersa91e9642001-11-14 23:32:33 +00001304 base_i = (PyTypeObject *)base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001305 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001306 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001307 return NULL;
1308 }
1309 candidate = solid_base(base_i);
Tim Petersa91e9642001-11-14 23:32:33 +00001310 if (winner == NULL) {
1311 winner = candidate;
1312 base = base_i;
1313 }
1314 else if (PyType_IsSubtype(winner, candidate))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001315 ;
1316 else if (PyType_IsSubtype(candidate, winner)) {
1317 winner = candidate;
1318 base = base_i;
1319 }
1320 else {
1321 PyErr_SetString(
1322 PyExc_TypeError,
1323 "multiple bases have "
1324 "instance lay-out conflict");
1325 return NULL;
1326 }
1327 }
Guido van Rossume54616c2001-12-14 04:19:56 +00001328 if (base == NULL)
1329 PyErr_SetString(PyExc_TypeError,
1330 "a new-style class can't have only classic bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001331 return base;
1332}
1333
1334static int
1335extra_ivars(PyTypeObject *type, PyTypeObject *base)
1336{
Neil Schemenauerc806c882001-08-29 23:54:54 +00001337 size_t t_size = type->tp_basicsize;
1338 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001339
Guido van Rossum9676b222001-08-17 20:32:36 +00001340 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001341 if (type->tp_itemsize || base->tp_itemsize) {
1342 /* If itemsize is involved, stricter rules */
1343 return t_size != b_size ||
1344 type->tp_itemsize != base->tp_itemsize;
1345 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001346 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
1347 type->tp_weaklistoffset + sizeof(PyObject *) == t_size)
1348 t_size -= sizeof(PyObject *);
1349 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
1350 type->tp_dictoffset + sizeof(PyObject *) == t_size)
1351 t_size -= sizeof(PyObject *);
1352
1353 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001354}
1355
1356static PyTypeObject *
1357solid_base(PyTypeObject *type)
1358{
1359 PyTypeObject *base;
1360
1361 if (type->tp_base)
1362 base = solid_base(type->tp_base);
1363 else
1364 base = &PyBaseObject_Type;
1365 if (extra_ivars(type, base))
1366 return type;
1367 else
1368 return base;
1369}
1370
Jeremy Hylton938ace62002-07-17 16:30:39 +00001371static void object_dealloc(PyObject *);
1372static int object_init(PyObject *, PyObject *, PyObject *);
1373static int update_slot(PyTypeObject *, PyObject *);
1374static void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001375
1376static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001377subtype_dict(PyObject *obj, void *context)
1378{
1379 PyObject **dictptr = _PyObject_GetDictPtr(obj);
1380 PyObject *dict;
1381
1382 if (dictptr == NULL) {
1383 PyErr_SetString(PyExc_AttributeError,
1384 "This object has no __dict__");
1385 return NULL;
1386 }
1387 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +00001388 if (dict == NULL)
1389 *dictptr = dict = PyDict_New();
1390 Py_XINCREF(dict);
1391 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001392}
1393
Guido van Rossum6661be32001-10-26 04:26:12 +00001394static int
1395subtype_setdict(PyObject *obj, PyObject *value, void *context)
1396{
1397 PyObject **dictptr = _PyObject_GetDictPtr(obj);
1398 PyObject *dict;
1399
1400 if (dictptr == NULL) {
1401 PyErr_SetString(PyExc_AttributeError,
1402 "This object has no __dict__");
1403 return -1;
1404 }
Guido van Rossumd331cb52001-12-05 19:46:42 +00001405 if (value != NULL && !PyDict_Check(value)) {
Guido van Rossum6661be32001-10-26 04:26:12 +00001406 PyErr_SetString(PyExc_TypeError,
1407 "__dict__ must be set to a dictionary");
1408 return -1;
1409 }
1410 dict = *dictptr;
Guido van Rossumd331cb52001-12-05 19:46:42 +00001411 Py_XINCREF(value);
Guido van Rossum6661be32001-10-26 04:26:12 +00001412 *dictptr = value;
1413 Py_XDECREF(dict);
1414 return 0;
1415}
1416
Guido van Rossumad47da02002-08-12 19:05:44 +00001417static PyObject *
1418subtype_getweakref(PyObject *obj, void *context)
1419{
1420 PyObject **weaklistptr;
1421 PyObject *result;
1422
1423 if (obj->ob_type->tp_weaklistoffset == 0) {
1424 PyErr_SetString(PyExc_AttributeError,
1425 "This object has no __weaklist__");
1426 return NULL;
1427 }
1428 assert(obj->ob_type->tp_weaklistoffset > 0);
1429 assert(obj->ob_type->tp_weaklistoffset + sizeof(PyObject *) <=
Guido van Rossum3747a0f2002-08-12 19:25:08 +00001430 (size_t)(obj->ob_type->tp_basicsize));
Guido van Rossumad47da02002-08-12 19:05:44 +00001431 weaklistptr = (PyObject **)
Guido van Rossum3747a0f2002-08-12 19:25:08 +00001432 ((char *)obj + obj->ob_type->tp_weaklistoffset);
Guido van Rossumad47da02002-08-12 19:05:44 +00001433 if (*weaklistptr == NULL)
1434 result = Py_None;
1435 else
1436 result = *weaklistptr;
1437 Py_INCREF(result);
1438 return result;
1439}
1440
Guido van Rossum373c7412003-01-07 13:41:37 +00001441/* Three variants on the subtype_getsets list. */
1442
1443static PyGetSetDef subtype_getsets_full[] = {
Guido van Rossumad47da02002-08-12 19:05:44 +00001444 {"__dict__", subtype_dict, subtype_setdict,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001445 PyDoc_STR("dictionary for instance variables (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001446 {"__weakref__", subtype_getweakref, NULL,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001447 PyDoc_STR("list of weak references to the object (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001448 {0}
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001449};
1450
Guido van Rossum373c7412003-01-07 13:41:37 +00001451static PyGetSetDef subtype_getsets_dict_only[] = {
1452 {"__dict__", subtype_dict, subtype_setdict,
1453 PyDoc_STR("dictionary for instance variables (if defined)")},
1454 {0}
1455};
1456
1457static PyGetSetDef subtype_getsets_weakref_only[] = {
1458 {"__weakref__", subtype_getweakref, NULL,
1459 PyDoc_STR("list of weak references to the object (if defined)")},
1460 {0}
1461};
1462
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001463static int
1464valid_identifier(PyObject *s)
1465{
Guido van Rossum03013a02002-07-16 14:30:28 +00001466 unsigned char *p;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001467 int i, n;
1468
1469 if (!PyString_Check(s)) {
1470 PyErr_SetString(PyExc_TypeError,
1471 "__slots__ must be strings");
1472 return 0;
1473 }
Guido van Rossum03013a02002-07-16 14:30:28 +00001474 p = (unsigned char *) PyString_AS_STRING(s);
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001475 n = PyString_GET_SIZE(s);
1476 /* We must reject an empty name. As a hack, we bump the
1477 length to 1 so that the loop will balk on the trailing \0. */
1478 if (n == 0)
1479 n = 1;
1480 for (i = 0; i < n; i++, p++) {
1481 if (!(i == 0 ? isalpha(*p) : isalnum(*p)) && *p != '_') {
1482 PyErr_SetString(PyExc_TypeError,
1483 "__slots__ must be identifiers");
1484 return 0;
1485 }
1486 }
1487 return 1;
1488}
1489
Martin v. Löwisd919a592002-10-14 21:07:28 +00001490#ifdef Py_USING_UNICODE
1491/* Replace Unicode objects in slots. */
1492
1493static PyObject *
1494_unicode_to_string(PyObject *slots, int nslots)
1495{
1496 PyObject *tmp = slots;
1497 PyObject *o, *o1;
1498 int i;
1499 intintargfunc copy = slots->ob_type->tp_as_sequence->sq_slice;
1500 for (i = 0; i < nslots; i++) {
1501 if (PyUnicode_Check(o = PyTuple_GET_ITEM(tmp, i))) {
1502 if (tmp == slots) {
1503 tmp = copy(slots, 0, PyTuple_GET_SIZE(slots));
1504 if (tmp == NULL)
1505 return NULL;
1506 }
1507 o1 = _PyUnicode_AsDefaultEncodedString
1508 (o, NULL);
1509 if (o1 == NULL) {
1510 Py_DECREF(tmp);
1511 return 0;
1512 }
1513 Py_INCREF(o1);
1514 Py_DECREF(o);
1515 PyTuple_SET_ITEM(tmp, i, o1);
1516 }
1517 }
1518 return tmp;
1519}
1520#endif
1521
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001522static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001523type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
1524{
1525 PyObject *name, *bases, *dict;
1526 static char *kwlist[] = {"name", "bases", "dict", 0};
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001527 PyObject *slots, *tmp, *newslots;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001528 PyTypeObject *type, *base, *tmptype, *winner;
Guido van Rossume5c691a2003-03-07 15:13:17 +00001529 PyHeapTypeObject *et;
Guido van Rossum6f799372001-09-20 20:46:19 +00001530 PyMemberDef *mp;
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001531 int i, nbases, nslots, slotoffset, add_dict, add_weak;
Guido van Rossumad47da02002-08-12 19:05:44 +00001532 int j, may_add_dict, may_add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001533
Tim Peters3abca122001-10-27 19:37:48 +00001534 assert(args != NULL && PyTuple_Check(args));
1535 assert(kwds == NULL || PyDict_Check(kwds));
1536
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001537 /* Special case: type(x) should return x->ob_type */
Tim Peters3abca122001-10-27 19:37:48 +00001538 {
1539 const int nargs = PyTuple_GET_SIZE(args);
1540 const int nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
1541
1542 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
1543 PyObject *x = PyTuple_GET_ITEM(args, 0);
1544 Py_INCREF(x->ob_type);
1545 return (PyObject *) x->ob_type;
1546 }
1547
1548 /* SF bug 475327 -- if that didn't trigger, we need 3
1549 arguments. but PyArg_ParseTupleAndKeywords below may give
1550 a msg saying type() needs exactly 3. */
1551 if (nargs + nkwds != 3) {
1552 PyErr_SetString(PyExc_TypeError,
1553 "type() takes 1 or 3 arguments");
1554 return NULL;
1555 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001556 }
1557
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001558 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001559 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
1560 &name,
1561 &PyTuple_Type, &bases,
1562 &PyDict_Type, &dict))
1563 return NULL;
1564
1565 /* Determine the proper metatype to deal with this,
1566 and check for metatype conflicts while we're at it.
1567 Note that if some other metatype wins to contract,
1568 it's possible that its instances are not types. */
1569 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001570 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001571 for (i = 0; i < nbases; i++) {
1572 tmp = PyTuple_GET_ITEM(bases, i);
1573 tmptype = tmp->ob_type;
Tim Petersa91e9642001-11-14 23:32:33 +00001574 if (tmptype == &PyClass_Type)
1575 continue; /* Special case classic classes */
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001576 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001577 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001578 if (PyType_IsSubtype(tmptype, winner)) {
1579 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001580 continue;
1581 }
1582 PyErr_SetString(PyExc_TypeError,
1583 "metatype conflict among bases");
1584 return NULL;
1585 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001586 if (winner != metatype) {
1587 if (winner->tp_new != type_new) /* Pass it to the winner */
1588 return winner->tp_new(winner, args, kwds);
1589 metatype = winner;
1590 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001591
1592 /* Adjust for empty tuple bases */
1593 if (nbases == 0) {
1594 bases = Py_BuildValue("(O)", &PyBaseObject_Type);
1595 if (bases == NULL)
1596 return NULL;
1597 nbases = 1;
1598 }
1599 else
1600 Py_INCREF(bases);
1601
1602 /* XXX From here until type is allocated, "return NULL" leaks bases! */
1603
1604 /* Calculate best base, and check that all bases are type objects */
1605 base = best_base(bases);
1606 if (base == NULL)
1607 return NULL;
1608 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
1609 PyErr_Format(PyExc_TypeError,
1610 "type '%.100s' is not an acceptable base type",
1611 base->tp_name);
1612 return NULL;
1613 }
1614
Tim Peters6d6c1a32001-08-02 04:15:00 +00001615 /* Check for a __slots__ sequence variable in dict, and count it */
1616 slots = PyDict_GetItemString(dict, "__slots__");
1617 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +00001618 add_dict = 0;
1619 add_weak = 0;
Guido van Rossumad47da02002-08-12 19:05:44 +00001620 may_add_dict = base->tp_dictoffset == 0;
1621 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
1622 if (slots == NULL) {
1623 if (may_add_dict) {
1624 add_dict++;
1625 }
1626 if (may_add_weak) {
1627 add_weak++;
1628 }
1629 }
1630 else {
1631 /* Have slots */
1632
Tim Peters6d6c1a32001-08-02 04:15:00 +00001633 /* Make it into a tuple */
1634 if (PyString_Check(slots))
1635 slots = Py_BuildValue("(O)", slots);
1636 else
1637 slots = PySequence_Tuple(slots);
1638 if (slots == NULL)
1639 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00001640 assert(PyTuple_Check(slots));
1641
1642 /* Are slots allowed? */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001643 nslots = PyTuple_GET_SIZE(slots);
Guido van Rossume5c691a2003-03-07 15:13:17 +00001644 if (nslots > 0 && base->tp_itemsize != 0 && !PyType_Check(base)) {
1645 /* for the special case of meta types, allow slots */
Guido van Rossumc4141872001-08-30 04:43:35 +00001646 PyErr_Format(PyExc_TypeError,
1647 "nonempty __slots__ "
1648 "not supported for subtype of '%s'",
1649 base->tp_name);
Guido van Rossumad47da02002-08-12 19:05:44 +00001650 bad_slots:
1651 Py_DECREF(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +00001652 return NULL;
1653 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001654
Martin v. Löwisd919a592002-10-14 21:07:28 +00001655#ifdef Py_USING_UNICODE
1656 tmp = _unicode_to_string(slots, nslots);
Martin v. Löwis13b1a5c2002-10-14 21:11:34 +00001657 if (tmp != slots) {
1658 Py_DECREF(slots);
1659 slots = tmp;
1660 }
Martin v. Löwisd919a592002-10-14 21:07:28 +00001661 if (!tmp)
1662 return NULL;
1663#endif
Guido van Rossumad47da02002-08-12 19:05:44 +00001664 /* Check for valid slot names and two special cases */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001665 for (i = 0; i < nslots; i++) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001666 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
1667 char *s;
1668 if (!valid_identifier(tmp))
1669 goto bad_slots;
1670 assert(PyString_Check(tmp));
1671 s = PyString_AS_STRING(tmp);
1672 if (strcmp(s, "__dict__") == 0) {
1673 if (!may_add_dict || add_dict) {
1674 PyErr_SetString(PyExc_TypeError,
1675 "__dict__ slot disallowed: "
1676 "we already got one");
1677 goto bad_slots;
1678 }
1679 add_dict++;
1680 }
1681 if (strcmp(s, "__weakref__") == 0) {
1682 if (!may_add_weak || add_weak) {
1683 PyErr_SetString(PyExc_TypeError,
1684 "__weakref__ slot disallowed: "
1685 "either we already got one, "
1686 "or __itemsize__ != 0");
1687 goto bad_slots;
1688 }
1689 add_weak++;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001690 }
1691 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001692
Guido van Rossumad47da02002-08-12 19:05:44 +00001693 /* Copy slots into yet another tuple, demangling names */
1694 newslots = PyTuple_New(nslots - add_dict - add_weak);
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001695 if (newslots == NULL)
Guido van Rossumad47da02002-08-12 19:05:44 +00001696 goto bad_slots;
1697 for (i = j = 0; i < nslots; i++) {
1698 char *s;
Guido van Rossum8e829202002-08-16 03:47:49 +00001699 char buffer[256];
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001700 tmp = PyTuple_GET_ITEM(slots, i);
Guido van Rossumad47da02002-08-12 19:05:44 +00001701 s = PyString_AS_STRING(tmp);
1702 if ((add_dict && strcmp(s, "__dict__") == 0) ||
1703 (add_weak && strcmp(s, "__weakref__") == 0))
1704 continue;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001705 if (_Py_Mangle(PyString_AS_STRING(name),
Guido van Rossumad47da02002-08-12 19:05:44 +00001706 PyString_AS_STRING(tmp),
1707 buffer, sizeof(buffer)))
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001708 {
1709 tmp = PyString_FromString(buffer);
1710 } else {
1711 Py_INCREF(tmp);
1712 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001713 PyTuple_SET_ITEM(newslots, j, tmp);
1714 j++;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001715 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001716 assert(j == nslots - add_dict - add_weak);
1717 nslots = j;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001718 Py_DECREF(slots);
1719 slots = newslots;
1720
Guido van Rossumad47da02002-08-12 19:05:44 +00001721 /* Secondary bases may provide weakrefs or dict */
1722 if (nbases > 1 &&
1723 ((may_add_dict && !add_dict) ||
1724 (may_add_weak && !add_weak))) {
1725 for (i = 0; i < nbases; i++) {
1726 tmp = PyTuple_GET_ITEM(bases, i);
1727 if (tmp == (PyObject *)base)
1728 continue; /* Skip primary base */
1729 if (PyClass_Check(tmp)) {
1730 /* Classic base class provides both */
1731 if (may_add_dict && !add_dict)
1732 add_dict++;
1733 if (may_add_weak && !add_weak)
1734 add_weak++;
1735 break;
1736 }
1737 assert(PyType_Check(tmp));
1738 tmptype = (PyTypeObject *)tmp;
1739 if (may_add_dict && !add_dict &&
1740 tmptype->tp_dictoffset != 0)
1741 add_dict++;
1742 if (may_add_weak && !add_weak &&
1743 tmptype->tp_weaklistoffset != 0)
1744 add_weak++;
1745 if (may_add_dict && !add_dict)
1746 continue;
1747 if (may_add_weak && !add_weak)
1748 continue;
1749 /* Nothing more to check */
1750 break;
1751 }
1752 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001753 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001754
1755 /* XXX From here until type is safely allocated,
1756 "return NULL" may leak slots! */
1757
1758 /* Allocate the type object */
1759 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
Guido van Rossumad47da02002-08-12 19:05:44 +00001760 if (type == NULL) {
1761 Py_XDECREF(slots);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001762 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00001763 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001764
1765 /* Keep name and slots alive in the extended type object */
Guido van Rossume5c691a2003-03-07 15:13:17 +00001766 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001767 Py_INCREF(name);
1768 et->name = name;
1769 et->slots = slots;
1770
Guido van Rossumdc91b992001-08-08 22:26:22 +00001771 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001772 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
1773 Py_TPFLAGS_BASETYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00001774 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
1775 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00001776
1777 /* It's a new-style number unless it specifically inherits any
1778 old-style numeric behavior */
1779 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
1780 (base->tp_as_number == NULL))
1781 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
1782
1783 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001784 type->tp_as_number = &et->as_number;
1785 type->tp_as_sequence = &et->as_sequence;
1786 type->tp_as_mapping = &et->as_mapping;
1787 type->tp_as_buffer = &et->as_buffer;
1788 type->tp_name = PyString_AS_STRING(name);
1789
1790 /* Set tp_base and tp_bases */
1791 type->tp_bases = bases;
1792 Py_INCREF(base);
1793 type->tp_base = base;
1794
Guido van Rossum687ae002001-10-15 22:03:32 +00001795 /* Initialize tp_dict from passed-in dict */
1796 type->tp_dict = dict = PyDict_Copy(dict);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001797 if (dict == NULL) {
1798 Py_DECREF(type);
1799 return NULL;
1800 }
1801
Guido van Rossumc3542212001-08-16 09:18:56 +00001802 /* Set __module__ in the dict */
1803 if (PyDict_GetItemString(dict, "__module__") == NULL) {
1804 tmp = PyEval_GetGlobals();
1805 if (tmp != NULL) {
1806 tmp = PyDict_GetItemString(tmp, "__name__");
1807 if (tmp != NULL) {
1808 if (PyDict_SetItemString(dict, "__module__",
1809 tmp) < 0)
1810 return NULL;
1811 }
1812 }
1813 }
1814
Tim Peters2f93e282001-10-04 05:27:00 +00001815 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
Tim Peters24008312002-03-17 18:56:20 +00001816 and is a string. The __doc__ accessor will first look for tp_doc;
1817 if that fails, it will still look into __dict__.
Tim Peters2f93e282001-10-04 05:27:00 +00001818 */
1819 {
1820 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
1821 if (doc != NULL && PyString_Check(doc)) {
1822 const size_t n = (size_t)PyString_GET_SIZE(doc);
Tim Peters59f809d2001-10-04 05:43:02 +00001823 type->tp_doc = (char *)PyObject_MALLOC(n+1);
Tim Peters2f93e282001-10-04 05:27:00 +00001824 if (type->tp_doc == NULL) {
1825 Py_DECREF(type);
1826 return NULL;
1827 }
1828 memcpy(type->tp_doc, PyString_AS_STRING(doc), n+1);
1829 }
1830 }
1831
Tim Peters6d6c1a32001-08-02 04:15:00 +00001832 /* Special-case __new__: if it's a plain function,
1833 make it a static function */
1834 tmp = PyDict_GetItemString(dict, "__new__");
1835 if (tmp != NULL && PyFunction_Check(tmp)) {
1836 tmp = PyStaticMethod_New(tmp);
1837 if (tmp == NULL) {
1838 Py_DECREF(type);
1839 return NULL;
1840 }
1841 PyDict_SetItemString(dict, "__new__", tmp);
1842 Py_DECREF(tmp);
1843 }
1844
1845 /* Add descriptors for custom slots from __slots__, or for __dict__ */
Guido van Rossume5c691a2003-03-07 15:13:17 +00001846 mp = PyHeapType_GET_MEMBERS(et);
Neil Schemenauerc806c882001-08-29 23:54:54 +00001847 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001848 if (slots != NULL) {
1849 for (i = 0; i < nslots; i++, mp++) {
1850 mp->name = PyString_AS_STRING(
1851 PyTuple_GET_ITEM(slots, i));
Guido van Rossum64b206c2001-12-04 17:13:22 +00001852 mp->type = T_OBJECT_EX;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001853 mp->offset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +00001854 if (base->tp_weaklistoffset == 0 &&
Guido van Rossum64b206c2001-12-04 17:13:22 +00001855 strcmp(mp->name, "__weakref__") == 0) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001856 add_weak++;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001857 mp->type = T_OBJECT;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001858 mp->flags = READONLY;
Guido van Rossum9676b222001-08-17 20:32:36 +00001859 type->tp_weaklistoffset = slotoffset;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001860 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001861 slotoffset += sizeof(PyObject *);
1862 }
1863 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001864 if (add_dict) {
1865 if (base->tp_itemsize)
1866 type->tp_dictoffset = -(long)sizeof(PyObject *);
1867 else
1868 type->tp_dictoffset = slotoffset;
1869 slotoffset += sizeof(PyObject *);
1870 }
1871 if (add_weak) {
1872 assert(!base->tp_itemsize);
1873 type->tp_weaklistoffset = slotoffset;
1874 slotoffset += sizeof(PyObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001875 }
1876 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001877 type->tp_itemsize = base->tp_itemsize;
Guido van Rossume5c691a2003-03-07 15:13:17 +00001878 type->tp_members = PyHeapType_GET_MEMBERS(et);
Guido van Rossum373c7412003-01-07 13:41:37 +00001879
1880 if (type->tp_weaklistoffset && type->tp_dictoffset)
1881 type->tp_getset = subtype_getsets_full;
1882 else if (type->tp_weaklistoffset && !type->tp_dictoffset)
1883 type->tp_getset = subtype_getsets_weakref_only;
1884 else if (!type->tp_weaklistoffset && type->tp_dictoffset)
1885 type->tp_getset = subtype_getsets_dict_only;
1886 else
1887 type->tp_getset = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001888
1889 /* Special case some slots */
1890 if (type->tp_dictoffset != 0 || nslots > 0) {
1891 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
1892 type->tp_getattro = PyObject_GenericGetAttr;
1893 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
1894 type->tp_setattro = PyObject_GenericSetAttr;
1895 }
1896 type->tp_dealloc = subtype_dealloc;
1897
Guido van Rossum9475a232001-10-05 20:51:39 +00001898 /* Enable GC unless there are really no instance variables possible */
1899 if (!(type->tp_basicsize == sizeof(PyObject) &&
1900 type->tp_itemsize == 0))
1901 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
1902
Tim Peters6d6c1a32001-08-02 04:15:00 +00001903 /* Always override allocation strategy to use regular heap */
1904 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00001905 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001906 type->tp_free = PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00001907 type->tp_traverse = subtype_traverse;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001908 type->tp_clear = subtype_clear;
Guido van Rossum048eb752001-10-02 21:24:57 +00001909 }
1910 else
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001911 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001912
1913 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001914 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001915 Py_DECREF(type);
1916 return NULL;
1917 }
1918
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001919 /* Put the proper slots in place */
1920 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00001921
Tim Peters6d6c1a32001-08-02 04:15:00 +00001922 return (PyObject *)type;
1923}
1924
1925/* Internal API to look for a name through the MRO.
1926 This returns a borrowed reference, and doesn't set an exception! */
1927PyObject *
1928_PyType_Lookup(PyTypeObject *type, PyObject *name)
1929{
1930 int i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00001931 PyObject *mro, *res, *base, *dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001932
Guido van Rossum687ae002001-10-15 22:03:32 +00001933 /* Look in tp_dict of types in MRO */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001934 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00001935
1936 /* If mro is NULL, the type is either not yet initialized
1937 by PyType_Ready(), or already cleared by type_clear().
1938 Either way the safest thing to do is to return NULL. */
1939 if (mro == NULL)
1940 return NULL;
1941
Tim Peters6d6c1a32001-08-02 04:15:00 +00001942 assert(PyTuple_Check(mro));
1943 n = PyTuple_GET_SIZE(mro);
1944 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001945 base = PyTuple_GET_ITEM(mro, i);
1946 if (PyClass_Check(base))
1947 dict = ((PyClassObject *)base)->cl_dict;
1948 else {
1949 assert(PyType_Check(base));
1950 dict = ((PyTypeObject *)base)->tp_dict;
1951 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001952 assert(dict && PyDict_Check(dict));
1953 res = PyDict_GetItem(dict, name);
1954 if (res != NULL)
1955 return res;
1956 }
1957 return NULL;
1958}
1959
1960/* This is similar to PyObject_GenericGetAttr(),
1961 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
1962static PyObject *
1963type_getattro(PyTypeObject *type, PyObject *name)
1964{
1965 PyTypeObject *metatype = type->ob_type;
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001966 PyObject *meta_attribute, *attribute;
1967 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001968
1969 /* Initialize this type (we'll assume the metatype is initialized) */
1970 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001971 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001972 return NULL;
1973 }
1974
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001975 /* No readable descriptor found yet */
1976 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00001977
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001978 /* Look for the attribute in the metatype */
1979 meta_attribute = _PyType_Lookup(metatype, name);
1980
1981 if (meta_attribute != NULL) {
1982 meta_get = meta_attribute->ob_type->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00001983
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001984 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
1985 /* Data descriptors implement tp_descr_set to intercept
1986 * writes. Assume the attribute is not overridden in
1987 * type's tp_dict (and bases): call the descriptor now.
1988 */
1989 return meta_get(meta_attribute, (PyObject *)type,
1990 (PyObject *)metatype);
1991 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001992 }
1993
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001994 /* No data descriptor found on metatype. Look in tp_dict of this
1995 * type and its bases */
1996 attribute = _PyType_Lookup(type, name);
1997 if (attribute != NULL) {
1998 /* Implement descriptor functionality, if any */
1999 descrgetfunc local_get = attribute->ob_type->tp_descr_get;
2000 if (local_get != NULL) {
2001 /* NULL 2nd argument indicates the descriptor was
2002 * found on the target object itself (or a base) */
2003 return local_get(attribute, (PyObject *)NULL,
2004 (PyObject *)type);
2005 }
Tim Peters34592512002-07-11 06:23:50 +00002006
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002007 Py_INCREF(attribute);
2008 return attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002009 }
2010
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002011 /* No attribute found in local __dict__ (or bases): use the
2012 * descriptor from the metatype, if any */
2013 if (meta_get != NULL)
2014 return meta_get(meta_attribute, (PyObject *)type,
2015 (PyObject *)metatype);
2016
2017 /* If an ordinary attribute was found on the metatype, return it now */
2018 if (meta_attribute != NULL) {
2019 Py_INCREF(meta_attribute);
2020 return meta_attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002021 }
2022
2023 /* Give up */
2024 PyErr_Format(PyExc_AttributeError,
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002025 "type object '%.50s' has no attribute '%.400s'",
2026 type->tp_name, PyString_AS_STRING(name));
Tim Peters6d6c1a32001-08-02 04:15:00 +00002027 return NULL;
2028}
2029
2030static int
2031type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
2032{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002033 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2034 PyErr_Format(
2035 PyExc_TypeError,
2036 "can't set attributes of built-in/extension type '%s'",
2037 type->tp_name);
2038 return -1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002039 }
Guido van Rossum8d24ee92003-03-24 23:49:49 +00002040 /* XXX Example of how I expect this to be used...
2041 if (update_subclasses(type, name, invalidate_cache, NULL) < 0)
2042 return -1;
2043 */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002044 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
2045 return -1;
2046 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002047}
2048
2049static void
2050type_dealloc(PyTypeObject *type)
2051{
Guido van Rossume5c691a2003-03-07 15:13:17 +00002052 PyHeapTypeObject *et;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002053
2054 /* Assert this is a heap-allocated type object */
2055 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002056 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00002057 PyObject_ClearWeakRefs((PyObject *)type);
Guido van Rossume5c691a2003-03-07 15:13:17 +00002058 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002059 Py_XDECREF(type->tp_base);
2060 Py_XDECREF(type->tp_dict);
2061 Py_XDECREF(type->tp_bases);
2062 Py_XDECREF(type->tp_mro);
Guido van Rossum687ae002001-10-15 22:03:32 +00002063 Py_XDECREF(type->tp_cache);
Guido van Rossum1c450732001-10-08 15:18:27 +00002064 Py_XDECREF(type->tp_subclasses);
Neal Norwitzcee5ca02002-07-30 00:42:06 +00002065 PyObject_Free(type->tp_doc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002066 Py_XDECREF(et->name);
2067 Py_XDECREF(et->slots);
2068 type->ob_type->tp_free((PyObject *)type);
2069}
2070
Guido van Rossum1c450732001-10-08 15:18:27 +00002071static PyObject *
2072type_subclasses(PyTypeObject *type, PyObject *args_ignored)
2073{
2074 PyObject *list, *raw, *ref;
2075 int i, n;
2076
2077 list = PyList_New(0);
2078 if (list == NULL)
2079 return NULL;
2080 raw = type->tp_subclasses;
2081 if (raw == NULL)
2082 return list;
2083 assert(PyList_Check(raw));
2084 n = PyList_GET_SIZE(raw);
2085 for (i = 0; i < n; i++) {
2086 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00002087 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00002088 ref = PyWeakref_GET_OBJECT(ref);
2089 if (ref != Py_None) {
2090 if (PyList_Append(list, ref) < 0) {
2091 Py_DECREF(list);
2092 return NULL;
2093 }
2094 }
2095 }
2096 return list;
2097}
2098
Tim Peters6d6c1a32001-08-02 04:15:00 +00002099static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002100 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002101 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
Guido van Rossum1c450732001-10-08 15:18:27 +00002102 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002103 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002104 {0}
2105};
2106
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002107PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002108"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002109"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002110
Guido van Rossum048eb752001-10-02 21:24:57 +00002111static int
2112type_traverse(PyTypeObject *type, visitproc visit, void *arg)
2113{
Guido van Rossum048eb752001-10-02 21:24:57 +00002114 int err;
2115
Guido van Rossuma3862092002-06-10 15:24:42 +00002116 /* Because of type_is_gc(), the collector only calls this
2117 for heaptypes. */
2118 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002119
2120#define VISIT(SLOT) \
2121 if (SLOT) { \
2122 err = visit((PyObject *)(SLOT), arg); \
2123 if (err) \
2124 return err; \
2125 }
2126
2127 VISIT(type->tp_dict);
Guido van Rossum687ae002001-10-15 22:03:32 +00002128 VISIT(type->tp_cache);
Guido van Rossum048eb752001-10-02 21:24:57 +00002129 VISIT(type->tp_mro);
2130 VISIT(type->tp_bases);
2131 VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00002132
2133 /* There's no need to visit type->tp_subclasses or
Guido van Rossume5c691a2003-03-07 15:13:17 +00002134 ((PyHeapTypeObject *)type)->slots, because they can't be involved
Guido van Rossuma3862092002-06-10 15:24:42 +00002135 in cycles; tp_subclasses is a list of weak references,
2136 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00002137
2138#undef VISIT
2139
2140 return 0;
2141}
2142
2143static int
2144type_clear(PyTypeObject *type)
2145{
Guido van Rossum048eb752001-10-02 21:24:57 +00002146 PyObject *tmp;
2147
Guido van Rossuma3862092002-06-10 15:24:42 +00002148 /* Because of type_is_gc(), the collector only calls this
2149 for heaptypes. */
2150 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002151
2152#define CLEAR(SLOT) \
2153 if (SLOT) { \
2154 tmp = (PyObject *)(SLOT); \
2155 SLOT = NULL; \
2156 Py_DECREF(tmp); \
2157 }
2158
Guido van Rossuma3862092002-06-10 15:24:42 +00002159 /* The only field we need to clear is tp_mro, which is part of a
2160 hard cycle (its first element is the class itself) that won't
2161 be broken otherwise (it's a tuple and tuples don't have a
2162 tp_clear handler). None of the other fields need to be
2163 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00002164
Guido van Rossuma3862092002-06-10 15:24:42 +00002165 tp_dict:
2166 It is a dict, so the collector will call its tp_clear.
2167
2168 tp_cache:
2169 Not used; if it were, it would be a dict.
2170
2171 tp_bases, tp_base:
2172 If these are involved in a cycle, there must be at least
2173 one other, mutable object in the cycle, e.g. a base
2174 class's dict; the cycle will be broken that way.
2175
2176 tp_subclasses:
2177 A list of weak references can't be part of a cycle; and
2178 lists have their own tp_clear.
2179
Guido van Rossume5c691a2003-03-07 15:13:17 +00002180 slots (in PyHeapTypeObject):
Guido van Rossuma3862092002-06-10 15:24:42 +00002181 A tuple of strings can't be part of a cycle.
2182 */
2183
2184 CLEAR(type->tp_mro);
Tim Peters2f93e282001-10-04 05:27:00 +00002185
Guido van Rossum048eb752001-10-02 21:24:57 +00002186#undef CLEAR
2187
2188 return 0;
2189}
2190
2191static int
2192type_is_gc(PyTypeObject *type)
2193{
2194 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
2195}
2196
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002197PyTypeObject PyType_Type = {
2198 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002199 0, /* ob_size */
2200 "type", /* tp_name */
Guido van Rossume5c691a2003-03-07 15:13:17 +00002201 sizeof(PyHeapTypeObject), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00002202 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002203 (destructor)type_dealloc, /* tp_dealloc */
2204 0, /* tp_print */
2205 0, /* tp_getattr */
2206 0, /* tp_setattr */
2207 type_compare, /* tp_compare */
2208 (reprfunc)type_repr, /* tp_repr */
2209 0, /* tp_as_number */
2210 0, /* tp_as_sequence */
2211 0, /* tp_as_mapping */
2212 (hashfunc)_Py_HashPointer, /* tp_hash */
2213 (ternaryfunc)type_call, /* tp_call */
2214 0, /* tp_str */
2215 (getattrofunc)type_getattro, /* tp_getattro */
2216 (setattrofunc)type_setattro, /* tp_setattro */
2217 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00002218 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2219 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002220 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00002221 (traverseproc)type_traverse, /* tp_traverse */
2222 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002223 0, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00002224 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002225 0, /* tp_iter */
2226 0, /* tp_iternext */
2227 type_methods, /* tp_methods */
2228 type_members, /* tp_members */
2229 type_getsets, /* tp_getset */
2230 0, /* tp_base */
2231 0, /* tp_dict */
2232 0, /* tp_descr_get */
2233 0, /* tp_descr_set */
2234 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
2235 0, /* tp_init */
2236 0, /* tp_alloc */
2237 type_new, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002238 PyObject_GC_Del, /* tp_free */
Guido van Rossum048eb752001-10-02 21:24:57 +00002239 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002240};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002241
2242
2243/* The base type of all types (eventually)... except itself. */
2244
2245static int
2246object_init(PyObject *self, PyObject *args, PyObject *kwds)
2247{
2248 return 0;
2249}
2250
Guido van Rossum298e4212003-02-13 16:30:16 +00002251/* If we don't have a tp_new for a new-style class, new will use this one.
2252 Therefore this should take no arguments/keywords. However, this new may
2253 also be inherited by objects that define a tp_init but no tp_new. These
2254 objects WILL pass argumets to tp_new, because it gets the same args as
2255 tp_init. So only allow arguments if we aren't using the default init, in
2256 which case we expect init to handle argument parsing. */
2257static PyObject *
2258object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2259{
2260 if (type->tp_init == object_init && (PyTuple_GET_SIZE(args) ||
2261 (kwds && PyDict_Check(kwds) && PyDict_Size(kwds)))) {
2262 PyErr_SetString(PyExc_TypeError,
2263 "default __new__ takes no parameters");
2264 return NULL;
2265 }
2266 return type->tp_alloc(type, 0);
2267}
2268
Tim Peters6d6c1a32001-08-02 04:15:00 +00002269static void
2270object_dealloc(PyObject *self)
2271{
2272 self->ob_type->tp_free(self);
2273}
2274
Guido van Rossum8e248182001-08-12 05:17:56 +00002275static PyObject *
2276object_repr(PyObject *self)
2277{
Guido van Rossum76e69632001-08-16 18:52:43 +00002278 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00002279 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002280
Guido van Rossum76e69632001-08-16 18:52:43 +00002281 type = self->ob_type;
2282 mod = type_module(type, NULL);
2283 if (mod == NULL)
2284 PyErr_Clear();
2285 else if (!PyString_Check(mod)) {
2286 Py_DECREF(mod);
2287 mod = NULL;
2288 }
2289 name = type_name(type, NULL);
2290 if (name == NULL)
2291 return NULL;
2292 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002293 rtn = PyString_FromFormat("<%s.%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002294 PyString_AS_STRING(mod),
2295 PyString_AS_STRING(name),
2296 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002297 else
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002298 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002299 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002300 Py_XDECREF(mod);
2301 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00002302 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002303}
2304
Guido van Rossumb8f63662001-08-15 23:57:02 +00002305static PyObject *
2306object_str(PyObject *self)
2307{
2308 unaryfunc f;
2309
2310 f = self->ob_type->tp_repr;
2311 if (f == NULL)
2312 f = object_repr;
2313 return f(self);
2314}
2315
Guido van Rossum8e248182001-08-12 05:17:56 +00002316static long
2317object_hash(PyObject *self)
2318{
2319 return _Py_HashPointer(self);
2320}
Guido van Rossum8e248182001-08-12 05:17:56 +00002321
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002322static PyObject *
2323object_get_class(PyObject *self, void *closure)
2324{
2325 Py_INCREF(self->ob_type);
2326 return (PyObject *)(self->ob_type);
2327}
2328
2329static int
2330equiv_structs(PyTypeObject *a, PyTypeObject *b)
2331{
2332 return a == b ||
2333 (a != NULL &&
2334 b != NULL &&
2335 a->tp_basicsize == b->tp_basicsize &&
2336 a->tp_itemsize == b->tp_itemsize &&
2337 a->tp_dictoffset == b->tp_dictoffset &&
2338 a->tp_weaklistoffset == b->tp_weaklistoffset &&
2339 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
2340 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
2341}
2342
2343static int
2344same_slots_added(PyTypeObject *a, PyTypeObject *b)
2345{
2346 PyTypeObject *base = a->tp_base;
2347 int size;
2348
2349 if (base != b->tp_base)
2350 return 0;
2351 if (equiv_structs(a, base) && equiv_structs(b, base))
2352 return 1;
2353 size = base->tp_basicsize;
2354 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
2355 size += sizeof(PyObject *);
2356 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
2357 size += sizeof(PyObject *);
2358 return size == a->tp_basicsize && size == b->tp_basicsize;
2359}
2360
2361static int
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002362compatible_for_assignment(PyTypeObject* old, PyTypeObject* new, char* attr)
2363{
2364 PyTypeObject *newbase, *oldbase;
2365
2366 if (new->tp_dealloc != old->tp_dealloc ||
2367 new->tp_free != old->tp_free)
2368 {
2369 PyErr_Format(PyExc_TypeError,
2370 "%s assignment: "
2371 "'%s' deallocator differs from '%s'",
2372 attr,
2373 new->tp_name,
2374 old->tp_name);
2375 return 0;
2376 }
2377 newbase = new;
2378 oldbase = old;
2379 while (equiv_structs(newbase, newbase->tp_base))
2380 newbase = newbase->tp_base;
2381 while (equiv_structs(oldbase, oldbase->tp_base))
2382 oldbase = oldbase->tp_base;
2383 if (newbase != oldbase &&
2384 (newbase->tp_base != oldbase->tp_base ||
2385 !same_slots_added(newbase, oldbase))) {
2386 PyErr_Format(PyExc_TypeError,
2387 "%s assignment: "
2388 "'%s' object layout differs from '%s'",
2389 attr,
2390 new->tp_name,
2391 old->tp_name);
2392 return 0;
2393 }
Tim Petersea7f75d2002-12-07 21:39:16 +00002394
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002395 return 1;
2396}
2397
2398static int
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002399object_set_class(PyObject *self, PyObject *value, void *closure)
2400{
2401 PyTypeObject *old = self->ob_type;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002402 PyTypeObject *new;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002403
Guido van Rossumb6b89422002-04-15 01:03:30 +00002404 if (value == NULL) {
2405 PyErr_SetString(PyExc_TypeError,
2406 "can't delete __class__ attribute");
2407 return -1;
2408 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002409 if (!PyType_Check(value)) {
2410 PyErr_Format(PyExc_TypeError,
2411 "__class__ must be set to new-style class, not '%s' object",
2412 value->ob_type->tp_name);
2413 return -1;
2414 }
2415 new = (PyTypeObject *)value;
Guido van Rossum40af8892002-08-10 05:42:07 +00002416 if (!(new->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
2417 !(old->tp_flags & Py_TPFLAGS_HEAPTYPE))
2418 {
2419 PyErr_Format(PyExc_TypeError,
2420 "__class__ assignment: only for heap types");
2421 return -1;
2422 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002423 if (compatible_for_assignment(new, old, "__class__")) {
2424 Py_INCREF(new);
2425 self->ob_type = new;
2426 Py_DECREF(old);
2427 return 0;
2428 }
2429 else {
Guido van Rossum9ee4b942002-05-24 18:47:47 +00002430 return -1;
2431 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002432}
2433
2434static PyGetSetDef object_getsets[] = {
2435 {"__class__", object_get_class, object_set_class,
Neal Norwitz858e34f2002-08-13 17:18:45 +00002436 PyDoc_STR("the object's class")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002437 {0}
2438};
2439
Guido van Rossumc53f0092003-02-18 22:05:12 +00002440
Guido van Rossum036f9992003-02-21 22:02:54 +00002441/* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
2442 We fall back to helpers in copy_reg for:
2443 - pickle protocols < 2
2444 - calculating the list of slot names (done only once per class)
2445 - the __newobj__ function (which is used as a token but never called)
2446*/
2447
2448static PyObject *
2449import_copy_reg(void)
2450{
2451 static PyObject *copy_reg_str;
Guido van Rossum3926a632001-09-25 16:25:58 +00002452
2453 if (!copy_reg_str) {
2454 copy_reg_str = PyString_InternFromString("copy_reg");
2455 if (copy_reg_str == NULL)
2456 return NULL;
2457 }
Guido van Rossum036f9992003-02-21 22:02:54 +00002458
2459 return PyImport_Import(copy_reg_str);
2460}
2461
2462static PyObject *
2463slotnames(PyObject *cls)
2464{
2465 PyObject *clsdict;
2466 PyObject *copy_reg;
2467 PyObject *slotnames;
2468
2469 if (!PyType_Check(cls)) {
2470 Py_INCREF(Py_None);
2471 return Py_None;
2472 }
2473
2474 clsdict = ((PyTypeObject *)cls)->tp_dict;
2475 slotnames = PyDict_GetItemString(clsdict, "__slotnames__");
2476 if (slotnames != NULL) {
2477 Py_INCREF(slotnames);
2478 return slotnames;
2479 }
2480
2481 copy_reg = import_copy_reg();
2482 if (copy_reg == NULL)
2483 return NULL;
2484
2485 slotnames = PyObject_CallMethod(copy_reg, "_slotnames", "O", cls);
2486 Py_DECREF(copy_reg);
2487 if (slotnames != NULL &&
2488 slotnames != Py_None &&
2489 !PyList_Check(slotnames))
2490 {
2491 PyErr_SetString(PyExc_TypeError,
2492 "copy_reg._slotnames didn't return a list or None");
2493 Py_DECREF(slotnames);
2494 slotnames = NULL;
2495 }
2496
2497 return slotnames;
2498}
2499
2500static PyObject *
2501reduce_2(PyObject *obj)
2502{
2503 PyObject *cls, *getnewargs;
2504 PyObject *args = NULL, *args2 = NULL;
2505 PyObject *getstate = NULL, *state = NULL, *names = NULL;
2506 PyObject *slots = NULL, *listitems = NULL, *dictitems = NULL;
2507 PyObject *copy_reg = NULL, *newobj = NULL, *res = NULL;
2508 int i, n;
2509
2510 cls = PyObject_GetAttrString(obj, "__class__");
2511 if (cls == NULL)
2512 return NULL;
2513
2514 getnewargs = PyObject_GetAttrString(obj, "__getnewargs__");
2515 if (getnewargs != NULL) {
2516 args = PyObject_CallObject(getnewargs, NULL);
2517 Py_DECREF(getnewargs);
2518 if (args != NULL && !PyTuple_Check(args)) {
2519 PyErr_SetString(PyExc_TypeError,
2520 "__getnewargs__ should return a tuple");
2521 goto end;
2522 }
2523 }
2524 else {
2525 PyErr_Clear();
2526 args = PyTuple_New(0);
2527 }
2528 if (args == NULL)
2529 goto end;
2530
2531 getstate = PyObject_GetAttrString(obj, "__getstate__");
2532 if (getstate != NULL) {
2533 state = PyObject_CallObject(getstate, NULL);
2534 Py_DECREF(getstate);
2535 }
2536 else {
2537 state = PyObject_GetAttrString(obj, "__dict__");
2538 if (state == NULL) {
2539 PyErr_Clear();
2540 state = Py_None;
2541 Py_INCREF(state);
2542 }
2543 names = slotnames(cls);
2544 if (names == NULL)
2545 goto end;
2546 if (names != Py_None) {
2547 assert(PyList_Check(names));
2548 slots = PyDict_New();
2549 if (slots == NULL)
2550 goto end;
2551 n = 0;
2552 /* Can't pre-compute the list size; the list
2553 is stored on the class so accessible to other
2554 threads, which may be run by DECREF */
2555 for (i = 0; i < PyList_GET_SIZE(names); i++) {
2556 PyObject *name, *value;
2557 name = PyList_GET_ITEM(names, i);
2558 value = PyObject_GetAttr(obj, name);
2559 if (value == NULL)
2560 PyErr_Clear();
2561 else {
2562 int err = PyDict_SetItem(slots, name,
2563 value);
2564 Py_DECREF(value);
2565 if (err)
2566 goto end;
2567 n++;
2568 }
2569 }
2570 if (n) {
2571 state = Py_BuildValue("(NO)", state, slots);
2572 if (state == NULL)
2573 goto end;
2574 }
2575 }
2576 }
2577
2578 if (!PyList_Check(obj)) {
2579 listitems = Py_None;
2580 Py_INCREF(listitems);
2581 }
2582 else {
2583 listitems = PyObject_GetIter(obj);
2584 if (listitems == NULL)
2585 goto end;
2586 }
2587
2588 if (!PyDict_Check(obj)) {
2589 dictitems = Py_None;
2590 Py_INCREF(dictitems);
2591 }
2592 else {
2593 dictitems = PyObject_CallMethod(obj, "iteritems", "");
2594 if (dictitems == NULL)
2595 goto end;
2596 }
2597
2598 copy_reg = import_copy_reg();
2599 if (copy_reg == NULL)
2600 goto end;
2601 newobj = PyObject_GetAttrString(copy_reg, "__newobj__");
2602 if (newobj == NULL)
2603 goto end;
2604
2605 n = PyTuple_GET_SIZE(args);
2606 args2 = PyTuple_New(n+1);
2607 if (args2 == NULL)
2608 goto end;
2609 PyTuple_SET_ITEM(args2, 0, cls);
2610 cls = NULL;
2611 for (i = 0; i < n; i++) {
2612 PyObject *v = PyTuple_GET_ITEM(args, i);
2613 Py_INCREF(v);
2614 PyTuple_SET_ITEM(args2, i+1, v);
2615 }
2616
2617 res = Py_BuildValue("(OOOOO)",
2618 newobj, args2, state, listitems, dictitems);
2619
2620 end:
2621 Py_XDECREF(cls);
2622 Py_XDECREF(args);
2623 Py_XDECREF(args2);
2624 Py_XDECREF(state);
2625 Py_XDECREF(names);
2626 Py_XDECREF(listitems);
2627 Py_XDECREF(dictitems);
2628 Py_XDECREF(copy_reg);
2629 Py_XDECREF(newobj);
2630 return res;
2631}
2632
2633static PyObject *
2634object_reduce_ex(PyObject *self, PyObject *args)
2635{
2636 /* Call copy_reg._reduce_ex(self, proto) */
2637 PyObject *reduce, *copy_reg, *res;
2638 int proto = 0;
2639
2640 if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
2641 return NULL;
2642
2643 reduce = PyObject_GetAttrString(self, "__reduce__");
2644 if (reduce == NULL)
2645 PyErr_Clear();
2646 else {
2647 PyObject *cls, *clsreduce, *objreduce;
2648 int override;
2649 cls = PyObject_GetAttrString(self, "__class__");
2650 if (cls == NULL) {
2651 Py_DECREF(reduce);
2652 return NULL;
2653 }
2654 clsreduce = PyObject_GetAttrString(cls, "__reduce__");
2655 Py_DECREF(cls);
2656 if (clsreduce == NULL) {
2657 Py_DECREF(reduce);
2658 return NULL;
2659 }
2660 objreduce = PyDict_GetItemString(PyBaseObject_Type.tp_dict,
2661 "__reduce__");
2662 override = (clsreduce != objreduce);
2663 Py_DECREF(clsreduce);
2664 if (override) {
2665 res = PyObject_CallObject(reduce, NULL);
2666 Py_DECREF(reduce);
2667 return res;
2668 }
2669 else
2670 Py_DECREF(reduce);
2671 }
2672
2673 if (proto >= 2)
2674 return reduce_2(self);
2675
2676 copy_reg = import_copy_reg();
Guido van Rossum3926a632001-09-25 16:25:58 +00002677 if (!copy_reg)
2678 return NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00002679
Guido van Rossumc53f0092003-02-18 22:05:12 +00002680 res = PyEval_CallMethod(copy_reg, "_reduce_ex", "(Oi)", self, proto);
Guido van Rossum3926a632001-09-25 16:25:58 +00002681 Py_DECREF(copy_reg);
Guido van Rossum036f9992003-02-21 22:02:54 +00002682
Guido van Rossum3926a632001-09-25 16:25:58 +00002683 return res;
2684}
2685
2686static PyMethodDef object_methods[] = {
Guido van Rossumc53f0092003-02-18 22:05:12 +00002687 {"__reduce_ex__", object_reduce_ex, METH_VARARGS,
2688 PyDoc_STR("helper for pickle")},
2689 {"__reduce__", object_reduce_ex, METH_VARARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002690 PyDoc_STR("helper for pickle")},
Guido van Rossum3926a632001-09-25 16:25:58 +00002691 {0}
2692};
2693
Guido van Rossum036f9992003-02-21 22:02:54 +00002694
Tim Peters6d6c1a32001-08-02 04:15:00 +00002695PyTypeObject PyBaseObject_Type = {
2696 PyObject_HEAD_INIT(&PyType_Type)
2697 0, /* ob_size */
2698 "object", /* tp_name */
2699 sizeof(PyObject), /* tp_basicsize */
2700 0, /* tp_itemsize */
2701 (destructor)object_dealloc, /* tp_dealloc */
2702 0, /* tp_print */
2703 0, /* tp_getattr */
2704 0, /* tp_setattr */
2705 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002706 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002707 0, /* tp_as_number */
2708 0, /* tp_as_sequence */
2709 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002710 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002711 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002712 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002713 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002714 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002715 0, /* tp_as_buffer */
2716 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002717 PyDoc_STR("The most base type"), /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002718 0, /* tp_traverse */
2719 0, /* tp_clear */
2720 0, /* tp_richcompare */
2721 0, /* tp_weaklistoffset */
2722 0, /* tp_iter */
2723 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00002724 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002725 0, /* tp_members */
2726 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002727 0, /* tp_base */
2728 0, /* tp_dict */
2729 0, /* tp_descr_get */
2730 0, /* tp_descr_set */
2731 0, /* tp_dictoffset */
2732 object_init, /* tp_init */
2733 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossum298e4212003-02-13 16:30:16 +00002734 object_new, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002735 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002736};
2737
2738
2739/* Initialize the __dict__ in a type object */
2740
2741static int
2742add_methods(PyTypeObject *type, PyMethodDef *meth)
2743{
Guido van Rossum687ae002001-10-15 22:03:32 +00002744 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002745
2746 for (; meth->ml_name != NULL; meth++) {
2747 PyObject *descr;
2748 if (PyDict_GetItemString(dict, meth->ml_name))
2749 continue;
Fred Drake7bf97152002-03-28 05:33:33 +00002750 if (meth->ml_flags & METH_CLASS) {
2751 if (meth->ml_flags & METH_STATIC) {
2752 PyErr_SetString(PyExc_ValueError,
2753 "method cannot be both class and static");
2754 return -1;
2755 }
Tim Petersbca1cbc2002-12-09 22:56:13 +00002756 descr = PyDescr_NewClassMethod(type, meth);
Fred Drake7bf97152002-03-28 05:33:33 +00002757 }
2758 else if (meth->ml_flags & METH_STATIC) {
Guido van Rossum9af48ff2003-02-11 17:12:46 +00002759 PyObject *cfunc = PyCFunction_New(meth, NULL);
2760 if (cfunc == NULL)
2761 return -1;
2762 descr = PyStaticMethod_New(cfunc);
2763 Py_DECREF(cfunc);
Fred Drake7bf97152002-03-28 05:33:33 +00002764 }
2765 else {
2766 descr = PyDescr_NewMethod(type, meth);
2767 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002768 if (descr == NULL)
2769 return -1;
Fred Drake7bf97152002-03-28 05:33:33 +00002770 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002771 return -1;
2772 Py_DECREF(descr);
2773 }
2774 return 0;
2775}
2776
2777static int
Guido van Rossum6f799372001-09-20 20:46:19 +00002778add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002779{
Guido van Rossum687ae002001-10-15 22:03:32 +00002780 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002781
2782 for (; memb->name != NULL; memb++) {
2783 PyObject *descr;
2784 if (PyDict_GetItemString(dict, memb->name))
2785 continue;
2786 descr = PyDescr_NewMember(type, memb);
2787 if (descr == NULL)
2788 return -1;
2789 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
2790 return -1;
2791 Py_DECREF(descr);
2792 }
2793 return 0;
2794}
2795
2796static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00002797add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002798{
Guido van Rossum687ae002001-10-15 22:03:32 +00002799 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002800
2801 for (; gsp->name != NULL; gsp++) {
2802 PyObject *descr;
2803 if (PyDict_GetItemString(dict, gsp->name))
2804 continue;
2805 descr = PyDescr_NewGetSet(type, gsp);
2806
2807 if (descr == NULL)
2808 return -1;
2809 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
2810 return -1;
2811 Py_DECREF(descr);
2812 }
2813 return 0;
2814}
2815
Guido van Rossum13d52f02001-08-10 21:24:08 +00002816static void
2817inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002818{
2819 int oldsize, newsize;
2820
Guido van Rossum13d52f02001-08-10 21:24:08 +00002821 /* Special flag magic */
2822 if (!type->tp_as_buffer && base->tp_as_buffer) {
2823 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
2824 type->tp_flags |=
2825 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
2826 }
2827 if (!type->tp_as_sequence && base->tp_as_sequence) {
2828 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
2829 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
2830 }
2831 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
2832 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
2833 if ((!type->tp_as_number && base->tp_as_number) ||
2834 (!type->tp_as_sequence && base->tp_as_sequence)) {
2835 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
2836 if (!type->tp_as_number && !type->tp_as_sequence) {
2837 type->tp_flags |= base->tp_flags &
2838 Py_TPFLAGS_HAVE_INPLACEOPS;
2839 }
2840 }
2841 /* Wow */
2842 }
2843 if (!type->tp_as_number && base->tp_as_number) {
2844 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
2845 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
2846 }
2847
2848 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00002849 oldsize = base->tp_basicsize;
2850 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
2851 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
2852 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00002853 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
2854 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00002855 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00002856 if (type->tp_traverse == NULL)
2857 type->tp_traverse = base->tp_traverse;
2858 if (type->tp_clear == NULL)
2859 type->tp_clear = base->tp_clear;
2860 }
2861 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
Guido van Rossumf884b742001-12-17 17:14:22 +00002862 /* The condition below could use some explanation.
2863 It appears that tp_new is not inherited for static types
2864 whose base class is 'object'; this seems to be a precaution
2865 so that old extension types don't suddenly become
2866 callable (object.__new__ wouldn't insure the invariants
2867 that the extension type's own factory function ensures).
2868 Heap types, of course, are under our control, so they do
2869 inherit tp_new; static extension types that specify some
2870 other built-in type as the default are considered
2871 new-style-aware so they also inherit object.__new__. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002872 if (base != &PyBaseObject_Type ||
2873 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2874 if (type->tp_new == NULL)
2875 type->tp_new = base->tp_new;
2876 }
2877 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00002878 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00002879
2880 /* Copy other non-function slots */
2881
2882#undef COPYVAL
2883#define COPYVAL(SLOT) \
2884 if (type->SLOT == 0) type->SLOT = base->SLOT
2885
2886 COPYVAL(tp_itemsize);
2887 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
2888 COPYVAL(tp_weaklistoffset);
2889 }
2890 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2891 COPYVAL(tp_dictoffset);
2892 }
Guido van Rossum13d52f02001-08-10 21:24:08 +00002893}
2894
2895static void
2896inherit_slots(PyTypeObject *type, PyTypeObject *base)
2897{
2898 PyTypeObject *basebase;
2899
2900#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00002901#undef COPYSLOT
2902#undef COPYNUM
2903#undef COPYSEQ
2904#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00002905#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00002906
2907#define SLOTDEFINED(SLOT) \
2908 (base->SLOT != 0 && \
2909 (basebase == NULL || base->SLOT != basebase->SLOT))
2910
Tim Peters6d6c1a32001-08-02 04:15:00 +00002911#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00002912 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00002913
2914#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
2915#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
2916#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00002917#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002918
Guido van Rossum13d52f02001-08-10 21:24:08 +00002919 /* This won't inherit indirect slots (from tp_as_number etc.)
2920 if type doesn't provide the space. */
2921
2922 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
2923 basebase = base->tp_base;
2924 if (basebase->tp_as_number == NULL)
2925 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002926 COPYNUM(nb_add);
2927 COPYNUM(nb_subtract);
2928 COPYNUM(nb_multiply);
2929 COPYNUM(nb_divide);
2930 COPYNUM(nb_remainder);
2931 COPYNUM(nb_divmod);
2932 COPYNUM(nb_power);
2933 COPYNUM(nb_negative);
2934 COPYNUM(nb_positive);
2935 COPYNUM(nb_absolute);
2936 COPYNUM(nb_nonzero);
2937 COPYNUM(nb_invert);
2938 COPYNUM(nb_lshift);
2939 COPYNUM(nb_rshift);
2940 COPYNUM(nb_and);
2941 COPYNUM(nb_xor);
2942 COPYNUM(nb_or);
2943 COPYNUM(nb_coerce);
2944 COPYNUM(nb_int);
2945 COPYNUM(nb_long);
2946 COPYNUM(nb_float);
2947 COPYNUM(nb_oct);
2948 COPYNUM(nb_hex);
2949 COPYNUM(nb_inplace_add);
2950 COPYNUM(nb_inplace_subtract);
2951 COPYNUM(nb_inplace_multiply);
2952 COPYNUM(nb_inplace_divide);
2953 COPYNUM(nb_inplace_remainder);
2954 COPYNUM(nb_inplace_power);
2955 COPYNUM(nb_inplace_lshift);
2956 COPYNUM(nb_inplace_rshift);
2957 COPYNUM(nb_inplace_and);
2958 COPYNUM(nb_inplace_xor);
2959 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00002960 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
2961 COPYNUM(nb_true_divide);
2962 COPYNUM(nb_floor_divide);
2963 COPYNUM(nb_inplace_true_divide);
2964 COPYNUM(nb_inplace_floor_divide);
2965 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002966 }
2967
Guido van Rossum13d52f02001-08-10 21:24:08 +00002968 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
2969 basebase = base->tp_base;
2970 if (basebase->tp_as_sequence == NULL)
2971 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002972 COPYSEQ(sq_length);
2973 COPYSEQ(sq_concat);
2974 COPYSEQ(sq_repeat);
2975 COPYSEQ(sq_item);
2976 COPYSEQ(sq_slice);
2977 COPYSEQ(sq_ass_item);
2978 COPYSEQ(sq_ass_slice);
2979 COPYSEQ(sq_contains);
2980 COPYSEQ(sq_inplace_concat);
2981 COPYSEQ(sq_inplace_repeat);
2982 }
2983
Guido van Rossum13d52f02001-08-10 21:24:08 +00002984 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
2985 basebase = base->tp_base;
2986 if (basebase->tp_as_mapping == NULL)
2987 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002988 COPYMAP(mp_length);
2989 COPYMAP(mp_subscript);
2990 COPYMAP(mp_ass_subscript);
2991 }
2992
Tim Petersfc57ccb2001-10-12 02:38:24 +00002993 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
2994 basebase = base->tp_base;
2995 if (basebase->tp_as_buffer == NULL)
2996 basebase = NULL;
2997 COPYBUF(bf_getreadbuffer);
2998 COPYBUF(bf_getwritebuffer);
2999 COPYBUF(bf_getsegcount);
3000 COPYBUF(bf_getcharbuffer);
3001 }
3002
Guido van Rossum13d52f02001-08-10 21:24:08 +00003003 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003004
Tim Peters6d6c1a32001-08-02 04:15:00 +00003005 COPYSLOT(tp_dealloc);
3006 COPYSLOT(tp_print);
3007 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
3008 type->tp_getattr = base->tp_getattr;
3009 type->tp_getattro = base->tp_getattro;
3010 }
3011 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
3012 type->tp_setattr = base->tp_setattr;
3013 type->tp_setattro = base->tp_setattro;
3014 }
3015 /* tp_compare see tp_richcompare */
3016 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003017 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003018 COPYSLOT(tp_call);
3019 COPYSLOT(tp_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003020 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003021 if (type->tp_compare == NULL &&
3022 type->tp_richcompare == NULL &&
3023 type->tp_hash == NULL)
3024 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003025 type->tp_compare = base->tp_compare;
3026 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003027 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003028 }
3029 }
3030 else {
3031 COPYSLOT(tp_compare);
3032 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003033 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
3034 COPYSLOT(tp_iter);
3035 COPYSLOT(tp_iternext);
3036 }
3037 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
3038 COPYSLOT(tp_descr_get);
3039 COPYSLOT(tp_descr_set);
3040 COPYSLOT(tp_dictoffset);
3041 COPYSLOT(tp_init);
3042 COPYSLOT(tp_alloc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003043 COPYSLOT(tp_free);
Guido van Rossumcc8fe042002-04-05 17:10:16 +00003044 COPYSLOT(tp_is_gc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003045 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003046}
3047
Jeremy Hylton938ace62002-07-17 16:30:39 +00003048static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00003049
Tim Peters6d6c1a32001-08-02 04:15:00 +00003050int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00003051PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003052{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003053 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003054 PyTypeObject *base;
3055 int i, n;
3056
Guido van Rossumcab05802002-06-10 15:29:03 +00003057 if (type->tp_flags & Py_TPFLAGS_READY) {
3058 assert(type->tp_dict != NULL);
Guido van Rossumd614f972001-08-10 17:39:49 +00003059 return 0;
Guido van Rossumcab05802002-06-10 15:29:03 +00003060 }
Guido van Rossumd614f972001-08-10 17:39:49 +00003061 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00003062
3063 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003064
Tim Peters36eb4df2003-03-23 03:33:13 +00003065#ifdef Py_TRACE_REFS
3066 /* PyType_Ready is the closest thing we have to a choke point
3067 * for type objects, so is the best place I can think of to try
3068 * to get type objects into the doubly-linked list of all objects.
3069 * Still, not all type objects go thru PyType_Ready.
3070 */
Tim Peters7571a0f2003-03-23 17:52:28 +00003071 _Py_AddToAllObjects((PyObject *)type, 0);
Tim Peters36eb4df2003-03-23 03:33:13 +00003072#endif
3073
Tim Peters6d6c1a32001-08-02 04:15:00 +00003074 /* Initialize tp_base (defaults to BaseObject unless that's us) */
3075 base = type->tp_base;
3076 if (base == NULL && type != &PyBaseObject_Type)
3077 base = type->tp_base = &PyBaseObject_Type;
3078
Guido van Rossum323a9cf2002-08-14 17:26:30 +00003079 /* Initialize the base class */
3080 if (base && base->tp_dict == NULL) {
3081 if (PyType_Ready(base) < 0)
3082 goto error;
3083 }
3084
Guido van Rossum0986d822002-04-08 01:38:42 +00003085 /* Initialize ob_type if NULL. This means extensions that want to be
3086 compilable separately on Windows can call PyType_Ready() instead of
3087 initializing the ob_type field of their type objects. */
3088 if (type->ob_type == NULL)
3089 type->ob_type = base->ob_type;
3090
Tim Peters6d6c1a32001-08-02 04:15:00 +00003091 /* Initialize tp_bases */
3092 bases = type->tp_bases;
3093 if (bases == NULL) {
3094 if (base == NULL)
3095 bases = PyTuple_New(0);
3096 else
3097 bases = Py_BuildValue("(O)", base);
3098 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003099 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003100 type->tp_bases = bases;
3101 }
3102
Guido van Rossum687ae002001-10-15 22:03:32 +00003103 /* Initialize tp_dict */
3104 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003105 if (dict == NULL) {
3106 dict = PyDict_New();
3107 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003108 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00003109 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003110 }
3111
Guido van Rossum687ae002001-10-15 22:03:32 +00003112 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003113 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003114 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003115 if (type->tp_methods != NULL) {
3116 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003117 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003118 }
3119 if (type->tp_members != NULL) {
3120 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003121 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003122 }
3123 if (type->tp_getset != NULL) {
3124 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003125 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003126 }
3127
Tim Peters6d6c1a32001-08-02 04:15:00 +00003128 /* Calculate method resolution order */
3129 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00003130 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003131 }
3132
Guido van Rossum13d52f02001-08-10 21:24:08 +00003133 /* Inherit special flags from dominant base */
3134 if (type->tp_base != NULL)
3135 inherit_special(type, type->tp_base);
3136
Tim Peters6d6c1a32001-08-02 04:15:00 +00003137 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003138 bases = type->tp_mro;
3139 assert(bases != NULL);
3140 assert(PyTuple_Check(bases));
3141 n = PyTuple_GET_SIZE(bases);
3142 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003143 PyObject *b = PyTuple_GET_ITEM(bases, i);
3144 if (PyType_Check(b))
3145 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003146 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003147
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003148 /* if the type dictionary doesn't contain a __doc__, set it from
3149 the tp_doc slot.
3150 */
3151 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
3152 if (type->tp_doc != NULL) {
3153 PyObject *doc = PyString_FromString(type->tp_doc);
3154 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
3155 Py_DECREF(doc);
3156 } else {
Guido van Rossumd4641072002-04-03 02:13:37 +00003157 PyDict_SetItemString(type->tp_dict,
3158 "__doc__", Py_None);
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003159 }
3160 }
3161
Guido van Rossum13d52f02001-08-10 21:24:08 +00003162 /* Some more special stuff */
3163 base = type->tp_base;
3164 if (base != NULL) {
3165 if (type->tp_as_number == NULL)
3166 type->tp_as_number = base->tp_as_number;
3167 if (type->tp_as_sequence == NULL)
3168 type->tp_as_sequence = base->tp_as_sequence;
3169 if (type->tp_as_mapping == NULL)
3170 type->tp_as_mapping = base->tp_as_mapping;
Guido van Rossumeea47182003-02-11 20:39:59 +00003171 if (type->tp_as_buffer == NULL)
3172 type->tp_as_buffer = base->tp_as_buffer;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003173 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003174
Guido van Rossum1c450732001-10-08 15:18:27 +00003175 /* Link into each base class's list of subclasses */
3176 bases = type->tp_bases;
3177 n = PyTuple_GET_SIZE(bases);
3178 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003179 PyObject *b = PyTuple_GET_ITEM(bases, i);
3180 if (PyType_Check(b) &&
3181 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00003182 goto error;
3183 }
3184
Guido van Rossum13d52f02001-08-10 21:24:08 +00003185 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00003186 assert(type->tp_dict != NULL);
3187 type->tp_flags =
3188 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003189 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00003190
3191 error:
3192 type->tp_flags &= ~Py_TPFLAGS_READYING;
3193 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003194}
3195
Guido van Rossum1c450732001-10-08 15:18:27 +00003196static int
3197add_subclass(PyTypeObject *base, PyTypeObject *type)
3198{
3199 int i;
3200 PyObject *list, *ref, *new;
3201
3202 list = base->tp_subclasses;
3203 if (list == NULL) {
3204 base->tp_subclasses = list = PyList_New(0);
3205 if (list == NULL)
3206 return -1;
3207 }
3208 assert(PyList_Check(list));
3209 new = PyWeakref_NewRef((PyObject *)type, NULL);
3210 i = PyList_GET_SIZE(list);
3211 while (--i >= 0) {
3212 ref = PyList_GET_ITEM(list, i);
3213 assert(PyWeakref_CheckRef(ref));
Guido van Rossum3930bc32002-10-18 13:51:49 +00003214 if (PyWeakref_GET_OBJECT(ref) == Py_None)
3215 return PyList_SetItem(list, i, new);
Guido van Rossum1c450732001-10-08 15:18:27 +00003216 }
3217 i = PyList_Append(list, new);
3218 Py_DECREF(new);
3219 return i;
3220}
3221
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003222static void
3223remove_subclass(PyTypeObject *base, PyTypeObject *type)
3224{
3225 int i;
3226 PyObject *list, *ref;
3227
3228 list = base->tp_subclasses;
3229 if (list == NULL) {
3230 return;
3231 }
3232 assert(PyList_Check(list));
3233 i = PyList_GET_SIZE(list);
3234 while (--i >= 0) {
3235 ref = PyList_GET_ITEM(list, i);
3236 assert(PyWeakref_CheckRef(ref));
3237 if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
3238 /* this can't fail, right? */
3239 PySequence_DelItem(list, i);
3240 return;
3241 }
3242 }
3243}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003244
3245/* Generic wrappers for overloadable 'operators' such as __getitem__ */
3246
3247/* There's a wrapper *function* for each distinct function typedef used
3248 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
3249 wrapper *table* for each distinct operation (e.g. __len__, __add__).
3250 Most tables have only one entry; the tables for binary operators have two
3251 entries, one regular and one with reversed arguments. */
3252
3253static PyObject *
3254wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
3255{
3256 inquiry func = (inquiry)wrapped;
3257 int res;
3258
3259 if (!PyArg_ParseTuple(args, ""))
3260 return NULL;
3261 res = (*func)(self);
3262 if (res == -1 && PyErr_Occurred())
3263 return NULL;
3264 return PyInt_FromLong((long)res);
3265}
3266
Tim Peters6d6c1a32001-08-02 04:15:00 +00003267static PyObject *
3268wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
3269{
3270 binaryfunc func = (binaryfunc)wrapped;
3271 PyObject *other;
3272
3273 if (!PyArg_ParseTuple(args, "O", &other))
3274 return NULL;
3275 return (*func)(self, other);
3276}
3277
3278static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003279wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
3280{
3281 binaryfunc func = (binaryfunc)wrapped;
3282 PyObject *other;
3283
3284 if (!PyArg_ParseTuple(args, "O", &other))
3285 return NULL;
3286 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003287 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003288 Py_INCREF(Py_NotImplemented);
3289 return Py_NotImplemented;
3290 }
3291 return (*func)(self, other);
3292}
3293
3294static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003295wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3296{
3297 binaryfunc func = (binaryfunc)wrapped;
3298 PyObject *other;
3299
3300 if (!PyArg_ParseTuple(args, "O", &other))
3301 return NULL;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003302 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003303 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003304 Py_INCREF(Py_NotImplemented);
3305 return Py_NotImplemented;
3306 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003307 return (*func)(other, self);
3308}
3309
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003310static PyObject *
3311wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
3312{
3313 coercion func = (coercion)wrapped;
3314 PyObject *other, *res;
3315 int ok;
3316
3317 if (!PyArg_ParseTuple(args, "O", &other))
3318 return NULL;
3319 ok = func(&self, &other);
3320 if (ok < 0)
3321 return NULL;
3322 if (ok > 0) {
3323 Py_INCREF(Py_NotImplemented);
3324 return Py_NotImplemented;
3325 }
3326 res = PyTuple_New(2);
3327 if (res == NULL) {
3328 Py_DECREF(self);
3329 Py_DECREF(other);
3330 return NULL;
3331 }
3332 PyTuple_SET_ITEM(res, 0, self);
3333 PyTuple_SET_ITEM(res, 1, other);
3334 return res;
3335}
3336
Tim Peters6d6c1a32001-08-02 04:15:00 +00003337static PyObject *
3338wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
3339{
3340 ternaryfunc func = (ternaryfunc)wrapped;
3341 PyObject *other;
3342 PyObject *third = Py_None;
3343
3344 /* Note: This wrapper only works for __pow__() */
3345
3346 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
3347 return NULL;
3348 return (*func)(self, other, third);
3349}
3350
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00003351static PyObject *
3352wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3353{
3354 ternaryfunc func = (ternaryfunc)wrapped;
3355 PyObject *other;
3356 PyObject *third = Py_None;
3357
3358 /* Note: This wrapper only works for __pow__() */
3359
3360 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
3361 return NULL;
3362 return (*func)(other, self, third);
3363}
3364
Tim Peters6d6c1a32001-08-02 04:15:00 +00003365static PyObject *
3366wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
3367{
3368 unaryfunc func = (unaryfunc)wrapped;
3369
3370 if (!PyArg_ParseTuple(args, ""))
3371 return NULL;
3372 return (*func)(self);
3373}
3374
Tim Peters6d6c1a32001-08-02 04:15:00 +00003375static PyObject *
3376wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
3377{
3378 intargfunc func = (intargfunc)wrapped;
3379 int i;
3380
3381 if (!PyArg_ParseTuple(args, "i", &i))
3382 return NULL;
3383 return (*func)(self, i);
3384}
3385
Guido van Rossum5d815f32001-08-17 21:57:47 +00003386static int
3387getindex(PyObject *self, PyObject *arg)
3388{
3389 int i;
3390
3391 i = PyInt_AsLong(arg);
3392 if (i == -1 && PyErr_Occurred())
3393 return -1;
3394 if (i < 0) {
3395 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
3396 if (sq && sq->sq_length) {
3397 int n = (*sq->sq_length)(self);
3398 if (n < 0)
3399 return -1;
3400 i += n;
3401 }
3402 }
3403 return i;
3404}
3405
3406static PyObject *
3407wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
3408{
3409 intargfunc func = (intargfunc)wrapped;
3410 PyObject *arg;
3411 int i;
3412
Guido van Rossumf4593e02001-10-03 12:09:30 +00003413 if (PyTuple_GET_SIZE(args) == 1) {
3414 arg = PyTuple_GET_ITEM(args, 0);
3415 i = getindex(self, arg);
3416 if (i == -1 && PyErr_Occurred())
3417 return NULL;
3418 return (*func)(self, i);
3419 }
3420 PyArg_ParseTuple(args, "O", &arg);
3421 assert(PyErr_Occurred());
3422 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003423}
3424
Tim Peters6d6c1a32001-08-02 04:15:00 +00003425static PyObject *
3426wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
3427{
3428 intintargfunc func = (intintargfunc)wrapped;
3429 int i, j;
3430
3431 if (!PyArg_ParseTuple(args, "ii", &i, &j))
3432 return NULL;
3433 return (*func)(self, i, j);
3434}
3435
Tim Peters6d6c1a32001-08-02 04:15:00 +00003436static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003437wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003438{
3439 intobjargproc func = (intobjargproc)wrapped;
3440 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003441 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003442
Guido van Rossum5d815f32001-08-17 21:57:47 +00003443 if (!PyArg_ParseTuple(args, "OO", &arg, &value))
3444 return NULL;
3445 i = getindex(self, arg);
3446 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00003447 return NULL;
3448 res = (*func)(self, i, value);
3449 if (res == -1 && PyErr_Occurred())
3450 return NULL;
3451 Py_INCREF(Py_None);
3452 return Py_None;
3453}
3454
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003455static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003456wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003457{
3458 intobjargproc func = (intobjargproc)wrapped;
3459 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003460 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003461
Guido van Rossum5d815f32001-08-17 21:57:47 +00003462 if (!PyArg_ParseTuple(args, "O", &arg))
3463 return NULL;
3464 i = getindex(self, arg);
3465 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003466 return NULL;
3467 res = (*func)(self, i, NULL);
3468 if (res == -1 && PyErr_Occurred())
3469 return NULL;
3470 Py_INCREF(Py_None);
3471 return Py_None;
3472}
3473
Tim Peters6d6c1a32001-08-02 04:15:00 +00003474static PyObject *
3475wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
3476{
3477 intintobjargproc func = (intintobjargproc)wrapped;
3478 int i, j, res;
3479 PyObject *value;
3480
3481 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
3482 return NULL;
3483 res = (*func)(self, i, j, value);
3484 if (res == -1 && PyErr_Occurred())
3485 return NULL;
3486 Py_INCREF(Py_None);
3487 return Py_None;
3488}
3489
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003490static PyObject *
3491wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
3492{
3493 intintobjargproc func = (intintobjargproc)wrapped;
3494 int i, j, res;
3495
3496 if (!PyArg_ParseTuple(args, "ii", &i, &j))
3497 return NULL;
3498 res = (*func)(self, i, j, NULL);
3499 if (res == -1 && PyErr_Occurred())
3500 return NULL;
3501 Py_INCREF(Py_None);
3502 return Py_None;
3503}
3504
Tim Peters6d6c1a32001-08-02 04:15:00 +00003505/* XXX objobjproc is a misnomer; should be objargpred */
3506static PyObject *
3507wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
3508{
3509 objobjproc func = (objobjproc)wrapped;
3510 int res;
3511 PyObject *value;
3512
3513 if (!PyArg_ParseTuple(args, "O", &value))
3514 return NULL;
3515 res = (*func)(self, value);
3516 if (res == -1 && PyErr_Occurred())
3517 return NULL;
3518 return PyInt_FromLong((long)res);
3519}
3520
Tim Peters6d6c1a32001-08-02 04:15:00 +00003521static PyObject *
3522wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
3523{
3524 objobjargproc func = (objobjargproc)wrapped;
3525 int res;
3526 PyObject *key, *value;
3527
3528 if (!PyArg_ParseTuple(args, "OO", &key, &value))
3529 return NULL;
3530 res = (*func)(self, key, value);
3531 if (res == -1 && PyErr_Occurred())
3532 return NULL;
3533 Py_INCREF(Py_None);
3534 return Py_None;
3535}
3536
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003537static PyObject *
3538wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
3539{
3540 objobjargproc func = (objobjargproc)wrapped;
3541 int res;
3542 PyObject *key;
3543
3544 if (!PyArg_ParseTuple(args, "O", &key))
3545 return NULL;
3546 res = (*func)(self, key, NULL);
3547 if (res == -1 && PyErr_Occurred())
3548 return NULL;
3549 Py_INCREF(Py_None);
3550 return Py_None;
3551}
3552
Tim Peters6d6c1a32001-08-02 04:15:00 +00003553static PyObject *
3554wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
3555{
3556 cmpfunc func = (cmpfunc)wrapped;
3557 int res;
3558 PyObject *other;
3559
3560 if (!PyArg_ParseTuple(args, "O", &other))
3561 return NULL;
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00003562 if (other->ob_type->tp_compare != func &&
3563 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00003564 PyErr_Format(
3565 PyExc_TypeError,
3566 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
3567 self->ob_type->tp_name,
3568 self->ob_type->tp_name,
3569 other->ob_type->tp_name);
3570 return NULL;
3571 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003572 res = (*func)(self, other);
3573 if (PyErr_Occurred())
3574 return NULL;
3575 return PyInt_FromLong((long)res);
3576}
3577
Tim Peters6d6c1a32001-08-02 04:15:00 +00003578static PyObject *
3579wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
3580{
3581 setattrofunc func = (setattrofunc)wrapped;
3582 int res;
3583 PyObject *name, *value;
3584
3585 if (!PyArg_ParseTuple(args, "OO", &name, &value))
3586 return NULL;
3587 res = (*func)(self, name, value);
3588 if (res < 0)
3589 return NULL;
3590 Py_INCREF(Py_None);
3591 return Py_None;
3592}
3593
3594static PyObject *
3595wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
3596{
3597 setattrofunc func = (setattrofunc)wrapped;
3598 int res;
3599 PyObject *name;
3600
3601 if (!PyArg_ParseTuple(args, "O", &name))
3602 return NULL;
3603 res = (*func)(self, name, NULL);
3604 if (res < 0)
3605 return NULL;
3606 Py_INCREF(Py_None);
3607 return Py_None;
3608}
3609
Tim Peters6d6c1a32001-08-02 04:15:00 +00003610static PyObject *
3611wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
3612{
3613 hashfunc func = (hashfunc)wrapped;
3614 long res;
3615
3616 if (!PyArg_ParseTuple(args, ""))
3617 return NULL;
3618 res = (*func)(self);
3619 if (res == -1 && PyErr_Occurred())
3620 return NULL;
3621 return PyInt_FromLong(res);
3622}
3623
Tim Peters6d6c1a32001-08-02 04:15:00 +00003624static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00003625wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003626{
3627 ternaryfunc func = (ternaryfunc)wrapped;
3628
Guido van Rossumc8e56452001-10-22 00:43:43 +00003629 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003630}
3631
Tim Peters6d6c1a32001-08-02 04:15:00 +00003632static PyObject *
3633wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
3634{
3635 richcmpfunc func = (richcmpfunc)wrapped;
3636 PyObject *other;
3637
3638 if (!PyArg_ParseTuple(args, "O", &other))
3639 return NULL;
3640 return (*func)(self, other, op);
3641}
3642
3643#undef RICHCMP_WRAPPER
3644#define RICHCMP_WRAPPER(NAME, OP) \
3645static PyObject * \
3646richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
3647{ \
3648 return wrap_richcmpfunc(self, args, wrapped, OP); \
3649}
3650
Jack Jansen8e938b42001-08-08 15:29:49 +00003651RICHCMP_WRAPPER(lt, Py_LT)
3652RICHCMP_WRAPPER(le, Py_LE)
3653RICHCMP_WRAPPER(eq, Py_EQ)
3654RICHCMP_WRAPPER(ne, Py_NE)
3655RICHCMP_WRAPPER(gt, Py_GT)
3656RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003657
Tim Peters6d6c1a32001-08-02 04:15:00 +00003658static PyObject *
3659wrap_next(PyObject *self, PyObject *args, void *wrapped)
3660{
3661 unaryfunc func = (unaryfunc)wrapped;
3662 PyObject *res;
3663
3664 if (!PyArg_ParseTuple(args, ""))
3665 return NULL;
3666 res = (*func)(self);
3667 if (res == NULL && !PyErr_Occurred())
3668 PyErr_SetNone(PyExc_StopIteration);
3669 return res;
3670}
3671
Tim Peters6d6c1a32001-08-02 04:15:00 +00003672static PyObject *
3673wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
3674{
3675 descrgetfunc func = (descrgetfunc)wrapped;
3676 PyObject *obj;
3677 PyObject *type = NULL;
3678
3679 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
3680 return NULL;
Guido van Rossum82ed25c2003-02-11 16:25:43 +00003681 if (obj == Py_None)
3682 obj = NULL;
3683 if (type == Py_None)
3684 type = NULL;
3685 if (type == NULL &&obj == NULL) {
3686 PyErr_SetString(PyExc_TypeError,
3687 "__get__(None, None) is invalid");
3688 return NULL;
3689 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003690 return (*func)(self, obj, type);
3691}
3692
Tim Peters6d6c1a32001-08-02 04:15:00 +00003693static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003694wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003695{
3696 descrsetfunc func = (descrsetfunc)wrapped;
3697 PyObject *obj, *value;
3698 int ret;
3699
3700 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
3701 return NULL;
3702 ret = (*func)(self, obj, value);
3703 if (ret < 0)
3704 return NULL;
3705 Py_INCREF(Py_None);
3706 return Py_None;
3707}
Guido van Rossum22b13872002-08-06 21:41:44 +00003708
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00003709static PyObject *
3710wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
3711{
3712 descrsetfunc func = (descrsetfunc)wrapped;
3713 PyObject *obj;
3714 int ret;
3715
3716 if (!PyArg_ParseTuple(args, "O", &obj))
3717 return NULL;
3718 ret = (*func)(self, obj, NULL);
3719 if (ret < 0)
3720 return NULL;
3721 Py_INCREF(Py_None);
3722 return Py_None;
3723}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003724
Tim Peters6d6c1a32001-08-02 04:15:00 +00003725static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00003726wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003727{
3728 initproc func = (initproc)wrapped;
3729
Guido van Rossumc8e56452001-10-22 00:43:43 +00003730 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003731 return NULL;
3732 Py_INCREF(Py_None);
3733 return Py_None;
3734}
3735
Tim Peters6d6c1a32001-08-02 04:15:00 +00003736static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003737tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003738{
Barry Warsaw60f01882001-08-22 19:24:42 +00003739 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003740 PyObject *arg0, *res;
3741
3742 if (self == NULL || !PyType_Check(self))
3743 Py_FatalError("__new__() called with non-type 'self'");
3744 type = (PyTypeObject *)self;
3745 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003746 PyErr_Format(PyExc_TypeError,
3747 "%s.__new__(): not enough arguments",
3748 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003749 return NULL;
3750 }
3751 arg0 = PyTuple_GET_ITEM(args, 0);
3752 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003753 PyErr_Format(PyExc_TypeError,
3754 "%s.__new__(X): X is not a type object (%s)",
3755 type->tp_name,
3756 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003757 return NULL;
3758 }
3759 subtype = (PyTypeObject *)arg0;
3760 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003761 PyErr_Format(PyExc_TypeError,
3762 "%s.__new__(%s): %s is not a subtype of %s",
3763 type->tp_name,
3764 subtype->tp_name,
3765 subtype->tp_name,
3766 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003767 return NULL;
3768 }
Barry Warsaw60f01882001-08-22 19:24:42 +00003769
3770 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00003771 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00003772 most derived base that's not a heap type is this type. */
3773 staticbase = subtype;
3774 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
3775 staticbase = staticbase->tp_base;
Guido van Rossuma8c60f42001-09-14 19:43:36 +00003776 if (staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003777 PyErr_Format(PyExc_TypeError,
3778 "%s.__new__(%s) is not safe, use %s.__new__()",
3779 type->tp_name,
3780 subtype->tp_name,
3781 staticbase == NULL ? "?" : staticbase->tp_name);
3782 return NULL;
3783 }
3784
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003785 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
3786 if (args == NULL)
3787 return NULL;
3788 res = type->tp_new(subtype, args, kwds);
3789 Py_DECREF(args);
3790 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003791}
3792
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003793static struct PyMethodDef tp_new_methoddef[] = {
3794 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00003795 PyDoc_STR("T.__new__(S, ...) -> "
3796 "a new object with type S, a subtype of T")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00003797 {0}
3798};
3799
3800static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003801add_tp_new_wrapper(PyTypeObject *type)
3802{
Guido van Rossumf040ede2001-08-07 16:40:56 +00003803 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003804
Guido van Rossum687ae002001-10-15 22:03:32 +00003805 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00003806 return 0;
3807 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003808 if (func == NULL)
3809 return -1;
Guido van Rossum687ae002001-10-15 22:03:32 +00003810 return PyDict_SetItemString(type->tp_dict, "__new__", func);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003811}
3812
Guido van Rossumf040ede2001-08-07 16:40:56 +00003813/* Slot wrappers that call the corresponding __foo__ slot. See comments
3814 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003815
Guido van Rossumdc91b992001-08-08 22:26:22 +00003816#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003817static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003818FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003819{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00003820 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003821 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003822}
3823
Guido van Rossumdc91b992001-08-08 22:26:22 +00003824#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003825static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003826FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003827{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003828 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003829 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003830}
3831
Guido van Rossumcd118802003-01-06 22:57:47 +00003832/* Boolean helper for SLOT1BINFULL().
3833 right.__class__ is a nontrivial subclass of left.__class__. */
3834static int
3835method_is_overloaded(PyObject *left, PyObject *right, char *name)
3836{
3837 PyObject *a, *b;
3838 int ok;
3839
3840 b = PyObject_GetAttrString((PyObject *)(right->ob_type), name);
3841 if (b == NULL) {
3842 PyErr_Clear();
3843 /* If right doesn't have it, it's not overloaded */
3844 return 0;
3845 }
3846
3847 a = PyObject_GetAttrString((PyObject *)(left->ob_type), name);
3848 if (a == NULL) {
3849 PyErr_Clear();
3850 Py_DECREF(b);
3851 /* If right has it but left doesn't, it's overloaded */
3852 return 1;
3853 }
3854
3855 ok = PyObject_RichCompareBool(a, b, Py_NE);
3856 Py_DECREF(a);
3857 Py_DECREF(b);
3858 if (ok < 0) {
3859 PyErr_Clear();
3860 return 0;
3861 }
3862
3863 return ok;
3864}
3865
Guido van Rossumdc91b992001-08-08 22:26:22 +00003866
3867#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003868static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003869FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003870{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003871 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00003872 int do_other = self->ob_type != other->ob_type && \
3873 other->ob_type->tp_as_number != NULL && \
3874 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003875 if (self->ob_type->tp_as_number != NULL && \
3876 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
3877 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00003878 if (do_other && \
Guido van Rossumcd118802003-01-06 22:57:47 +00003879 PyType_IsSubtype(other->ob_type, self->ob_type) && \
3880 method_is_overloaded(self, other, ROPSTR)) { \
Guido van Rossum55f20992001-10-01 17:18:22 +00003881 r = call_maybe( \
3882 other, ROPSTR, &rcache_str, "(O)", self); \
3883 if (r != Py_NotImplemented) \
3884 return r; \
3885 Py_DECREF(r); \
3886 do_other = 0; \
3887 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00003888 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00003889 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003890 if (r != Py_NotImplemented || \
3891 other->ob_type == self->ob_type) \
3892 return r; \
3893 Py_DECREF(r); \
3894 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00003895 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00003896 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00003897 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003898 } \
3899 Py_INCREF(Py_NotImplemented); \
3900 return Py_NotImplemented; \
3901}
3902
3903#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
3904 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
3905
3906#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
3907static PyObject * \
3908FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
3909{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003910 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003911 return call_method(self, OPSTR, &cache_str, \
3912 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003913}
3914
3915static int
3916slot_sq_length(PyObject *self)
3917{
Guido van Rossum2730b132001-08-28 18:22:14 +00003918 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00003919 PyObject *res = call_method(self, "__len__", &len_str, "()");
Guido van Rossum26111622001-10-01 16:42:49 +00003920 int len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003921
3922 if (res == NULL)
3923 return -1;
Guido van Rossum26111622001-10-01 16:42:49 +00003924 len = (int)PyInt_AsLong(res);
3925 Py_DECREF(res);
Jeremy Hylton73a088e2002-07-25 16:43:29 +00003926 if (len == -1 && PyErr_Occurred())
3927 return -1;
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00003928 if (len < 0) {
Guido van Rossum22b13872002-08-06 21:41:44 +00003929 PyErr_SetString(PyExc_ValueError,
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00003930 "__len__() should return >= 0");
3931 return -1;
3932 }
Guido van Rossum26111622001-10-01 16:42:49 +00003933 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003934}
3935
Guido van Rossumdc91b992001-08-08 22:26:22 +00003936SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
3937SLOT1(slot_sq_repeat, "__mul__", int, "i")
Guido van Rossumf4593e02001-10-03 12:09:30 +00003938
3939/* Super-optimized version of slot_sq_item.
3940 Other slots could do the same... */
3941static PyObject *
3942slot_sq_item(PyObject *self, int i)
3943{
3944 static PyObject *getitem_str;
3945 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
3946 descrgetfunc f;
3947
3948 if (getitem_str == NULL) {
3949 getitem_str = PyString_InternFromString("__getitem__");
3950 if (getitem_str == NULL)
3951 return NULL;
3952 }
3953 func = _PyType_Lookup(self->ob_type, getitem_str);
3954 if (func != NULL) {
Guido van Rossumf4593e02001-10-03 12:09:30 +00003955 if ((f = func->ob_type->tp_descr_get) == NULL)
3956 Py_INCREF(func);
Neal Norwitz673cd822002-10-18 16:33:13 +00003957 else {
Guido van Rossumf4593e02001-10-03 12:09:30 +00003958 func = f(func, self, (PyObject *)(self->ob_type));
Neal Norwitz673cd822002-10-18 16:33:13 +00003959 if (func == NULL) {
3960 return NULL;
3961 }
3962 }
Guido van Rossumf4593e02001-10-03 12:09:30 +00003963 ival = PyInt_FromLong(i);
3964 if (ival != NULL) {
3965 args = PyTuple_New(1);
3966 if (args != NULL) {
3967 PyTuple_SET_ITEM(args, 0, ival);
3968 retval = PyObject_Call(func, args, NULL);
3969 Py_XDECREF(args);
3970 Py_XDECREF(func);
3971 return retval;
3972 }
3973 }
3974 }
3975 else {
3976 PyErr_SetObject(PyExc_AttributeError, getitem_str);
3977 }
3978 Py_XDECREF(args);
3979 Py_XDECREF(ival);
3980 Py_XDECREF(func);
3981 return NULL;
3982}
3983
Guido van Rossumdc91b992001-08-08 22:26:22 +00003984SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003985
3986static int
3987slot_sq_ass_item(PyObject *self, int index, PyObject *value)
3988{
3989 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003990 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003991
3992 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003993 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003994 "(i)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003995 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003996 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003997 "(iO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003998 if (res == NULL)
3999 return -1;
4000 Py_DECREF(res);
4001 return 0;
4002}
4003
4004static int
4005slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
4006{
4007 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004008 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004009
4010 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004011 res = call_method(self, "__delslice__", &delslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004012 "(ii)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004013 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004014 res = call_method(self, "__setslice__", &setslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004015 "(iiO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004016 if (res == NULL)
4017 return -1;
4018 Py_DECREF(res);
4019 return 0;
4020}
4021
4022static int
4023slot_sq_contains(PyObject *self, PyObject *value)
4024{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004025 PyObject *func, *res, *args;
Tim Petersbf9b2442003-03-23 05:35:36 +00004026 int result = -1;
4027
Guido van Rossum60718732001-08-28 17:47:51 +00004028 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004029
Guido van Rossum55f20992001-10-01 17:18:22 +00004030 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004031 if (func != NULL) {
4032 args = Py_BuildValue("(O)", value);
4033 if (args == NULL)
4034 res = NULL;
4035 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004036 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004037 Py_DECREF(args);
4038 }
4039 Py_DECREF(func);
Tim Petersbf9b2442003-03-23 05:35:36 +00004040 if (res != NULL) {
4041 result = PyObject_IsTrue(res);
4042 Py_DECREF(res);
4043 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004044 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004045 else if (! PyErr_Occurred()) {
4046 result = _PySequence_IterSearch(self, value,
4047 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004048 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004049 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004050}
4051
Guido van Rossumdc91b992001-08-08 22:26:22 +00004052SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
4053SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004054
4055#define slot_mp_length slot_sq_length
4056
Guido van Rossumdc91b992001-08-08 22:26:22 +00004057SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004058
4059static int
4060slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
4061{
4062 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004063 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004064
4065 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004066 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004067 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004068 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004069 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004070 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004071 if (res == NULL)
4072 return -1;
4073 Py_DECREF(res);
4074 return 0;
4075}
4076
Guido van Rossumdc91b992001-08-08 22:26:22 +00004077SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
4078SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
4079SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
4080SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
4081SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
4082SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
4083
Jeremy Hylton938ace62002-07-17 16:30:39 +00004084static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00004085
4086SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
4087 nb_power, "__pow__", "__rpow__")
4088
4089static PyObject *
4090slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
4091{
Guido van Rossum2730b132001-08-28 18:22:14 +00004092 static PyObject *pow_str;
4093
Guido van Rossumdc91b992001-08-08 22:26:22 +00004094 if (modulus == Py_None)
4095 return slot_nb_power_binary(self, other);
Guido van Rossum23094982002-06-10 14:30:43 +00004096 /* Three-arg power doesn't use __rpow__. But ternary_op
4097 can call this when the second argument's type uses
4098 slot_nb_power, so check before calling self.__pow__. */
4099 if (self->ob_type->tp_as_number != NULL &&
4100 self->ob_type->tp_as_number->nb_power == slot_nb_power) {
4101 return call_method(self, "__pow__", &pow_str,
4102 "(OO)", other, modulus);
4103 }
4104 Py_INCREF(Py_NotImplemented);
4105 return Py_NotImplemented;
Guido van Rossumdc91b992001-08-08 22:26:22 +00004106}
4107
4108SLOT0(slot_nb_negative, "__neg__")
4109SLOT0(slot_nb_positive, "__pos__")
4110SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004111
4112static int
4113slot_nb_nonzero(PyObject *self)
4114{
Tim Petersea7f75d2002-12-07 21:39:16 +00004115 PyObject *func, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00004116 static PyObject *nonzero_str, *len_str;
Tim Petersea7f75d2002-12-07 21:39:16 +00004117 int result = -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004118
Guido van Rossum55f20992001-10-01 17:18:22 +00004119 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004120 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00004121 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00004122 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00004123 func = lookup_maybe(self, "__len__", &len_str);
Tim Petersea7f75d2002-12-07 21:39:16 +00004124 if (func == NULL)
4125 return PyErr_Occurred() ? -1 : 1;
4126 }
4127 args = PyTuple_New(0);
4128 if (args != NULL) {
4129 PyObject *temp = PyObject_Call(func, args, NULL);
4130 Py_DECREF(args);
4131 if (temp != NULL) {
4132 result = PyObject_IsTrue(temp);
4133 Py_DECREF(temp);
Guido van Rossum55f20992001-10-01 17:18:22 +00004134 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004135 }
Guido van Rossum55f20992001-10-01 17:18:22 +00004136 Py_DECREF(func);
Tim Petersea7f75d2002-12-07 21:39:16 +00004137 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004138}
4139
Guido van Rossumdc91b992001-08-08 22:26:22 +00004140SLOT0(slot_nb_invert, "__invert__")
4141SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
4142SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
4143SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
4144SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
4145SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004146
4147static int
4148slot_nb_coerce(PyObject **a, PyObject **b)
4149{
4150 static PyObject *coerce_str;
4151 PyObject *self = *a, *other = *b;
4152
4153 if (self->ob_type->tp_as_number != NULL &&
4154 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
4155 PyObject *r;
4156 r = call_maybe(
4157 self, "__coerce__", &coerce_str, "(O)", other);
4158 if (r == NULL)
4159 return -1;
4160 if (r == Py_NotImplemented) {
4161 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004162 }
Guido van Rossum55f20992001-10-01 17:18:22 +00004163 else {
4164 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
4165 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004166 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00004167 Py_DECREF(r);
4168 return -1;
4169 }
4170 *a = PyTuple_GET_ITEM(r, 0);
4171 Py_INCREF(*a);
4172 *b = PyTuple_GET_ITEM(r, 1);
4173 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004174 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00004175 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004176 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004177 }
4178 if (other->ob_type->tp_as_number != NULL &&
4179 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
4180 PyObject *r;
4181 r = call_maybe(
4182 other, "__coerce__", &coerce_str, "(O)", self);
4183 if (r == NULL)
4184 return -1;
4185 if (r == Py_NotImplemented) {
4186 Py_DECREF(r);
4187 return 1;
4188 }
4189 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
4190 PyErr_SetString(PyExc_TypeError,
4191 "__coerce__ didn't return a 2-tuple");
4192 Py_DECREF(r);
4193 return -1;
4194 }
4195 *a = PyTuple_GET_ITEM(r, 1);
4196 Py_INCREF(*a);
4197 *b = PyTuple_GET_ITEM(r, 0);
4198 Py_INCREF(*b);
4199 Py_DECREF(r);
4200 return 0;
4201 }
4202 return 1;
4203}
4204
Guido van Rossumdc91b992001-08-08 22:26:22 +00004205SLOT0(slot_nb_int, "__int__")
4206SLOT0(slot_nb_long, "__long__")
4207SLOT0(slot_nb_float, "__float__")
4208SLOT0(slot_nb_oct, "__oct__")
4209SLOT0(slot_nb_hex, "__hex__")
4210SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
4211SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
4212SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
4213SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
4214SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Guido van Rossum6e5680f2002-10-15 01:01:53 +00004215SLOT1(slot_nb_inplace_power, "__ipow__", PyObject *, "O")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004216SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
4217SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
4218SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
4219SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
4220SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
4221SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
4222 "__floordiv__", "__rfloordiv__")
4223SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
4224SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
4225SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004226
4227static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00004228half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004229{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004230 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004231 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004232 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004233
Guido van Rossum60718732001-08-28 17:47:51 +00004234 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004235 if (func == NULL) {
4236 PyErr_Clear();
4237 }
4238 else {
4239 args = Py_BuildValue("(O)", other);
4240 if (args == NULL)
4241 res = NULL;
4242 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004243 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004244 Py_DECREF(args);
4245 }
Raymond Hettingerab5dae32002-06-24 13:08:16 +00004246 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004247 if (res != Py_NotImplemented) {
4248 if (res == NULL)
4249 return -2;
4250 c = PyInt_AsLong(res);
4251 Py_DECREF(res);
4252 if (c == -1 && PyErr_Occurred())
4253 return -2;
4254 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
4255 }
4256 Py_DECREF(res);
4257 }
4258 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004259}
4260
Guido van Rossumab3b0342001-09-18 20:38:53 +00004261/* This slot is published for the benefit of try_3way_compare in object.c */
4262int
4263_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00004264{
4265 int c;
4266
Guido van Rossumab3b0342001-09-18 20:38:53 +00004267 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004268 c = half_compare(self, other);
4269 if (c <= 1)
4270 return c;
4271 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00004272 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004273 c = half_compare(other, self);
4274 if (c < -1)
4275 return -2;
4276 if (c <= 1)
4277 return -c;
4278 }
4279 return (void *)self < (void *)other ? -1 :
4280 (void *)self > (void *)other ? 1 : 0;
4281}
4282
4283static PyObject *
4284slot_tp_repr(PyObject *self)
4285{
4286 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004287 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004288
Guido van Rossum60718732001-08-28 17:47:51 +00004289 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004290 if (func != NULL) {
4291 res = PyEval_CallObject(func, NULL);
4292 Py_DECREF(func);
4293 return res;
4294 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00004295 PyErr_Clear();
4296 return PyString_FromFormat("<%s object at %p>",
4297 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004298}
4299
4300static PyObject *
4301slot_tp_str(PyObject *self)
4302{
4303 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004304 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004305
Guido van Rossum60718732001-08-28 17:47:51 +00004306 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004307 if (func != NULL) {
4308 res = PyEval_CallObject(func, NULL);
4309 Py_DECREF(func);
4310 return res;
4311 }
4312 else {
4313 PyErr_Clear();
4314 return slot_tp_repr(self);
4315 }
4316}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004317
4318static long
4319slot_tp_hash(PyObject *self)
4320{
Tim Peters61ce0a92002-12-06 23:38:02 +00004321 PyObject *func;
Guido van Rossum60718732001-08-28 17:47:51 +00004322 static PyObject *hash_str, *eq_str, *cmp_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004323 long h;
4324
Guido van Rossum60718732001-08-28 17:47:51 +00004325 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004326
4327 if (func != NULL) {
Tim Peters61ce0a92002-12-06 23:38:02 +00004328 PyObject *res = PyEval_CallObject(func, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004329 Py_DECREF(func);
4330 if (res == NULL)
4331 return -1;
4332 h = PyInt_AsLong(res);
Tim Peters61ce0a92002-12-06 23:38:02 +00004333 Py_DECREF(res);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004334 }
4335 else {
4336 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004337 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004338 if (func == NULL) {
4339 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004340 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004341 }
4342 if (func != NULL) {
4343 Py_DECREF(func);
4344 PyErr_SetString(PyExc_TypeError, "unhashable type");
4345 return -1;
4346 }
4347 PyErr_Clear();
4348 h = _Py_HashPointer((void *)self);
4349 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004350 if (h == -1 && !PyErr_Occurred())
4351 h = -2;
4352 return h;
4353}
4354
4355static PyObject *
4356slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
4357{
Guido van Rossum60718732001-08-28 17:47:51 +00004358 static PyObject *call_str;
4359 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004360 PyObject *res;
4361
4362 if (meth == NULL)
4363 return NULL;
4364 res = PyObject_Call(meth, args, kwds);
4365 Py_DECREF(meth);
4366 return res;
4367}
4368
Guido van Rossum14a6f832001-10-17 13:59:09 +00004369/* There are two slot dispatch functions for tp_getattro.
4370
4371 - slot_tp_getattro() is used when __getattribute__ is overridden
4372 but no __getattr__ hook is present;
4373
4374 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
4375
Guido van Rossumc334df52002-04-04 23:44:47 +00004376 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
4377 detects the absence of __getattr__ and then installs the simpler slot if
4378 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00004379
Tim Peters6d6c1a32001-08-02 04:15:00 +00004380static PyObject *
4381slot_tp_getattro(PyObject *self, PyObject *name)
4382{
Guido van Rossum14a6f832001-10-17 13:59:09 +00004383 static PyObject *getattribute_str = NULL;
4384 return call_method(self, "__getattribute__", &getattribute_str,
4385 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004386}
4387
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004388static PyObject *
4389slot_tp_getattr_hook(PyObject *self, PyObject *name)
4390{
4391 PyTypeObject *tp = self->ob_type;
4392 PyObject *getattr, *getattribute, *res;
4393 static PyObject *getattribute_str = NULL;
4394 static PyObject *getattr_str = NULL;
4395
4396 if (getattr_str == NULL) {
4397 getattr_str = PyString_InternFromString("__getattr__");
4398 if (getattr_str == NULL)
4399 return NULL;
4400 }
4401 if (getattribute_str == NULL) {
4402 getattribute_str =
4403 PyString_InternFromString("__getattribute__");
4404 if (getattribute_str == NULL)
4405 return NULL;
4406 }
4407 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004408 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004409 /* No __getattr__ hook: use a simpler dispatcher */
4410 tp->tp_getattro = slot_tp_getattro;
4411 return slot_tp_getattro(self, name);
4412 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004413 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004414 if (getattribute == NULL ||
4415 (getattribute->ob_type == &PyWrapperDescr_Type &&
4416 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
4417 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004418 res = PyObject_GenericGetAttr(self, name);
4419 else
4420 res = PyObject_CallFunction(getattribute, "OO", self, name);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004421 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004422 PyErr_Clear();
4423 res = PyObject_CallFunction(getattr, "OO", self, name);
4424 }
4425 return res;
4426}
4427
Tim Peters6d6c1a32001-08-02 04:15:00 +00004428static int
4429slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
4430{
4431 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004432 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004433
4434 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004435 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004436 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004437 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004438 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004439 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004440 if (res == NULL)
4441 return -1;
4442 Py_DECREF(res);
4443 return 0;
4444}
4445
4446/* Map rich comparison operators to their __xx__ namesakes */
4447static char *name_op[] = {
4448 "__lt__",
4449 "__le__",
4450 "__eq__",
4451 "__ne__",
4452 "__gt__",
4453 "__ge__",
4454};
4455
4456static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00004457half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004458{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004459 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004460 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00004461
Guido van Rossum60718732001-08-28 17:47:51 +00004462 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004463 if (func == NULL) {
4464 PyErr_Clear();
4465 Py_INCREF(Py_NotImplemented);
4466 return Py_NotImplemented;
4467 }
4468 args = Py_BuildValue("(O)", other);
4469 if (args == NULL)
4470 res = NULL;
4471 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004472 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004473 Py_DECREF(args);
4474 }
4475 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004476 return res;
4477}
4478
Guido van Rossumb8f63662001-08-15 23:57:02 +00004479/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
4480static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
4481
4482static PyObject *
4483slot_tp_richcompare(PyObject *self, PyObject *other, int op)
4484{
4485 PyObject *res;
4486
4487 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
4488 res = half_richcompare(self, other, op);
4489 if (res != Py_NotImplemented)
4490 return res;
4491 Py_DECREF(res);
4492 }
4493 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
4494 res = half_richcompare(other, self, swapped_op[op]);
4495 if (res != Py_NotImplemented) {
4496 return res;
4497 }
4498 Py_DECREF(res);
4499 }
4500 Py_INCREF(Py_NotImplemented);
4501 return Py_NotImplemented;
4502}
4503
4504static PyObject *
4505slot_tp_iter(PyObject *self)
4506{
4507 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004508 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004509
Guido van Rossum60718732001-08-28 17:47:51 +00004510 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004511 if (func != NULL) {
Guido van Rossum84b2bed2002-08-16 17:01:09 +00004512 PyObject *args;
4513 args = res = PyTuple_New(0);
4514 if (args != NULL) {
4515 res = PyObject_Call(func, args, NULL);
4516 Py_DECREF(args);
4517 }
4518 Py_DECREF(func);
4519 return res;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004520 }
4521 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004522 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004523 if (func == NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00004524 PyErr_SetString(PyExc_TypeError,
4525 "iteration over non-sequence");
Guido van Rossumb8f63662001-08-15 23:57:02 +00004526 return NULL;
4527 }
4528 Py_DECREF(func);
4529 return PySeqIter_New(self);
4530}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004531
4532static PyObject *
4533slot_tp_iternext(PyObject *self)
4534{
Guido van Rossum2730b132001-08-28 18:22:14 +00004535 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00004536 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004537}
4538
Guido van Rossum1a493502001-08-17 16:47:50 +00004539static PyObject *
4540slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4541{
4542 PyTypeObject *tp = self->ob_type;
4543 PyObject *get;
4544 static PyObject *get_str = NULL;
4545
4546 if (get_str == NULL) {
4547 get_str = PyString_InternFromString("__get__");
4548 if (get_str == NULL)
4549 return NULL;
4550 }
4551 get = _PyType_Lookup(tp, get_str);
4552 if (get == NULL) {
4553 /* Avoid further slowdowns */
4554 if (tp->tp_descr_get == slot_tp_descr_get)
4555 tp->tp_descr_get = NULL;
4556 Py_INCREF(self);
4557 return self;
4558 }
Guido van Rossum2c252392001-08-24 10:13:31 +00004559 if (obj == NULL)
4560 obj = Py_None;
4561 if (type == NULL)
4562 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00004563 return PyObject_CallFunction(get, "OOO", self, obj, type);
4564}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004565
4566static int
4567slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
4568{
Guido van Rossum2c252392001-08-24 10:13:31 +00004569 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004570 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00004571
4572 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00004573 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004574 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00004575 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004576 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004577 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004578 if (res == NULL)
4579 return -1;
4580 Py_DECREF(res);
4581 return 0;
4582}
4583
4584static int
4585slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
4586{
Guido van Rossum60718732001-08-28 17:47:51 +00004587 static PyObject *init_str;
4588 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004589 PyObject *res;
4590
4591 if (meth == NULL)
4592 return -1;
4593 res = PyObject_Call(meth, args, kwds);
4594 Py_DECREF(meth);
4595 if (res == NULL)
4596 return -1;
4597 Py_DECREF(res);
4598 return 0;
4599}
4600
4601static PyObject *
4602slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4603{
Guido van Rossum7bed2132002-08-08 21:57:53 +00004604 static PyObject *new_str;
4605 PyObject *func;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004606 PyObject *newargs, *x;
4607 int i, n;
4608
Guido van Rossum7bed2132002-08-08 21:57:53 +00004609 if (new_str == NULL) {
4610 new_str = PyString_InternFromString("__new__");
4611 if (new_str == NULL)
4612 return NULL;
4613 }
4614 func = PyObject_GetAttr((PyObject *)type, new_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004615 if (func == NULL)
4616 return NULL;
4617 assert(PyTuple_Check(args));
4618 n = PyTuple_GET_SIZE(args);
4619 newargs = PyTuple_New(n+1);
4620 if (newargs == NULL)
4621 return NULL;
4622 Py_INCREF(type);
4623 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
4624 for (i = 0; i < n; i++) {
4625 x = PyTuple_GET_ITEM(args, i);
4626 Py_INCREF(x);
4627 PyTuple_SET_ITEM(newargs, i+1, x);
4628 }
4629 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00004630 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004631 Py_DECREF(func);
4632 return x;
4633}
4634
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004635static void
4636slot_tp_del(PyObject *self)
4637{
4638 static PyObject *del_str = NULL;
4639 PyObject *del, *res;
4640 PyObject *error_type, *error_value, *error_traceback;
4641
4642 /* Temporarily resurrect the object. */
4643 assert(self->ob_refcnt == 0);
4644 self->ob_refcnt = 1;
4645
4646 /* Save the current exception, if any. */
4647 PyErr_Fetch(&error_type, &error_value, &error_traceback);
4648
4649 /* Execute __del__ method, if any. */
4650 del = lookup_maybe(self, "__del__", &del_str);
4651 if (del != NULL) {
4652 res = PyEval_CallObject(del, NULL);
4653 if (res == NULL)
4654 PyErr_WriteUnraisable(del);
4655 else
4656 Py_DECREF(res);
4657 Py_DECREF(del);
4658 }
4659
4660 /* Restore the saved exception. */
4661 PyErr_Restore(error_type, error_value, error_traceback);
4662
4663 /* Undo the temporary resurrection; can't use DECREF here, it would
4664 * cause a recursive call.
4665 */
4666 assert(self->ob_refcnt > 0);
4667 if (--self->ob_refcnt == 0)
4668 return; /* this is the normal path out */
4669
4670 /* __del__ resurrected it! Make it look like the original Py_DECREF
4671 * never happened.
4672 */
4673 {
4674 int refcnt = self->ob_refcnt;
4675 _Py_NewReference(self);
4676 self->ob_refcnt = refcnt;
4677 }
4678 assert(!PyType_IS_GC(self->ob_type) ||
4679 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
4680 /* If Py_REF_DEBUG, the original decref dropped _Py_RefTotal, but
4681 * _Py_NewReference bumped it again, so that's a wash.
4682 * If Py_TRACE_REFS, _Py_NewReference re-added self to the object
4683 * chain, so no more to do there either.
4684 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
4685 * _Py_NewReference bumped tp_allocs: both of those need to be
4686 * undone.
4687 */
4688#ifdef COUNT_ALLOCS
4689 --self->ob_type->tp_frees;
4690 --self->ob_type->tp_allocs;
4691#endif
4692}
4693
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004694
4695/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
Tim Petersbf9b2442003-03-23 05:35:36 +00004696 functions. The offsets here are relative to the 'PyHeapTypeObject'
Guido van Rossume5c691a2003-03-07 15:13:17 +00004697 structure, which incorporates the additional structures used for numbers,
4698 sequences and mappings.
4699 Note that multiple names may map to the same slot (e.g. __eq__,
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004700 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00004701 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
4702 terminated with an all-zero entry. (This table is further initialized and
4703 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004704
Guido van Rossum6d204072001-10-21 00:44:31 +00004705typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004706
4707#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00004708#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004709#undef ETSLOT
4710#undef SQSLOT
4711#undef MPSLOT
4712#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00004713#undef UNSLOT
4714#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004715#undef BINSLOT
4716#undef RBINSLOT
4717
Guido van Rossum6d204072001-10-21 00:44:31 +00004718#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004719 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
4720 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00004721#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
4722 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004723 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00004724#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Guido van Rossume5c691a2003-03-07 15:13:17 +00004725 {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004726 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00004727#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4728 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
4729#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4730 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
4731#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4732 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
4733#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4734 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
4735 "x." NAME "() <==> " DOC)
4736#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4737 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
4738 "x." NAME "(y) <==> x" DOC "y")
4739#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
4740 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
4741 "x." NAME "(y) <==> x" DOC "y")
4742#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
4743 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
4744 "x." NAME "(y) <==> y" DOC "x")
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004745
4746static slotdef slotdefs[] = {
Guido van Rossum6d204072001-10-21 00:44:31 +00004747 SQSLOT("__len__", sq_length, slot_sq_length, wrap_inquiry,
4748 "x.__len__() <==> len(x)"),
4749 SQSLOT("__add__", sq_concat, slot_sq_concat, wrap_binaryfunc,
4750 "x.__add__(y) <==> x+y"),
4751 SQSLOT("__mul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
4752 "x.__mul__(n) <==> x*n"),
4753 SQSLOT("__rmul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
4754 "x.__rmul__(n) <==> n*x"),
4755 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
4756 "x.__getitem__(y) <==> x[y]"),
4757 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_intintargfunc,
4758 "x.__getslice__(i, j) <==> x[i:j]"),
4759 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
4760 "x.__setitem__(i, y) <==> x[i]=y"),
4761 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
4762 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004763 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Guido van Rossum6d204072001-10-21 00:44:31 +00004764 wrap_intintobjargproc,
4765 "x.__setslice__(i, j, y) <==> x[i:j]=y"),
4766 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
4767 "x.__delslice__(i, j) <==> del x[i:j]"),
4768 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
4769 "x.__contains__(y) <==> y in x"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004770 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat,
Guido van Rossum6d204072001-10-21 00:44:31 +00004771 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004772 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat,
Guido van Rossum6d204072001-10-21 00:44:31 +00004773 wrap_intargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004774
Guido van Rossum6d204072001-10-21 00:44:31 +00004775 MPSLOT("__len__", mp_length, slot_mp_length, wrap_inquiry,
4776 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00004777 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004778 wrap_binaryfunc,
4779 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004780 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004781 wrap_objobjargproc,
4782 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004783 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004784 wrap_delitem,
4785 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004786
Guido van Rossum6d204072001-10-21 00:44:31 +00004787 BINSLOT("__add__", nb_add, slot_nb_add,
4788 "+"),
4789 RBINSLOT("__radd__", nb_add, slot_nb_add,
4790 "+"),
4791 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
4792 "-"),
4793 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
4794 "-"),
4795 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
4796 "*"),
4797 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
4798 "*"),
4799 BINSLOT("__div__", nb_divide, slot_nb_divide,
4800 "/"),
4801 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
4802 "/"),
4803 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
4804 "%"),
4805 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
4806 "%"),
4807 BINSLOT("__divmod__", nb_divmod, slot_nb_divmod,
4808 "divmod(x, y)"),
4809 RBINSLOT("__rdivmod__", nb_divmod, slot_nb_divmod,
4810 "divmod(y, x)"),
4811 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
4812 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
4813 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
4814 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
4815 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
4816 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
4817 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
4818 "abs(x)"),
Guido van Rossumdfce3bf2002-03-10 14:11:16 +00004819 UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquiry,
Guido van Rossum6d204072001-10-21 00:44:31 +00004820 "x != 0"),
4821 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
4822 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
4823 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
4824 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
4825 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
4826 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
4827 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
4828 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
4829 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
4830 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
4831 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
4832 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
4833 "x.__coerce__(y) <==> coerce(x, y)"),
4834 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
4835 "int(x)"),
4836 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
4837 "long(x)"),
4838 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
4839 "float(x)"),
4840 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
4841 "oct(x)"),
4842 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
4843 "hex(x)"),
4844 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
4845 wrap_binaryfunc, "+"),
4846 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
4847 wrap_binaryfunc, "-"),
4848 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
4849 wrap_binaryfunc, "*"),
4850 IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
4851 wrap_binaryfunc, "/"),
4852 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
4853 wrap_binaryfunc, "%"),
4854 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
Guido van Rossum6e5680f2002-10-15 01:01:53 +00004855 wrap_binaryfunc, "**"),
Guido van Rossum6d204072001-10-21 00:44:31 +00004856 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
4857 wrap_binaryfunc, "<<"),
4858 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
4859 wrap_binaryfunc, ">>"),
4860 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
4861 wrap_binaryfunc, "&"),
4862 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
4863 wrap_binaryfunc, "^"),
4864 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
4865 wrap_binaryfunc, "|"),
4866 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
4867 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
4868 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
4869 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
4870 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
4871 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
4872 IBSLOT("__itruediv__", nb_inplace_true_divide,
4873 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004874
Guido van Rossum6d204072001-10-21 00:44:31 +00004875 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
4876 "x.__str__() <==> str(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00004877 TPSLOT("__str__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00004878 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
4879 "x.__repr__() <==> repr(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00004880 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00004881 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
4882 "x.__cmp__(y) <==> cmp(x,y)"),
4883 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
4884 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00004885 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
4886 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004887 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00004888 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
4889 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
4890 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
4891 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
4892 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
4893 "x.__setattr__('name', value) <==> x.name = value"),
4894 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
4895 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
4896 "x.__delattr__('name') <==> del x.name"),
4897 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
4898 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
4899 "x.__lt__(y) <==> x<y"),
4900 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
4901 "x.__le__(y) <==> x<=y"),
4902 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
4903 "x.__eq__(y) <==> x==y"),
4904 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
4905 "x.__ne__(y) <==> x!=y"),
4906 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
4907 "x.__gt__(y) <==> x>y"),
4908 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
4909 "x.__ge__(y) <==> x>=y"),
4910 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
4911 "x.__iter__() <==> iter(x)"),
4912 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
4913 "x.next() -> the next value, or raise StopIteration"),
4914 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
4915 "descr.__get__(obj[, type]) -> value"),
4916 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
4917 "descr.__set__(obj, value)"),
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004918 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
4919 wrap_descr_delete, "descr.__delete__(obj)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00004920 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00004921 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00004922 "see x.__class__.__doc__ for signature",
4923 PyWrapperFlag_KEYWORDS),
4924 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004925 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004926 {NULL}
4927};
4928
Guido van Rossumc334df52002-04-04 23:44:47 +00004929/* Given a type pointer and an offset gotten from a slotdef entry, return a
4930 pointer to the actual slot. This is not quite the same as simply adding
4931 the offset to the type pointer, since it takes care to indirect through the
4932 proper indirection pointer (as_buffer, etc.); it returns NULL if the
4933 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004934static void **
4935slotptr(PyTypeObject *type, int offset)
4936{
4937 char *ptr;
4938
Guido van Rossume5c691a2003-03-07 15:13:17 +00004939 /* Note: this depends on the order of the members of PyHeapTypeObject! */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004940 assert(offset >= 0);
Guido van Rossume5c691a2003-03-07 15:13:17 +00004941 assert(offset < offsetof(PyHeapTypeObject, as_buffer));
4942 if (offset >= offsetof(PyHeapTypeObject, as_sequence)) {
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004943 ptr = (void *)type->tp_as_sequence;
Guido van Rossume5c691a2003-03-07 15:13:17 +00004944 offset -= offsetof(PyHeapTypeObject, as_sequence);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004945 }
Guido van Rossume5c691a2003-03-07 15:13:17 +00004946 else if (offset >= offsetof(PyHeapTypeObject, as_mapping)) {
Guido van Rossum09638c12002-06-13 19:17:46 +00004947 ptr = (void *)type->tp_as_mapping;
Guido van Rossume5c691a2003-03-07 15:13:17 +00004948 offset -= offsetof(PyHeapTypeObject, as_mapping);
Guido van Rossum09638c12002-06-13 19:17:46 +00004949 }
Guido van Rossume5c691a2003-03-07 15:13:17 +00004950 else if (offset >= offsetof(PyHeapTypeObject, as_number)) {
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004951 ptr = (void *)type->tp_as_number;
Guido van Rossume5c691a2003-03-07 15:13:17 +00004952 offset -= offsetof(PyHeapTypeObject, as_number);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004953 }
4954 else {
4955 ptr = (void *)type;
4956 }
4957 if (ptr != NULL)
4958 ptr += offset;
4959 return (void **)ptr;
4960}
Guido van Rossumf040ede2001-08-07 16:40:56 +00004961
Guido van Rossumc334df52002-04-04 23:44:47 +00004962/* Length of array of slotdef pointers used to store slots with the
4963 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
4964 the same __name__, for any __name__. Since that's a static property, it is
4965 appropriate to declare fixed-size arrays for this. */
4966#define MAX_EQUIV 10
4967
4968/* Return a slot pointer for a given name, but ONLY if the attribute has
4969 exactly one slot function. The name must be an interned string. */
4970static void **
4971resolve_slotdups(PyTypeObject *type, PyObject *name)
4972{
4973 /* XXX Maybe this could be optimized more -- but is it worth it? */
4974
4975 /* pname and ptrs act as a little cache */
4976 static PyObject *pname;
4977 static slotdef *ptrs[MAX_EQUIV];
4978 slotdef *p, **pp;
4979 void **res, **ptr;
4980
4981 if (pname != name) {
4982 /* Collect all slotdefs that match name into ptrs. */
4983 pname = name;
4984 pp = ptrs;
4985 for (p = slotdefs; p->name_strobj; p++) {
4986 if (p->name_strobj == name)
4987 *pp++ = p;
4988 }
4989 *pp = NULL;
4990 }
4991
4992 /* Look in all matching slots of the type; if exactly one of these has
4993 a filled-in slot, return its value. Otherwise return NULL. */
4994 res = NULL;
4995 for (pp = ptrs; *pp; pp++) {
4996 ptr = slotptr(type, (*pp)->offset);
4997 if (ptr == NULL || *ptr == NULL)
4998 continue;
4999 if (res != NULL)
5000 return NULL;
5001 res = ptr;
5002 }
5003 return res;
5004}
5005
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005006/* Common code for update_slots_callback() and fixup_slot_dispatchers(). This
Guido van Rossumc334df52002-04-04 23:44:47 +00005007 does some incredibly complex thinking and then sticks something into the
5008 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
5009 interests, and then stores a generic wrapper or a specific function into
5010 the slot.) Return a pointer to the next slotdef with a different offset,
5011 because that's convenient for fixup_slot_dispatchers(). */
5012static slotdef *
5013update_one_slot(PyTypeObject *type, slotdef *p)
5014{
5015 PyObject *descr;
5016 PyWrapperDescrObject *d;
5017 void *generic = NULL, *specific = NULL;
5018 int use_generic = 0;
5019 int offset = p->offset;
5020 void **ptr = slotptr(type, offset);
5021
5022 if (ptr == NULL) {
5023 do {
5024 ++p;
5025 } while (p->offset == offset);
5026 return p;
5027 }
5028 do {
5029 descr = _PyType_Lookup(type, p->name_strobj);
5030 if (descr == NULL)
5031 continue;
5032 if (descr->ob_type == &PyWrapperDescr_Type) {
5033 void **tptr = resolve_slotdups(type, p->name_strobj);
5034 if (tptr == NULL || tptr == ptr)
5035 generic = p->function;
5036 d = (PyWrapperDescrObject *)descr;
5037 if (d->d_base->wrapper == p->wrapper &&
5038 PyType_IsSubtype(type, d->d_type))
5039 {
5040 if (specific == NULL ||
5041 specific == d->d_wrapped)
5042 specific = d->d_wrapped;
5043 else
5044 use_generic = 1;
5045 }
5046 }
Guido van Rossum721f62e2002-08-09 02:14:34 +00005047 else if (descr->ob_type == &PyCFunction_Type &&
5048 PyCFunction_GET_FUNCTION(descr) ==
5049 (PyCFunction)tp_new_wrapper &&
5050 strcmp(p->name, "__new__") == 0)
5051 {
5052 /* The __new__ wrapper is not a wrapper descriptor,
5053 so must be special-cased differently.
5054 If we don't do this, creating an instance will
5055 always use slot_tp_new which will look up
5056 __new__ in the MRO which will call tp_new_wrapper
5057 which will look through the base classes looking
5058 for a static base and call its tp_new (usually
5059 PyType_GenericNew), after performing various
5060 sanity checks and constructing a new argument
5061 list. Cut all that nonsense short -- this speeds
5062 up instance creation tremendously. */
5063 specific = type->tp_new;
5064 /* XXX I'm not 100% sure that there isn't a hole
5065 in this reasoning that requires additional
5066 sanity checks. I'll buy the first person to
5067 point out a bug in this reasoning a beer. */
5068 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005069 else {
5070 use_generic = 1;
5071 generic = p->function;
5072 }
5073 } while ((++p)->offset == offset);
5074 if (specific && !use_generic)
5075 *ptr = specific;
5076 else
5077 *ptr = generic;
5078 return p;
5079}
5080
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005081/* In the type, update the slots whose slotdefs are gathered in the pp array.
5082 This is a callback for update_subclasses(). */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005083static int
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005084update_slots_callback(PyTypeObject *type, void *data)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005085{
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005086 slotdef **pp = (slotdef **)data;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005087
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005088 for (; *pp; pp++)
Guido van Rossumc334df52002-04-04 23:44:47 +00005089 update_one_slot(type, *pp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005090 return 0;
5091}
5092
Guido van Rossumc334df52002-04-04 23:44:47 +00005093/* Comparison function for qsort() to compare slotdefs by their offset, and
5094 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005095static int
5096slotdef_cmp(const void *aa, const void *bb)
5097{
5098 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
5099 int c = a->offset - b->offset;
5100 if (c != 0)
5101 return c;
5102 else
5103 return a - b;
5104}
5105
Guido van Rossumc334df52002-04-04 23:44:47 +00005106/* Initialize the slotdefs table by adding interned string objects for the
5107 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005108static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005109init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005110{
5111 slotdef *p;
5112 static int initialized = 0;
5113
5114 if (initialized)
5115 return;
5116 for (p = slotdefs; p->name; p++) {
5117 p->name_strobj = PyString_InternFromString(p->name);
5118 if (!p->name_strobj)
Guido van Rossumc334df52002-04-04 23:44:47 +00005119 Py_FatalError("Out of memory interning slotdef names");
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005120 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005121 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
5122 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005123 initialized = 1;
5124}
5125
Guido van Rossumc334df52002-04-04 23:44:47 +00005126/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005127static int
5128update_slot(PyTypeObject *type, PyObject *name)
5129{
Guido van Rossumc334df52002-04-04 23:44:47 +00005130 slotdef *ptrs[MAX_EQUIV];
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005131 slotdef *p;
5132 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005133 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005134
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005135 init_slotdefs();
5136 pp = ptrs;
5137 for (p = slotdefs; p->name; p++) {
5138 /* XXX assume name is interned! */
5139 if (p->name_strobj == name)
5140 *pp++ = p;
5141 }
5142 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005143 for (pp = ptrs; *pp; pp++) {
5144 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005145 offset = p->offset;
5146 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005147 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005148 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005149 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005150 if (ptrs[0] == NULL)
5151 return 0; /* Not an attribute that affects any slots */
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005152 return update_subclasses(type, name,
5153 update_slots_callback, (void *)ptrs);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005154}
5155
Guido van Rossumc334df52002-04-04 23:44:47 +00005156/* Store the proper functions in the slot dispatches at class (type)
5157 definition time, based upon which operations the class overrides in its
5158 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00005159static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005160fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005161{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005162 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005163
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005164 init_slotdefs();
Guido van Rossumc334df52002-04-04 23:44:47 +00005165 for (p = slotdefs; p->name; )
5166 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005167}
Guido van Rossum705f0f52001-08-24 16:47:00 +00005168
Michael W. Hudson98bbc492002-11-26 14:47:27 +00005169static void
5170update_all_slots(PyTypeObject* type)
5171{
5172 slotdef *p;
5173
5174 init_slotdefs();
5175 for (p = slotdefs; p->name; p++) {
5176 /* update_slot returns int but can't actually fail */
5177 update_slot(type, p->name_strobj);
5178 }
5179}
5180
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005181/* recurse_down_subclasses() and update_subclasses() are mutually
5182 recursive functions to call a callback for all subclasses,
5183 but refraining from recursing into subclasses that define 'name'. */
5184
5185static int
5186update_subclasses(PyTypeObject *type, PyObject *name,
5187 update_callback callback, void *data)
5188{
5189 if (callback(type, data) < 0)
5190 return -1;
5191 return recurse_down_subclasses(type, name, callback, data);
5192}
5193
5194static int
5195recurse_down_subclasses(PyTypeObject *type, PyObject *name,
5196 update_callback callback, void *data)
5197{
5198 PyTypeObject *subclass;
5199 PyObject *ref, *subclasses, *dict;
5200 int i, n;
5201
5202 subclasses = type->tp_subclasses;
5203 if (subclasses == NULL)
5204 return 0;
5205 assert(PyList_Check(subclasses));
5206 n = PyList_GET_SIZE(subclasses);
5207 for (i = 0; i < n; i++) {
5208 ref = PyList_GET_ITEM(subclasses, i);
5209 assert(PyWeakref_CheckRef(ref));
5210 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
5211 assert(subclass != NULL);
5212 if ((PyObject *)subclass == Py_None)
5213 continue;
5214 assert(PyType_Check(subclass));
5215 /* Avoid recursing down into unaffected classes */
5216 dict = subclass->tp_dict;
5217 if (dict != NULL && PyDict_Check(dict) &&
5218 PyDict_GetItem(dict, name) != NULL)
5219 continue;
5220 if (update_subclasses(subclass, name, callback, data) < 0)
5221 return -1;
5222 }
5223 return 0;
5224}
5225
Guido van Rossum6d204072001-10-21 00:44:31 +00005226/* This function is called by PyType_Ready() to populate the type's
5227 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00005228 function slot (like tp_repr) that's defined in the type, one or more
5229 corresponding descriptors are added in the type's tp_dict dictionary
5230 under the appropriate name (like __repr__). Some function slots
5231 cause more than one descriptor to be added (for example, the nb_add
5232 slot adds both __add__ and __radd__ descriptors) and some function
5233 slots compete for the same descriptor (for example both sq_item and
5234 mp_subscript generate a __getitem__ descriptor).
5235
5236 In the latter case, the first slotdef entry encoutered wins. Since
Tim Petersbf9b2442003-03-23 05:35:36 +00005237 slotdef entries are sorted by the offset of the slot in the
Guido van Rossume5c691a2003-03-07 15:13:17 +00005238 PyHeapTypeObject, this gives us some control over disambiguating
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005239 between competing slots: the members of PyHeapTypeObject are listed
5240 from most general to least general, so the most general slot is
5241 preferred. In particular, because as_mapping comes before as_sequence,
5242 for a type that defines both mp_subscript and sq_item, mp_subscript
5243 wins.
Guido van Rossum09638c12002-06-13 19:17:46 +00005244
5245 This only adds new descriptors and doesn't overwrite entries in
5246 tp_dict that were previously defined. The descriptors contain a
5247 reference to the C function they must call, so that it's safe if they
5248 are copied into a subtype's __dict__ and the subtype has a different
5249 C function in its slot -- calling the method defined by the
5250 descriptor will call the C function that was used to create it,
5251 rather than the C function present in the slot when it is called.
5252 (This is important because a subtype may have a C function in the
5253 slot that calls the method from the dictionary, and we want to avoid
5254 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00005255
5256static int
5257add_operators(PyTypeObject *type)
5258{
5259 PyObject *dict = type->tp_dict;
5260 slotdef *p;
5261 PyObject *descr;
5262 void **ptr;
5263
5264 init_slotdefs();
5265 for (p = slotdefs; p->name; p++) {
5266 if (p->wrapper == NULL)
5267 continue;
5268 ptr = slotptr(type, p->offset);
5269 if (!ptr || !*ptr)
5270 continue;
5271 if (PyDict_GetItem(dict, p->name_strobj))
5272 continue;
5273 descr = PyDescr_NewWrapper(type, p, *ptr);
5274 if (descr == NULL)
5275 return -1;
5276 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
5277 return -1;
5278 Py_DECREF(descr);
5279 }
5280 if (type->tp_new != NULL) {
5281 if (add_tp_new_wrapper(type) < 0)
5282 return -1;
5283 }
5284 return 0;
5285}
5286
Guido van Rossum705f0f52001-08-24 16:47:00 +00005287
5288/* Cooperative 'super' */
5289
5290typedef struct {
5291 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00005292 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005293 PyObject *obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005294 PyTypeObject *obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005295} superobject;
5296
Guido van Rossum6f799372001-09-20 20:46:19 +00005297static PyMemberDef super_members[] = {
5298 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
5299 "the class invoking super()"},
5300 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
5301 "the instance invoking super(); may be None"},
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005302 {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
5303 "the type of the the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005304 {0}
5305};
5306
Guido van Rossum705f0f52001-08-24 16:47:00 +00005307static void
5308super_dealloc(PyObject *self)
5309{
5310 superobject *su = (superobject *)self;
5311
Guido van Rossum048eb752001-10-02 21:24:57 +00005312 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005313 Py_XDECREF(su->obj);
5314 Py_XDECREF(su->type);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005315 Py_XDECREF(su->obj_type);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005316 self->ob_type->tp_free(self);
5317}
5318
5319static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005320super_repr(PyObject *self)
5321{
5322 superobject *su = (superobject *)self;
5323
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005324 if (su->obj_type)
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005325 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005326 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005327 su->type ? su->type->tp_name : "NULL",
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005328 su->obj_type->tp_name);
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005329 else
5330 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005331 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005332 su->type ? su->type->tp_name : "NULL");
5333}
5334
5335static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00005336super_getattro(PyObject *self, PyObject *name)
5337{
5338 superobject *su = (superobject *)self;
5339
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005340 if (su->obj_type != NULL) {
Tim Petersa91e9642001-11-14 23:32:33 +00005341 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005342 PyTypeObject *starttype;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005343 descrgetfunc f;
5344 int i, n;
5345
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005346 starttype = su->obj_type;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005347 mro = starttype->tp_mro;
5348
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005349 if (mro == NULL)
5350 n = 0;
5351 else {
5352 assert(PyTuple_Check(mro));
5353 n = PyTuple_GET_SIZE(mro);
5354 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005355 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00005356 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00005357 break;
5358 }
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005359#if 0
Guido van Rossume705ef12001-08-29 15:47:06 +00005360 if (i >= n && PyType_Check(su->obj)) {
Guido van Rossum155db9a2002-04-02 17:53:47 +00005361 starttype = (PyTypeObject *)(su->obj);
5362 mro = starttype->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005363 if (mro == NULL)
5364 n = 0;
5365 else {
5366 assert(PyTuple_Check(mro));
5367 n = PyTuple_GET_SIZE(mro);
5368 }
Guido van Rossume705ef12001-08-29 15:47:06 +00005369 for (i = 0; i < n; i++) {
5370 if ((PyObject *)(su->type) ==
5371 PyTuple_GET_ITEM(mro, i))
5372 break;
5373 }
Guido van Rossume705ef12001-08-29 15:47:06 +00005374 }
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005375#endif
Guido van Rossum705f0f52001-08-24 16:47:00 +00005376 i++;
5377 res = NULL;
5378 for (; i < n; i++) {
5379 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00005380 if (PyType_Check(tmp))
5381 dict = ((PyTypeObject *)tmp)->tp_dict;
5382 else if (PyClass_Check(tmp))
5383 dict = ((PyClassObject *)tmp)->cl_dict;
5384 else
5385 continue;
5386 res = PyDict_GetItem(dict, name);
Guido van Rossum5b443c62001-12-03 15:38:28 +00005387 if (res != NULL && !PyDescr_IsData(res)) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00005388 Py_INCREF(res);
5389 f = res->ob_type->tp_descr_get;
5390 if (f != NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00005391 tmp = f(res, su->obj,
5392 (PyObject *)starttype);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005393 Py_DECREF(res);
5394 res = tmp;
5395 }
5396 return res;
5397 }
5398 }
5399 }
5400 return PyObject_GenericGetAttr(self, name);
5401}
5402
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005403static PyTypeObject *
Guido van Rossum5b443c62001-12-03 15:38:28 +00005404supercheck(PyTypeObject *type, PyObject *obj)
5405{
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005406 /* Check that a super() call makes sense. Return a type object.
5407
5408 obj can be a new-style class, or an instance of one:
5409
5410 - If it is a class, it must be a subclass of 'type'. This case is
5411 used for class methods; the return value is obj.
5412
5413 - If it is an instance, it must be an instance of 'type'. This is
5414 the normal case; the return value is obj.__class__.
5415
5416 But... when obj is an instance, we want to allow for the case where
5417 obj->ob_type is not a subclass of type, but obj.__class__ is!
5418 This will allow using super() with a proxy for obj.
5419 */
5420
Guido van Rossum8e80a722003-02-18 19:22:22 +00005421 /* Check for first bullet above (special case) */
5422 if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
5423 Py_INCREF(obj);
5424 return (PyTypeObject *)obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005425 }
Guido van Rossum8e80a722003-02-18 19:22:22 +00005426
5427 /* Normal case */
5428 if (PyType_IsSubtype(obj->ob_type, type)) {
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005429 Py_INCREF(obj->ob_type);
5430 return obj->ob_type;
5431 }
5432 else {
5433 /* Try the slow way */
5434 static PyObject *class_str = NULL;
5435 PyObject *class_attr;
5436
5437 if (class_str == NULL) {
5438 class_str = PyString_FromString("__class__");
5439 if (class_str == NULL)
5440 return NULL;
5441 }
5442
5443 class_attr = PyObject_GetAttr(obj, class_str);
5444
5445 if (class_attr != NULL &&
5446 PyType_Check(class_attr) &&
5447 (PyTypeObject *)class_attr != obj->ob_type)
5448 {
5449 int ok = PyType_IsSubtype(
5450 (PyTypeObject *)class_attr, type);
5451 if (ok)
5452 return (PyTypeObject *)class_attr;
5453 }
5454
5455 if (class_attr == NULL)
5456 PyErr_Clear();
5457 else
5458 Py_DECREF(class_attr);
5459 }
5460
Tim Peters97e5ff52003-02-18 19:32:50 +00005461 PyErr_SetString(PyExc_TypeError,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005462 "super(type, obj): "
5463 "obj must be an instance or subtype of type");
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005464 return NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005465}
5466
Guido van Rossum705f0f52001-08-24 16:47:00 +00005467static PyObject *
5468super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5469{
5470 superobject *su = (superobject *)self;
5471 superobject *new;
5472
5473 if (obj == NULL || obj == Py_None || su->obj != NULL) {
5474 /* Not binding to an object, or already bound */
5475 Py_INCREF(self);
5476 return self;
5477 }
Guido van Rossum5b443c62001-12-03 15:38:28 +00005478 if (su->ob_type != &PySuper_Type)
5479 /* If su is an instance of a subclass of super,
5480 call its type */
5481 return PyObject_CallFunction((PyObject *)su->ob_type,
5482 "OO", su->type, obj);
5483 else {
5484 /* Inline the common case */
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005485 PyTypeObject *obj_type = supercheck(su->type, obj);
5486 if (obj_type == NULL)
Guido van Rossum5b443c62001-12-03 15:38:28 +00005487 return NULL;
5488 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
5489 NULL, NULL);
5490 if (new == NULL)
5491 return NULL;
5492 Py_INCREF(su->type);
5493 Py_INCREF(obj);
5494 new->type = su->type;
5495 new->obj = obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005496 new->obj_type = obj_type;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005497 return (PyObject *)new;
5498 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005499}
5500
5501static int
5502super_init(PyObject *self, PyObject *args, PyObject *kwds)
5503{
5504 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00005505 PyTypeObject *type;
5506 PyObject *obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005507 PyTypeObject *obj_type = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005508
5509 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
5510 return -1;
5511 if (obj == Py_None)
5512 obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005513 if (obj != NULL) {
5514 obj_type = supercheck(type, obj);
5515 if (obj_type == NULL)
5516 return -1;
5517 Py_INCREF(obj);
5518 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005519 Py_INCREF(type);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005520 su->type = type;
5521 su->obj = obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005522 su->obj_type = obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005523 return 0;
5524}
5525
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005526PyDoc_STRVAR(super_doc,
Guido van Rossum705f0f52001-08-24 16:47:00 +00005527"super(type) -> unbound super object\n"
5528"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00005529"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00005530"Typical use to call a cooperative superclass method:\n"
5531"class C(B):\n"
5532" def meth(self, arg):\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005533" super(C, self).meth(arg)");
Guido van Rossum705f0f52001-08-24 16:47:00 +00005534
Guido van Rossum048eb752001-10-02 21:24:57 +00005535static int
5536super_traverse(PyObject *self, visitproc visit, void *arg)
5537{
5538 superobject *su = (superobject *)self;
5539 int err;
5540
5541#define VISIT(SLOT) \
5542 if (SLOT) { \
5543 err = visit((PyObject *)(SLOT), arg); \
5544 if (err) \
5545 return err; \
5546 }
5547
5548 VISIT(su->obj);
5549 VISIT(su->type);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005550 VISIT(su->obj_type);
Guido van Rossum048eb752001-10-02 21:24:57 +00005551
5552#undef VISIT
5553
5554 return 0;
5555}
5556
Guido van Rossum705f0f52001-08-24 16:47:00 +00005557PyTypeObject PySuper_Type = {
5558 PyObject_HEAD_INIT(&PyType_Type)
5559 0, /* ob_size */
5560 "super", /* tp_name */
5561 sizeof(superobject), /* tp_basicsize */
5562 0, /* tp_itemsize */
5563 /* methods */
5564 super_dealloc, /* tp_dealloc */
5565 0, /* tp_print */
5566 0, /* tp_getattr */
5567 0, /* tp_setattr */
5568 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005569 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005570 0, /* tp_as_number */
5571 0, /* tp_as_sequence */
5572 0, /* tp_as_mapping */
5573 0, /* tp_hash */
5574 0, /* tp_call */
5575 0, /* tp_str */
5576 super_getattro, /* tp_getattro */
5577 0, /* tp_setattro */
5578 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00005579 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
5580 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005581 super_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00005582 super_traverse, /* tp_traverse */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005583 0, /* tp_clear */
5584 0, /* tp_richcompare */
5585 0, /* tp_weaklistoffset */
5586 0, /* tp_iter */
5587 0, /* tp_iternext */
5588 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005589 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005590 0, /* tp_getset */
5591 0, /* tp_base */
5592 0, /* tp_dict */
5593 super_descr_get, /* tp_descr_get */
5594 0, /* tp_descr_set */
5595 0, /* tp_dictoffset */
5596 super_init, /* tp_init */
5597 PyType_GenericAlloc, /* tp_alloc */
5598 PyType_GenericNew, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00005599 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005600};