blob: 91c40b9999df1632da1b2352c7766fdecb102295 [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 Hettingerf394df42003-04-06 19:13:41 +00001085 off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \
1086consistent method resolution\norder (MRO) for bases");
Guido van Rossum98f33732002-11-25 21:36:54 +00001087 i = 0;
1088 while (PyDict_Next(set, &i, &k, &v) && off < sizeof(buf)) {
1089 PyObject *name = class_name(k);
1090 off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s",
1091 name ? PyString_AS_STRING(name) : "?");
1092 Py_XDECREF(name);
1093 if (--n && off+1 < sizeof(buf)) {
1094 buf[off++] = ',';
1095 buf[off] = '\0';
1096 }
1097 }
1098 PyErr_SetString(PyExc_TypeError, buf);
1099 Py_DECREF(set);
1100}
1101
Tim Petersea7f75d2002-12-07 21:39:16 +00001102static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001103pmerge(PyObject *acc, PyObject* to_merge) {
1104 int i, j, to_merge_size;
1105 int *remain;
1106 int ok, empty_cnt;
Tim Petersea7f75d2002-12-07 21:39:16 +00001107
Guido van Rossum1f121312002-11-14 19:49:16 +00001108 to_merge_size = PyList_GET_SIZE(to_merge);
1109
Guido van Rossum98f33732002-11-25 21:36:54 +00001110 /* remain stores an index into each sublist of to_merge.
1111 remain[i] is the index of the next base in to_merge[i]
1112 that is not included in acc.
1113 */
Guido van Rossum1f121312002-11-14 19:49:16 +00001114 remain = PyMem_MALLOC(SIZEOF_INT*to_merge_size);
1115 if (remain == NULL)
1116 return -1;
1117 for (i = 0; i < to_merge_size; i++)
1118 remain[i] = 0;
1119
1120 again:
1121 empty_cnt = 0;
1122 for (i = 0; i < to_merge_size; i++) {
1123 PyObject *candidate;
Tim Petersea7f75d2002-12-07 21:39:16 +00001124
Guido van Rossum1f121312002-11-14 19:49:16 +00001125 PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
1126
1127 if (remain[i] >= PyList_GET_SIZE(cur_list)) {
1128 empty_cnt++;
1129 continue;
1130 }
1131
Guido van Rossum98f33732002-11-25 21:36:54 +00001132 /* Choose next candidate for MRO.
1133
1134 The input sequences alone can determine the choice.
1135 If not, choose the class which appears in the MRO
1136 of the earliest direct superclass of the new class.
1137 */
1138
Guido van Rossum1f121312002-11-14 19:49:16 +00001139 candidate = PyList_GET_ITEM(cur_list, remain[i]);
1140 for (j = 0; j < to_merge_size; j++) {
1141 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum98f33732002-11-25 21:36:54 +00001142 if (tail_contains(j_lst, remain[j], candidate)) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001143 goto skip; /* continue outer loop */
Guido van Rossum98f33732002-11-25 21:36:54 +00001144 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001145 }
1146 ok = PyList_Append(acc, candidate);
1147 if (ok < 0) {
1148 PyMem_Free(remain);
1149 return -1;
1150 }
1151 for (j = 0; j < to_merge_size; j++) {
1152 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum768158c2002-12-31 16:33:01 +00001153 if (remain[j] < PyList_GET_SIZE(j_lst) &&
1154 PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001155 remain[j]++;
1156 }
1157 }
1158 goto again;
Tim Peters9a6b8d82002-11-14 23:22:33 +00001159 skip: ;
Guido van Rossum1f121312002-11-14 19:49:16 +00001160 }
1161
Guido van Rossum98f33732002-11-25 21:36:54 +00001162 if (empty_cnt == to_merge_size) {
1163 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001164 return 0;
Guido van Rossum98f33732002-11-25 21:36:54 +00001165 }
1166 set_mro_error(to_merge, remain);
1167 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001168 return -1;
1169}
1170
Tim Peters6d6c1a32001-08-02 04:15:00 +00001171static PyObject *
1172mro_implementation(PyTypeObject *type)
1173{
1174 int i, n, ok;
1175 PyObject *bases, *result;
Guido van Rossum1f121312002-11-14 19:49:16 +00001176 PyObject *to_merge, *bases_aslist;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001177
Guido van Rossum63517572002-06-18 16:44:57 +00001178 if(type->tp_dict == NULL) {
1179 if(PyType_Ready(type) < 0)
1180 return NULL;
1181 }
1182
Guido van Rossum98f33732002-11-25 21:36:54 +00001183 /* Find a superclass linearization that honors the constraints
1184 of the explicit lists of bases and the constraints implied by
Tim Petersea7f75d2002-12-07 21:39:16 +00001185 each base class.
Guido van Rossum98f33732002-11-25 21:36:54 +00001186
1187 to_merge is a list of lists, where each list is a superclass
1188 linearization implied by a base class. The last element of
1189 to_merge is the declared list of bases.
1190 */
1191
Tim Peters6d6c1a32001-08-02 04:15:00 +00001192 bases = type->tp_bases;
1193 n = PyTuple_GET_SIZE(bases);
Guido van Rossum1f121312002-11-14 19:49:16 +00001194
1195 to_merge = PyList_New(n+1);
1196 if (to_merge == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001197 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001198
Tim Peters6d6c1a32001-08-02 04:15:00 +00001199 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001200 PyObject *base = PyTuple_GET_ITEM(bases, i);
1201 PyObject *parentMRO;
1202 if (PyType_Check(base))
1203 parentMRO = PySequence_List(
1204 ((PyTypeObject*)base)->tp_mro);
1205 else
1206 parentMRO = classic_mro(base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001207 if (parentMRO == NULL) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001208 Py_DECREF(to_merge);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001209 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001210 }
1211
1212 PyList_SET_ITEM(to_merge, i, parentMRO);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001213 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001214
1215 bases_aslist = PySequence_List(bases);
1216 if (bases_aslist == NULL) {
1217 Py_DECREF(to_merge);
1218 return NULL;
1219 }
Guido van Rossum98f33732002-11-25 21:36:54 +00001220 /* This is just a basic sanity check. */
1221 if (check_duplicates(bases_aslist) < 0) {
1222 Py_DECREF(to_merge);
1223 Py_DECREF(bases_aslist);
1224 return NULL;
1225 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001226 PyList_SET_ITEM(to_merge, n, bases_aslist);
1227
1228 result = Py_BuildValue("[O]", (PyObject *)type);
1229 if (result == NULL) {
1230 Py_DECREF(to_merge);
1231 return NULL;
1232 }
1233
1234 ok = pmerge(result, to_merge);
1235 Py_DECREF(to_merge);
1236 if (ok < 0) {
1237 Py_DECREF(result);
1238 return NULL;
1239 }
1240
Tim Peters6d6c1a32001-08-02 04:15:00 +00001241 return result;
1242}
1243
1244static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001245mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001246{
1247 PyTypeObject *type = (PyTypeObject *)self;
1248
Tim Peters6d6c1a32001-08-02 04:15:00 +00001249 return mro_implementation(type);
1250}
1251
1252static int
1253mro_internal(PyTypeObject *type)
1254{
1255 PyObject *mro, *result, *tuple;
1256
1257 if (type->ob_type == &PyType_Type) {
1258 result = mro_implementation(type);
1259 }
1260 else {
Guido van Rossum60718732001-08-28 17:47:51 +00001261 static PyObject *mro_str;
1262 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001263 if (mro == NULL)
1264 return -1;
1265 result = PyObject_CallObject(mro, NULL);
1266 Py_DECREF(mro);
1267 }
1268 if (result == NULL)
1269 return -1;
1270 tuple = PySequence_Tuple(result);
1271 Py_DECREF(result);
1272 type->tp_mro = tuple;
1273 return 0;
1274}
1275
1276
1277/* Calculate the best base amongst multiple base classes.
1278 This is the first one that's on the path to the "solid base". */
1279
1280static PyTypeObject *
1281best_base(PyObject *bases)
1282{
1283 int i, n;
1284 PyTypeObject *base, *winner, *candidate, *base_i;
Tim Petersa91e9642001-11-14 23:32:33 +00001285 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001286
1287 assert(PyTuple_Check(bases));
1288 n = PyTuple_GET_SIZE(bases);
1289 assert(n > 0);
Tim Petersa91e9642001-11-14 23:32:33 +00001290 base = NULL;
1291 winner = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001292 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001293 base_proto = PyTuple_GET_ITEM(bases, i);
1294 if (PyClass_Check(base_proto))
1295 continue;
1296 if (!PyType_Check(base_proto)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001297 PyErr_SetString(
1298 PyExc_TypeError,
1299 "bases must be types");
1300 return NULL;
1301 }
Tim Petersa91e9642001-11-14 23:32:33 +00001302 base_i = (PyTypeObject *)base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001303 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001304 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001305 return NULL;
1306 }
1307 candidate = solid_base(base_i);
Tim Petersa91e9642001-11-14 23:32:33 +00001308 if (winner == NULL) {
1309 winner = candidate;
1310 base = base_i;
1311 }
1312 else if (PyType_IsSubtype(winner, candidate))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001313 ;
1314 else if (PyType_IsSubtype(candidate, winner)) {
1315 winner = candidate;
1316 base = base_i;
1317 }
1318 else {
1319 PyErr_SetString(
1320 PyExc_TypeError,
1321 "multiple bases have "
1322 "instance lay-out conflict");
1323 return NULL;
1324 }
1325 }
Guido van Rossume54616c2001-12-14 04:19:56 +00001326 if (base == NULL)
1327 PyErr_SetString(PyExc_TypeError,
1328 "a new-style class can't have only classic bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001329 return base;
1330}
1331
1332static int
1333extra_ivars(PyTypeObject *type, PyTypeObject *base)
1334{
Neil Schemenauerc806c882001-08-29 23:54:54 +00001335 size_t t_size = type->tp_basicsize;
1336 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001337
Guido van Rossum9676b222001-08-17 20:32:36 +00001338 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001339 if (type->tp_itemsize || base->tp_itemsize) {
1340 /* If itemsize is involved, stricter rules */
1341 return t_size != b_size ||
1342 type->tp_itemsize != base->tp_itemsize;
1343 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001344 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
1345 type->tp_weaklistoffset + sizeof(PyObject *) == t_size)
1346 t_size -= sizeof(PyObject *);
1347 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
1348 type->tp_dictoffset + sizeof(PyObject *) == t_size)
1349 t_size -= sizeof(PyObject *);
1350
1351 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001352}
1353
1354static PyTypeObject *
1355solid_base(PyTypeObject *type)
1356{
1357 PyTypeObject *base;
1358
1359 if (type->tp_base)
1360 base = solid_base(type->tp_base);
1361 else
1362 base = &PyBaseObject_Type;
1363 if (extra_ivars(type, base))
1364 return type;
1365 else
1366 return base;
1367}
1368
Jeremy Hylton938ace62002-07-17 16:30:39 +00001369static void object_dealloc(PyObject *);
1370static int object_init(PyObject *, PyObject *, PyObject *);
1371static int update_slot(PyTypeObject *, PyObject *);
1372static void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001373
1374static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001375subtype_dict(PyObject *obj, void *context)
1376{
1377 PyObject **dictptr = _PyObject_GetDictPtr(obj);
1378 PyObject *dict;
1379
1380 if (dictptr == NULL) {
1381 PyErr_SetString(PyExc_AttributeError,
1382 "This object has no __dict__");
1383 return NULL;
1384 }
1385 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +00001386 if (dict == NULL)
1387 *dictptr = dict = PyDict_New();
1388 Py_XINCREF(dict);
1389 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001390}
1391
Guido van Rossum6661be32001-10-26 04:26:12 +00001392static int
1393subtype_setdict(PyObject *obj, PyObject *value, void *context)
1394{
1395 PyObject **dictptr = _PyObject_GetDictPtr(obj);
1396 PyObject *dict;
1397
1398 if (dictptr == NULL) {
1399 PyErr_SetString(PyExc_AttributeError,
1400 "This object has no __dict__");
1401 return -1;
1402 }
Guido van Rossumd331cb52001-12-05 19:46:42 +00001403 if (value != NULL && !PyDict_Check(value)) {
Guido van Rossum6661be32001-10-26 04:26:12 +00001404 PyErr_SetString(PyExc_TypeError,
1405 "__dict__ must be set to a dictionary");
1406 return -1;
1407 }
1408 dict = *dictptr;
Guido van Rossumd331cb52001-12-05 19:46:42 +00001409 Py_XINCREF(value);
Guido van Rossum6661be32001-10-26 04:26:12 +00001410 *dictptr = value;
1411 Py_XDECREF(dict);
1412 return 0;
1413}
1414
Guido van Rossumad47da02002-08-12 19:05:44 +00001415static PyObject *
1416subtype_getweakref(PyObject *obj, void *context)
1417{
1418 PyObject **weaklistptr;
1419 PyObject *result;
1420
1421 if (obj->ob_type->tp_weaklistoffset == 0) {
1422 PyErr_SetString(PyExc_AttributeError,
1423 "This object has no __weaklist__");
1424 return NULL;
1425 }
1426 assert(obj->ob_type->tp_weaklistoffset > 0);
1427 assert(obj->ob_type->tp_weaklistoffset + sizeof(PyObject *) <=
Guido van Rossum3747a0f2002-08-12 19:25:08 +00001428 (size_t)(obj->ob_type->tp_basicsize));
Guido van Rossumad47da02002-08-12 19:05:44 +00001429 weaklistptr = (PyObject **)
Guido van Rossum3747a0f2002-08-12 19:25:08 +00001430 ((char *)obj + obj->ob_type->tp_weaklistoffset);
Guido van Rossumad47da02002-08-12 19:05:44 +00001431 if (*weaklistptr == NULL)
1432 result = Py_None;
1433 else
1434 result = *weaklistptr;
1435 Py_INCREF(result);
1436 return result;
1437}
1438
Guido van Rossum373c7412003-01-07 13:41:37 +00001439/* Three variants on the subtype_getsets list. */
1440
1441static PyGetSetDef subtype_getsets_full[] = {
Guido van Rossumad47da02002-08-12 19:05:44 +00001442 {"__dict__", subtype_dict, subtype_setdict,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001443 PyDoc_STR("dictionary for instance variables (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001444 {"__weakref__", subtype_getweakref, NULL,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001445 PyDoc_STR("list of weak references to the object (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001446 {0}
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001447};
1448
Guido van Rossum373c7412003-01-07 13:41:37 +00001449static PyGetSetDef subtype_getsets_dict_only[] = {
1450 {"__dict__", subtype_dict, subtype_setdict,
1451 PyDoc_STR("dictionary for instance variables (if defined)")},
1452 {0}
1453};
1454
1455static PyGetSetDef subtype_getsets_weakref_only[] = {
1456 {"__weakref__", subtype_getweakref, NULL,
1457 PyDoc_STR("list of weak references to the object (if defined)")},
1458 {0}
1459};
1460
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001461static int
1462valid_identifier(PyObject *s)
1463{
Guido van Rossum03013a02002-07-16 14:30:28 +00001464 unsigned char *p;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001465 int i, n;
1466
1467 if (!PyString_Check(s)) {
1468 PyErr_SetString(PyExc_TypeError,
1469 "__slots__ must be strings");
1470 return 0;
1471 }
Guido van Rossum03013a02002-07-16 14:30:28 +00001472 p = (unsigned char *) PyString_AS_STRING(s);
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001473 n = PyString_GET_SIZE(s);
1474 /* We must reject an empty name. As a hack, we bump the
1475 length to 1 so that the loop will balk on the trailing \0. */
1476 if (n == 0)
1477 n = 1;
1478 for (i = 0; i < n; i++, p++) {
1479 if (!(i == 0 ? isalpha(*p) : isalnum(*p)) && *p != '_') {
1480 PyErr_SetString(PyExc_TypeError,
1481 "__slots__ must be identifiers");
1482 return 0;
1483 }
1484 }
1485 return 1;
1486}
1487
Martin v. Löwisd919a592002-10-14 21:07:28 +00001488#ifdef Py_USING_UNICODE
1489/* Replace Unicode objects in slots. */
1490
1491static PyObject *
1492_unicode_to_string(PyObject *slots, int nslots)
1493{
1494 PyObject *tmp = slots;
1495 PyObject *o, *o1;
1496 int i;
1497 intintargfunc copy = slots->ob_type->tp_as_sequence->sq_slice;
1498 for (i = 0; i < nslots; i++) {
1499 if (PyUnicode_Check(o = PyTuple_GET_ITEM(tmp, i))) {
1500 if (tmp == slots) {
1501 tmp = copy(slots, 0, PyTuple_GET_SIZE(slots));
1502 if (tmp == NULL)
1503 return NULL;
1504 }
1505 o1 = _PyUnicode_AsDefaultEncodedString
1506 (o, NULL);
1507 if (o1 == NULL) {
1508 Py_DECREF(tmp);
1509 return 0;
1510 }
1511 Py_INCREF(o1);
1512 Py_DECREF(o);
1513 PyTuple_SET_ITEM(tmp, i, o1);
1514 }
1515 }
1516 return tmp;
1517}
1518#endif
1519
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001520static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001521type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
1522{
1523 PyObject *name, *bases, *dict;
1524 static char *kwlist[] = {"name", "bases", "dict", 0};
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001525 PyObject *slots, *tmp, *newslots;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001526 PyTypeObject *type, *base, *tmptype, *winner;
Guido van Rossume5c691a2003-03-07 15:13:17 +00001527 PyHeapTypeObject *et;
Guido van Rossum6f799372001-09-20 20:46:19 +00001528 PyMemberDef *mp;
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001529 int i, nbases, nslots, slotoffset, add_dict, add_weak;
Guido van Rossumad47da02002-08-12 19:05:44 +00001530 int j, may_add_dict, may_add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001531
Tim Peters3abca122001-10-27 19:37:48 +00001532 assert(args != NULL && PyTuple_Check(args));
1533 assert(kwds == NULL || PyDict_Check(kwds));
1534
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001535 /* Special case: type(x) should return x->ob_type */
Tim Peters3abca122001-10-27 19:37:48 +00001536 {
1537 const int nargs = PyTuple_GET_SIZE(args);
1538 const int nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
1539
1540 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
1541 PyObject *x = PyTuple_GET_ITEM(args, 0);
1542 Py_INCREF(x->ob_type);
1543 return (PyObject *) x->ob_type;
1544 }
1545
1546 /* SF bug 475327 -- if that didn't trigger, we need 3
1547 arguments. but PyArg_ParseTupleAndKeywords below may give
1548 a msg saying type() needs exactly 3. */
1549 if (nargs + nkwds != 3) {
1550 PyErr_SetString(PyExc_TypeError,
1551 "type() takes 1 or 3 arguments");
1552 return NULL;
1553 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001554 }
1555
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001556 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001557 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
1558 &name,
1559 &PyTuple_Type, &bases,
1560 &PyDict_Type, &dict))
1561 return NULL;
1562
1563 /* Determine the proper metatype to deal with this,
1564 and check for metatype conflicts while we're at it.
1565 Note that if some other metatype wins to contract,
1566 it's possible that its instances are not types. */
1567 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001568 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001569 for (i = 0; i < nbases; i++) {
1570 tmp = PyTuple_GET_ITEM(bases, i);
1571 tmptype = tmp->ob_type;
Tim Petersa91e9642001-11-14 23:32:33 +00001572 if (tmptype == &PyClass_Type)
1573 continue; /* Special case classic classes */
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001574 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001575 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001576 if (PyType_IsSubtype(tmptype, winner)) {
1577 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001578 continue;
1579 }
1580 PyErr_SetString(PyExc_TypeError,
1581 "metatype conflict among bases");
1582 return NULL;
1583 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001584 if (winner != metatype) {
1585 if (winner->tp_new != type_new) /* Pass it to the winner */
1586 return winner->tp_new(winner, args, kwds);
1587 metatype = winner;
1588 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001589
1590 /* Adjust for empty tuple bases */
1591 if (nbases == 0) {
1592 bases = Py_BuildValue("(O)", &PyBaseObject_Type);
1593 if (bases == NULL)
1594 return NULL;
1595 nbases = 1;
1596 }
1597 else
1598 Py_INCREF(bases);
1599
1600 /* XXX From here until type is allocated, "return NULL" leaks bases! */
1601
1602 /* Calculate best base, and check that all bases are type objects */
1603 base = best_base(bases);
1604 if (base == NULL)
1605 return NULL;
1606 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
1607 PyErr_Format(PyExc_TypeError,
1608 "type '%.100s' is not an acceptable base type",
1609 base->tp_name);
1610 return NULL;
1611 }
1612
Tim Peters6d6c1a32001-08-02 04:15:00 +00001613 /* Check for a __slots__ sequence variable in dict, and count it */
1614 slots = PyDict_GetItemString(dict, "__slots__");
1615 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +00001616 add_dict = 0;
1617 add_weak = 0;
Guido van Rossumad47da02002-08-12 19:05:44 +00001618 may_add_dict = base->tp_dictoffset == 0;
1619 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
1620 if (slots == NULL) {
1621 if (may_add_dict) {
1622 add_dict++;
1623 }
1624 if (may_add_weak) {
1625 add_weak++;
1626 }
1627 }
1628 else {
1629 /* Have slots */
1630
Tim Peters6d6c1a32001-08-02 04:15:00 +00001631 /* Make it into a tuple */
1632 if (PyString_Check(slots))
1633 slots = Py_BuildValue("(O)", slots);
1634 else
1635 slots = PySequence_Tuple(slots);
1636 if (slots == NULL)
1637 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00001638 assert(PyTuple_Check(slots));
1639
1640 /* Are slots allowed? */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001641 nslots = PyTuple_GET_SIZE(slots);
Guido van Rossume5c691a2003-03-07 15:13:17 +00001642 if (nslots > 0 && base->tp_itemsize != 0 && !PyType_Check(base)) {
1643 /* for the special case of meta types, allow slots */
Guido van Rossumc4141872001-08-30 04:43:35 +00001644 PyErr_Format(PyExc_TypeError,
1645 "nonempty __slots__ "
1646 "not supported for subtype of '%s'",
1647 base->tp_name);
Guido van Rossumad47da02002-08-12 19:05:44 +00001648 bad_slots:
1649 Py_DECREF(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +00001650 return NULL;
1651 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001652
Martin v. Löwisd919a592002-10-14 21:07:28 +00001653#ifdef Py_USING_UNICODE
1654 tmp = _unicode_to_string(slots, nslots);
Martin v. Löwis13b1a5c2002-10-14 21:11:34 +00001655 if (tmp != slots) {
1656 Py_DECREF(slots);
1657 slots = tmp;
1658 }
Martin v. Löwisd919a592002-10-14 21:07:28 +00001659 if (!tmp)
1660 return NULL;
1661#endif
Guido van Rossumad47da02002-08-12 19:05:44 +00001662 /* Check for valid slot names and two special cases */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001663 for (i = 0; i < nslots; i++) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001664 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
1665 char *s;
1666 if (!valid_identifier(tmp))
1667 goto bad_slots;
1668 assert(PyString_Check(tmp));
1669 s = PyString_AS_STRING(tmp);
1670 if (strcmp(s, "__dict__") == 0) {
1671 if (!may_add_dict || add_dict) {
1672 PyErr_SetString(PyExc_TypeError,
1673 "__dict__ slot disallowed: "
1674 "we already got one");
1675 goto bad_slots;
1676 }
1677 add_dict++;
1678 }
1679 if (strcmp(s, "__weakref__") == 0) {
1680 if (!may_add_weak || add_weak) {
1681 PyErr_SetString(PyExc_TypeError,
1682 "__weakref__ slot disallowed: "
1683 "either we already got one, "
1684 "or __itemsize__ != 0");
1685 goto bad_slots;
1686 }
1687 add_weak++;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001688 }
1689 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001690
Guido van Rossumad47da02002-08-12 19:05:44 +00001691 /* Copy slots into yet another tuple, demangling names */
1692 newslots = PyTuple_New(nslots - add_dict - add_weak);
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001693 if (newslots == NULL)
Guido van Rossumad47da02002-08-12 19:05:44 +00001694 goto bad_slots;
1695 for (i = j = 0; i < nslots; i++) {
1696 char *s;
Guido van Rossum8e829202002-08-16 03:47:49 +00001697 char buffer[256];
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001698 tmp = PyTuple_GET_ITEM(slots, i);
Guido van Rossumad47da02002-08-12 19:05:44 +00001699 s = PyString_AS_STRING(tmp);
1700 if ((add_dict && strcmp(s, "__dict__") == 0) ||
1701 (add_weak && strcmp(s, "__weakref__") == 0))
1702 continue;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001703 if (_Py_Mangle(PyString_AS_STRING(name),
Guido van Rossumad47da02002-08-12 19:05:44 +00001704 PyString_AS_STRING(tmp),
1705 buffer, sizeof(buffer)))
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001706 {
1707 tmp = PyString_FromString(buffer);
1708 } else {
1709 Py_INCREF(tmp);
1710 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001711 PyTuple_SET_ITEM(newslots, j, tmp);
1712 j++;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001713 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001714 assert(j == nslots - add_dict - add_weak);
1715 nslots = j;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001716 Py_DECREF(slots);
1717 slots = newslots;
1718
Guido van Rossumad47da02002-08-12 19:05:44 +00001719 /* Secondary bases may provide weakrefs or dict */
1720 if (nbases > 1 &&
1721 ((may_add_dict && !add_dict) ||
1722 (may_add_weak && !add_weak))) {
1723 for (i = 0; i < nbases; i++) {
1724 tmp = PyTuple_GET_ITEM(bases, i);
1725 if (tmp == (PyObject *)base)
1726 continue; /* Skip primary base */
1727 if (PyClass_Check(tmp)) {
1728 /* Classic base class provides both */
1729 if (may_add_dict && !add_dict)
1730 add_dict++;
1731 if (may_add_weak && !add_weak)
1732 add_weak++;
1733 break;
1734 }
1735 assert(PyType_Check(tmp));
1736 tmptype = (PyTypeObject *)tmp;
1737 if (may_add_dict && !add_dict &&
1738 tmptype->tp_dictoffset != 0)
1739 add_dict++;
1740 if (may_add_weak && !add_weak &&
1741 tmptype->tp_weaklistoffset != 0)
1742 add_weak++;
1743 if (may_add_dict && !add_dict)
1744 continue;
1745 if (may_add_weak && !add_weak)
1746 continue;
1747 /* Nothing more to check */
1748 break;
1749 }
1750 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001751 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001752
1753 /* XXX From here until type is safely allocated,
1754 "return NULL" may leak slots! */
1755
1756 /* Allocate the type object */
1757 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
Guido van Rossumad47da02002-08-12 19:05:44 +00001758 if (type == NULL) {
1759 Py_XDECREF(slots);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001760 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00001761 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001762
1763 /* Keep name and slots alive in the extended type object */
Guido van Rossume5c691a2003-03-07 15:13:17 +00001764 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001765 Py_INCREF(name);
1766 et->name = name;
1767 et->slots = slots;
1768
Guido van Rossumdc91b992001-08-08 22:26:22 +00001769 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001770 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
1771 Py_TPFLAGS_BASETYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00001772 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
1773 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00001774
1775 /* It's a new-style number unless it specifically inherits any
1776 old-style numeric behavior */
1777 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
1778 (base->tp_as_number == NULL))
1779 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
1780
1781 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001782 type->tp_as_number = &et->as_number;
1783 type->tp_as_sequence = &et->as_sequence;
1784 type->tp_as_mapping = &et->as_mapping;
1785 type->tp_as_buffer = &et->as_buffer;
1786 type->tp_name = PyString_AS_STRING(name);
1787
1788 /* Set tp_base and tp_bases */
1789 type->tp_bases = bases;
1790 Py_INCREF(base);
1791 type->tp_base = base;
1792
Guido van Rossum687ae002001-10-15 22:03:32 +00001793 /* Initialize tp_dict from passed-in dict */
1794 type->tp_dict = dict = PyDict_Copy(dict);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001795 if (dict == NULL) {
1796 Py_DECREF(type);
1797 return NULL;
1798 }
1799
Guido van Rossumc3542212001-08-16 09:18:56 +00001800 /* Set __module__ in the dict */
1801 if (PyDict_GetItemString(dict, "__module__") == NULL) {
1802 tmp = PyEval_GetGlobals();
1803 if (tmp != NULL) {
1804 tmp = PyDict_GetItemString(tmp, "__name__");
1805 if (tmp != NULL) {
1806 if (PyDict_SetItemString(dict, "__module__",
1807 tmp) < 0)
1808 return NULL;
1809 }
1810 }
1811 }
1812
Tim Peters2f93e282001-10-04 05:27:00 +00001813 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
Tim Peters24008312002-03-17 18:56:20 +00001814 and is a string. The __doc__ accessor will first look for tp_doc;
1815 if that fails, it will still look into __dict__.
Tim Peters2f93e282001-10-04 05:27:00 +00001816 */
1817 {
1818 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
1819 if (doc != NULL && PyString_Check(doc)) {
1820 const size_t n = (size_t)PyString_GET_SIZE(doc);
Tim Peters59f809d2001-10-04 05:43:02 +00001821 type->tp_doc = (char *)PyObject_MALLOC(n+1);
Tim Peters2f93e282001-10-04 05:27:00 +00001822 if (type->tp_doc == NULL) {
1823 Py_DECREF(type);
1824 return NULL;
1825 }
1826 memcpy(type->tp_doc, PyString_AS_STRING(doc), n+1);
1827 }
1828 }
1829
Tim Peters6d6c1a32001-08-02 04:15:00 +00001830 /* Special-case __new__: if it's a plain function,
1831 make it a static function */
1832 tmp = PyDict_GetItemString(dict, "__new__");
1833 if (tmp != NULL && PyFunction_Check(tmp)) {
1834 tmp = PyStaticMethod_New(tmp);
1835 if (tmp == NULL) {
1836 Py_DECREF(type);
1837 return NULL;
1838 }
1839 PyDict_SetItemString(dict, "__new__", tmp);
1840 Py_DECREF(tmp);
1841 }
1842
1843 /* Add descriptors for custom slots from __slots__, or for __dict__ */
Guido van Rossume5c691a2003-03-07 15:13:17 +00001844 mp = PyHeapType_GET_MEMBERS(et);
Neil Schemenauerc806c882001-08-29 23:54:54 +00001845 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001846 if (slots != NULL) {
1847 for (i = 0; i < nslots; i++, mp++) {
1848 mp->name = PyString_AS_STRING(
1849 PyTuple_GET_ITEM(slots, i));
Guido van Rossum64b206c2001-12-04 17:13:22 +00001850 mp->type = T_OBJECT_EX;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001851 mp->offset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +00001852 if (base->tp_weaklistoffset == 0 &&
Guido van Rossum64b206c2001-12-04 17:13:22 +00001853 strcmp(mp->name, "__weakref__") == 0) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001854 add_weak++;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001855 mp->type = T_OBJECT;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001856 mp->flags = READONLY;
Guido van Rossum9676b222001-08-17 20:32:36 +00001857 type->tp_weaklistoffset = slotoffset;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001858 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001859 slotoffset += sizeof(PyObject *);
1860 }
1861 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001862 if (add_dict) {
1863 if (base->tp_itemsize)
1864 type->tp_dictoffset = -(long)sizeof(PyObject *);
1865 else
1866 type->tp_dictoffset = slotoffset;
1867 slotoffset += sizeof(PyObject *);
1868 }
1869 if (add_weak) {
1870 assert(!base->tp_itemsize);
1871 type->tp_weaklistoffset = slotoffset;
1872 slotoffset += sizeof(PyObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001873 }
1874 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001875 type->tp_itemsize = base->tp_itemsize;
Guido van Rossume5c691a2003-03-07 15:13:17 +00001876 type->tp_members = PyHeapType_GET_MEMBERS(et);
Guido van Rossum373c7412003-01-07 13:41:37 +00001877
1878 if (type->tp_weaklistoffset && type->tp_dictoffset)
1879 type->tp_getset = subtype_getsets_full;
1880 else if (type->tp_weaklistoffset && !type->tp_dictoffset)
1881 type->tp_getset = subtype_getsets_weakref_only;
1882 else if (!type->tp_weaklistoffset && type->tp_dictoffset)
1883 type->tp_getset = subtype_getsets_dict_only;
1884 else
1885 type->tp_getset = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001886
1887 /* Special case some slots */
1888 if (type->tp_dictoffset != 0 || nslots > 0) {
1889 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
1890 type->tp_getattro = PyObject_GenericGetAttr;
1891 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
1892 type->tp_setattro = PyObject_GenericSetAttr;
1893 }
1894 type->tp_dealloc = subtype_dealloc;
1895
Guido van Rossum9475a232001-10-05 20:51:39 +00001896 /* Enable GC unless there are really no instance variables possible */
1897 if (!(type->tp_basicsize == sizeof(PyObject) &&
1898 type->tp_itemsize == 0))
1899 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
1900
Tim Peters6d6c1a32001-08-02 04:15:00 +00001901 /* Always override allocation strategy to use regular heap */
1902 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00001903 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001904 type->tp_free = PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00001905 type->tp_traverse = subtype_traverse;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001906 type->tp_clear = subtype_clear;
Guido van Rossum048eb752001-10-02 21:24:57 +00001907 }
1908 else
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001909 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001910
1911 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001912 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001913 Py_DECREF(type);
1914 return NULL;
1915 }
1916
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001917 /* Put the proper slots in place */
1918 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00001919
Tim Peters6d6c1a32001-08-02 04:15:00 +00001920 return (PyObject *)type;
1921}
1922
1923/* Internal API to look for a name through the MRO.
1924 This returns a borrowed reference, and doesn't set an exception! */
1925PyObject *
1926_PyType_Lookup(PyTypeObject *type, PyObject *name)
1927{
1928 int i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00001929 PyObject *mro, *res, *base, *dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001930
Guido van Rossum687ae002001-10-15 22:03:32 +00001931 /* Look in tp_dict of types in MRO */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001932 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00001933
1934 /* If mro is NULL, the type is either not yet initialized
1935 by PyType_Ready(), or already cleared by type_clear().
1936 Either way the safest thing to do is to return NULL. */
1937 if (mro == NULL)
1938 return NULL;
1939
Tim Peters6d6c1a32001-08-02 04:15:00 +00001940 assert(PyTuple_Check(mro));
1941 n = PyTuple_GET_SIZE(mro);
1942 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001943 base = PyTuple_GET_ITEM(mro, i);
1944 if (PyClass_Check(base))
1945 dict = ((PyClassObject *)base)->cl_dict;
1946 else {
1947 assert(PyType_Check(base));
1948 dict = ((PyTypeObject *)base)->tp_dict;
1949 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001950 assert(dict && PyDict_Check(dict));
1951 res = PyDict_GetItem(dict, name);
1952 if (res != NULL)
1953 return res;
1954 }
1955 return NULL;
1956}
1957
1958/* This is similar to PyObject_GenericGetAttr(),
1959 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
1960static PyObject *
1961type_getattro(PyTypeObject *type, PyObject *name)
1962{
1963 PyTypeObject *metatype = type->ob_type;
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001964 PyObject *meta_attribute, *attribute;
1965 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001966
1967 /* Initialize this type (we'll assume the metatype is initialized) */
1968 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001969 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001970 return NULL;
1971 }
1972
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001973 /* No readable descriptor found yet */
1974 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00001975
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001976 /* Look for the attribute in the metatype */
1977 meta_attribute = _PyType_Lookup(metatype, name);
1978
1979 if (meta_attribute != NULL) {
1980 meta_get = meta_attribute->ob_type->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00001981
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001982 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
1983 /* Data descriptors implement tp_descr_set to intercept
1984 * writes. Assume the attribute is not overridden in
1985 * type's tp_dict (and bases): call the descriptor now.
1986 */
1987 return meta_get(meta_attribute, (PyObject *)type,
1988 (PyObject *)metatype);
1989 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001990 }
1991
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001992 /* No data descriptor found on metatype. Look in tp_dict of this
1993 * type and its bases */
1994 attribute = _PyType_Lookup(type, name);
1995 if (attribute != NULL) {
1996 /* Implement descriptor functionality, if any */
1997 descrgetfunc local_get = attribute->ob_type->tp_descr_get;
1998 if (local_get != NULL) {
1999 /* NULL 2nd argument indicates the descriptor was
2000 * found on the target object itself (or a base) */
2001 return local_get(attribute, (PyObject *)NULL,
2002 (PyObject *)type);
2003 }
Tim Peters34592512002-07-11 06:23:50 +00002004
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002005 Py_INCREF(attribute);
2006 return attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002007 }
2008
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002009 /* No attribute found in local __dict__ (or bases): use the
2010 * descriptor from the metatype, if any */
2011 if (meta_get != NULL)
2012 return meta_get(meta_attribute, (PyObject *)type,
2013 (PyObject *)metatype);
2014
2015 /* If an ordinary attribute was found on the metatype, return it now */
2016 if (meta_attribute != NULL) {
2017 Py_INCREF(meta_attribute);
2018 return meta_attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002019 }
2020
2021 /* Give up */
2022 PyErr_Format(PyExc_AttributeError,
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002023 "type object '%.50s' has no attribute '%.400s'",
2024 type->tp_name, PyString_AS_STRING(name));
Tim Peters6d6c1a32001-08-02 04:15:00 +00002025 return NULL;
2026}
2027
2028static int
2029type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
2030{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002031 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2032 PyErr_Format(
2033 PyExc_TypeError,
2034 "can't set attributes of built-in/extension type '%s'",
2035 type->tp_name);
2036 return -1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002037 }
Guido van Rossum8d24ee92003-03-24 23:49:49 +00002038 /* XXX Example of how I expect this to be used...
2039 if (update_subclasses(type, name, invalidate_cache, NULL) < 0)
2040 return -1;
2041 */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002042 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
2043 return -1;
2044 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002045}
2046
2047static void
2048type_dealloc(PyTypeObject *type)
2049{
Guido van Rossume5c691a2003-03-07 15:13:17 +00002050 PyHeapTypeObject *et;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002051
2052 /* Assert this is a heap-allocated type object */
2053 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002054 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00002055 PyObject_ClearWeakRefs((PyObject *)type);
Guido van Rossume5c691a2003-03-07 15:13:17 +00002056 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002057 Py_XDECREF(type->tp_base);
2058 Py_XDECREF(type->tp_dict);
2059 Py_XDECREF(type->tp_bases);
2060 Py_XDECREF(type->tp_mro);
Guido van Rossum687ae002001-10-15 22:03:32 +00002061 Py_XDECREF(type->tp_cache);
Guido van Rossum1c450732001-10-08 15:18:27 +00002062 Py_XDECREF(type->tp_subclasses);
Neal Norwitzcee5ca02002-07-30 00:42:06 +00002063 PyObject_Free(type->tp_doc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002064 Py_XDECREF(et->name);
2065 Py_XDECREF(et->slots);
2066 type->ob_type->tp_free((PyObject *)type);
2067}
2068
Guido van Rossum1c450732001-10-08 15:18:27 +00002069static PyObject *
2070type_subclasses(PyTypeObject *type, PyObject *args_ignored)
2071{
2072 PyObject *list, *raw, *ref;
2073 int i, n;
2074
2075 list = PyList_New(0);
2076 if (list == NULL)
2077 return NULL;
2078 raw = type->tp_subclasses;
2079 if (raw == NULL)
2080 return list;
2081 assert(PyList_Check(raw));
2082 n = PyList_GET_SIZE(raw);
2083 for (i = 0; i < n; i++) {
2084 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00002085 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00002086 ref = PyWeakref_GET_OBJECT(ref);
2087 if (ref != Py_None) {
2088 if (PyList_Append(list, ref) < 0) {
2089 Py_DECREF(list);
2090 return NULL;
2091 }
2092 }
2093 }
2094 return list;
2095}
2096
Tim Peters6d6c1a32001-08-02 04:15:00 +00002097static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002098 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002099 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
Guido van Rossum1c450732001-10-08 15:18:27 +00002100 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002101 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002102 {0}
2103};
2104
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002105PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002106"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002107"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002108
Guido van Rossum048eb752001-10-02 21:24:57 +00002109static int
2110type_traverse(PyTypeObject *type, visitproc visit, void *arg)
2111{
Guido van Rossum048eb752001-10-02 21:24:57 +00002112 int err;
2113
Guido van Rossuma3862092002-06-10 15:24:42 +00002114 /* Because of type_is_gc(), the collector only calls this
2115 for heaptypes. */
2116 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002117
2118#define VISIT(SLOT) \
2119 if (SLOT) { \
2120 err = visit((PyObject *)(SLOT), arg); \
2121 if (err) \
2122 return err; \
2123 }
2124
2125 VISIT(type->tp_dict);
Guido van Rossum687ae002001-10-15 22:03:32 +00002126 VISIT(type->tp_cache);
Guido van Rossum048eb752001-10-02 21:24:57 +00002127 VISIT(type->tp_mro);
2128 VISIT(type->tp_bases);
2129 VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00002130
2131 /* There's no need to visit type->tp_subclasses or
Guido van Rossume5c691a2003-03-07 15:13:17 +00002132 ((PyHeapTypeObject *)type)->slots, because they can't be involved
Guido van Rossuma3862092002-06-10 15:24:42 +00002133 in cycles; tp_subclasses is a list of weak references,
2134 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00002135
2136#undef VISIT
2137
2138 return 0;
2139}
2140
2141static int
2142type_clear(PyTypeObject *type)
2143{
Guido van Rossum048eb752001-10-02 21:24:57 +00002144 PyObject *tmp;
2145
Guido van Rossuma3862092002-06-10 15:24:42 +00002146 /* Because of type_is_gc(), the collector only calls this
2147 for heaptypes. */
2148 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002149
2150#define CLEAR(SLOT) \
2151 if (SLOT) { \
2152 tmp = (PyObject *)(SLOT); \
2153 SLOT = NULL; \
2154 Py_DECREF(tmp); \
2155 }
2156
Guido van Rossuma3862092002-06-10 15:24:42 +00002157 /* The only field we need to clear is tp_mro, which is part of a
2158 hard cycle (its first element is the class itself) that won't
2159 be broken otherwise (it's a tuple and tuples don't have a
2160 tp_clear handler). None of the other fields need to be
2161 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00002162
Guido van Rossuma3862092002-06-10 15:24:42 +00002163 tp_dict:
2164 It is a dict, so the collector will call its tp_clear.
2165
2166 tp_cache:
2167 Not used; if it were, it would be a dict.
2168
2169 tp_bases, tp_base:
2170 If these are involved in a cycle, there must be at least
2171 one other, mutable object in the cycle, e.g. a base
2172 class's dict; the cycle will be broken that way.
2173
2174 tp_subclasses:
2175 A list of weak references can't be part of a cycle; and
2176 lists have their own tp_clear.
2177
Guido van Rossume5c691a2003-03-07 15:13:17 +00002178 slots (in PyHeapTypeObject):
Guido van Rossuma3862092002-06-10 15:24:42 +00002179 A tuple of strings can't be part of a cycle.
2180 */
2181
2182 CLEAR(type->tp_mro);
Tim Peters2f93e282001-10-04 05:27:00 +00002183
Guido van Rossum048eb752001-10-02 21:24:57 +00002184#undef CLEAR
2185
2186 return 0;
2187}
2188
2189static int
2190type_is_gc(PyTypeObject *type)
2191{
2192 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
2193}
2194
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002195PyTypeObject PyType_Type = {
2196 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002197 0, /* ob_size */
2198 "type", /* tp_name */
Guido van Rossume5c691a2003-03-07 15:13:17 +00002199 sizeof(PyHeapTypeObject), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00002200 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002201 (destructor)type_dealloc, /* tp_dealloc */
2202 0, /* tp_print */
2203 0, /* tp_getattr */
2204 0, /* tp_setattr */
2205 type_compare, /* tp_compare */
2206 (reprfunc)type_repr, /* tp_repr */
2207 0, /* tp_as_number */
2208 0, /* tp_as_sequence */
2209 0, /* tp_as_mapping */
2210 (hashfunc)_Py_HashPointer, /* tp_hash */
2211 (ternaryfunc)type_call, /* tp_call */
2212 0, /* tp_str */
2213 (getattrofunc)type_getattro, /* tp_getattro */
2214 (setattrofunc)type_setattro, /* tp_setattro */
2215 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00002216 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2217 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002218 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00002219 (traverseproc)type_traverse, /* tp_traverse */
2220 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002221 0, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00002222 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002223 0, /* tp_iter */
2224 0, /* tp_iternext */
2225 type_methods, /* tp_methods */
2226 type_members, /* tp_members */
2227 type_getsets, /* tp_getset */
2228 0, /* tp_base */
2229 0, /* tp_dict */
2230 0, /* tp_descr_get */
2231 0, /* tp_descr_set */
2232 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
2233 0, /* tp_init */
2234 0, /* tp_alloc */
2235 type_new, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002236 PyObject_GC_Del, /* tp_free */
Guido van Rossum048eb752001-10-02 21:24:57 +00002237 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002238};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002239
2240
2241/* The base type of all types (eventually)... except itself. */
2242
2243static int
2244object_init(PyObject *self, PyObject *args, PyObject *kwds)
2245{
2246 return 0;
2247}
2248
Guido van Rossum298e4212003-02-13 16:30:16 +00002249/* If we don't have a tp_new for a new-style class, new will use this one.
2250 Therefore this should take no arguments/keywords. However, this new may
2251 also be inherited by objects that define a tp_init but no tp_new. These
2252 objects WILL pass argumets to tp_new, because it gets the same args as
2253 tp_init. So only allow arguments if we aren't using the default init, in
2254 which case we expect init to handle argument parsing. */
2255static PyObject *
2256object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2257{
2258 if (type->tp_init == object_init && (PyTuple_GET_SIZE(args) ||
2259 (kwds && PyDict_Check(kwds) && PyDict_Size(kwds)))) {
2260 PyErr_SetString(PyExc_TypeError,
2261 "default __new__ takes no parameters");
2262 return NULL;
2263 }
2264 return type->tp_alloc(type, 0);
2265}
2266
Tim Peters6d6c1a32001-08-02 04:15:00 +00002267static void
2268object_dealloc(PyObject *self)
2269{
2270 self->ob_type->tp_free(self);
2271}
2272
Guido van Rossum8e248182001-08-12 05:17:56 +00002273static PyObject *
2274object_repr(PyObject *self)
2275{
Guido van Rossum76e69632001-08-16 18:52:43 +00002276 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00002277 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002278
Guido van Rossum76e69632001-08-16 18:52:43 +00002279 type = self->ob_type;
2280 mod = type_module(type, NULL);
2281 if (mod == NULL)
2282 PyErr_Clear();
2283 else if (!PyString_Check(mod)) {
2284 Py_DECREF(mod);
2285 mod = NULL;
2286 }
2287 name = type_name(type, NULL);
2288 if (name == NULL)
2289 return NULL;
2290 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002291 rtn = PyString_FromFormat("<%s.%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002292 PyString_AS_STRING(mod),
2293 PyString_AS_STRING(name),
2294 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002295 else
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002296 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002297 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002298 Py_XDECREF(mod);
2299 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00002300 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002301}
2302
Guido van Rossumb8f63662001-08-15 23:57:02 +00002303static PyObject *
2304object_str(PyObject *self)
2305{
2306 unaryfunc f;
2307
2308 f = self->ob_type->tp_repr;
2309 if (f == NULL)
2310 f = object_repr;
2311 return f(self);
2312}
2313
Guido van Rossum8e248182001-08-12 05:17:56 +00002314static long
2315object_hash(PyObject *self)
2316{
2317 return _Py_HashPointer(self);
2318}
Guido van Rossum8e248182001-08-12 05:17:56 +00002319
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002320static PyObject *
2321object_get_class(PyObject *self, void *closure)
2322{
2323 Py_INCREF(self->ob_type);
2324 return (PyObject *)(self->ob_type);
2325}
2326
2327static int
2328equiv_structs(PyTypeObject *a, PyTypeObject *b)
2329{
2330 return a == b ||
2331 (a != NULL &&
2332 b != NULL &&
2333 a->tp_basicsize == b->tp_basicsize &&
2334 a->tp_itemsize == b->tp_itemsize &&
2335 a->tp_dictoffset == b->tp_dictoffset &&
2336 a->tp_weaklistoffset == b->tp_weaklistoffset &&
2337 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
2338 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
2339}
2340
2341static int
2342same_slots_added(PyTypeObject *a, PyTypeObject *b)
2343{
2344 PyTypeObject *base = a->tp_base;
2345 int size;
2346
2347 if (base != b->tp_base)
2348 return 0;
2349 if (equiv_structs(a, base) && equiv_structs(b, base))
2350 return 1;
2351 size = base->tp_basicsize;
2352 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
2353 size += sizeof(PyObject *);
2354 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
2355 size += sizeof(PyObject *);
2356 return size == a->tp_basicsize && size == b->tp_basicsize;
2357}
2358
2359static int
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002360compatible_for_assignment(PyTypeObject* old, PyTypeObject* new, char* attr)
2361{
2362 PyTypeObject *newbase, *oldbase;
2363
2364 if (new->tp_dealloc != old->tp_dealloc ||
2365 new->tp_free != old->tp_free)
2366 {
2367 PyErr_Format(PyExc_TypeError,
2368 "%s assignment: "
2369 "'%s' deallocator differs from '%s'",
2370 attr,
2371 new->tp_name,
2372 old->tp_name);
2373 return 0;
2374 }
2375 newbase = new;
2376 oldbase = old;
2377 while (equiv_structs(newbase, newbase->tp_base))
2378 newbase = newbase->tp_base;
2379 while (equiv_structs(oldbase, oldbase->tp_base))
2380 oldbase = oldbase->tp_base;
2381 if (newbase != oldbase &&
2382 (newbase->tp_base != oldbase->tp_base ||
2383 !same_slots_added(newbase, oldbase))) {
2384 PyErr_Format(PyExc_TypeError,
2385 "%s assignment: "
2386 "'%s' object layout differs from '%s'",
2387 attr,
2388 new->tp_name,
2389 old->tp_name);
2390 return 0;
2391 }
Tim Petersea7f75d2002-12-07 21:39:16 +00002392
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002393 return 1;
2394}
2395
2396static int
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002397object_set_class(PyObject *self, PyObject *value, void *closure)
2398{
2399 PyTypeObject *old = self->ob_type;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002400 PyTypeObject *new;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002401
Guido van Rossumb6b89422002-04-15 01:03:30 +00002402 if (value == NULL) {
2403 PyErr_SetString(PyExc_TypeError,
2404 "can't delete __class__ attribute");
2405 return -1;
2406 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002407 if (!PyType_Check(value)) {
2408 PyErr_Format(PyExc_TypeError,
2409 "__class__ must be set to new-style class, not '%s' object",
2410 value->ob_type->tp_name);
2411 return -1;
2412 }
2413 new = (PyTypeObject *)value;
Guido van Rossum40af8892002-08-10 05:42:07 +00002414 if (!(new->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
2415 !(old->tp_flags & Py_TPFLAGS_HEAPTYPE))
2416 {
2417 PyErr_Format(PyExc_TypeError,
2418 "__class__ assignment: only for heap types");
2419 return -1;
2420 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002421 if (compatible_for_assignment(new, old, "__class__")) {
2422 Py_INCREF(new);
2423 self->ob_type = new;
2424 Py_DECREF(old);
2425 return 0;
2426 }
2427 else {
Guido van Rossum9ee4b942002-05-24 18:47:47 +00002428 return -1;
2429 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002430}
2431
2432static PyGetSetDef object_getsets[] = {
2433 {"__class__", object_get_class, object_set_class,
Neal Norwitz858e34f2002-08-13 17:18:45 +00002434 PyDoc_STR("the object's class")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002435 {0}
2436};
2437
Guido van Rossumc53f0092003-02-18 22:05:12 +00002438
Guido van Rossum036f9992003-02-21 22:02:54 +00002439/* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
2440 We fall back to helpers in copy_reg for:
2441 - pickle protocols < 2
2442 - calculating the list of slot names (done only once per class)
2443 - the __newobj__ function (which is used as a token but never called)
2444*/
2445
2446static PyObject *
2447import_copy_reg(void)
2448{
2449 static PyObject *copy_reg_str;
Guido van Rossum3926a632001-09-25 16:25:58 +00002450
2451 if (!copy_reg_str) {
2452 copy_reg_str = PyString_InternFromString("copy_reg");
2453 if (copy_reg_str == NULL)
2454 return NULL;
2455 }
Guido van Rossum036f9992003-02-21 22:02:54 +00002456
2457 return PyImport_Import(copy_reg_str);
2458}
2459
2460static PyObject *
2461slotnames(PyObject *cls)
2462{
2463 PyObject *clsdict;
2464 PyObject *copy_reg;
2465 PyObject *slotnames;
2466
2467 if (!PyType_Check(cls)) {
2468 Py_INCREF(Py_None);
2469 return Py_None;
2470 }
2471
2472 clsdict = ((PyTypeObject *)cls)->tp_dict;
2473 slotnames = PyDict_GetItemString(clsdict, "__slotnames__");
2474 if (slotnames != NULL) {
2475 Py_INCREF(slotnames);
2476 return slotnames;
2477 }
2478
2479 copy_reg = import_copy_reg();
2480 if (copy_reg == NULL)
2481 return NULL;
2482
2483 slotnames = PyObject_CallMethod(copy_reg, "_slotnames", "O", cls);
2484 Py_DECREF(copy_reg);
2485 if (slotnames != NULL &&
2486 slotnames != Py_None &&
2487 !PyList_Check(slotnames))
2488 {
2489 PyErr_SetString(PyExc_TypeError,
2490 "copy_reg._slotnames didn't return a list or None");
2491 Py_DECREF(slotnames);
2492 slotnames = NULL;
2493 }
2494
2495 return slotnames;
2496}
2497
2498static PyObject *
2499reduce_2(PyObject *obj)
2500{
2501 PyObject *cls, *getnewargs;
2502 PyObject *args = NULL, *args2 = NULL;
2503 PyObject *getstate = NULL, *state = NULL, *names = NULL;
2504 PyObject *slots = NULL, *listitems = NULL, *dictitems = NULL;
2505 PyObject *copy_reg = NULL, *newobj = NULL, *res = NULL;
2506 int i, n;
2507
2508 cls = PyObject_GetAttrString(obj, "__class__");
2509 if (cls == NULL)
2510 return NULL;
2511
2512 getnewargs = PyObject_GetAttrString(obj, "__getnewargs__");
2513 if (getnewargs != NULL) {
2514 args = PyObject_CallObject(getnewargs, NULL);
2515 Py_DECREF(getnewargs);
2516 if (args != NULL && !PyTuple_Check(args)) {
2517 PyErr_SetString(PyExc_TypeError,
2518 "__getnewargs__ should return a tuple");
2519 goto end;
2520 }
2521 }
2522 else {
2523 PyErr_Clear();
2524 args = PyTuple_New(0);
2525 }
2526 if (args == NULL)
2527 goto end;
2528
2529 getstate = PyObject_GetAttrString(obj, "__getstate__");
2530 if (getstate != NULL) {
2531 state = PyObject_CallObject(getstate, NULL);
2532 Py_DECREF(getstate);
2533 }
2534 else {
2535 state = PyObject_GetAttrString(obj, "__dict__");
2536 if (state == NULL) {
2537 PyErr_Clear();
2538 state = Py_None;
2539 Py_INCREF(state);
2540 }
2541 names = slotnames(cls);
2542 if (names == NULL)
2543 goto end;
2544 if (names != Py_None) {
2545 assert(PyList_Check(names));
2546 slots = PyDict_New();
2547 if (slots == NULL)
2548 goto end;
2549 n = 0;
2550 /* Can't pre-compute the list size; the list
2551 is stored on the class so accessible to other
2552 threads, which may be run by DECREF */
2553 for (i = 0; i < PyList_GET_SIZE(names); i++) {
2554 PyObject *name, *value;
2555 name = PyList_GET_ITEM(names, i);
2556 value = PyObject_GetAttr(obj, name);
2557 if (value == NULL)
2558 PyErr_Clear();
2559 else {
2560 int err = PyDict_SetItem(slots, name,
2561 value);
2562 Py_DECREF(value);
2563 if (err)
2564 goto end;
2565 n++;
2566 }
2567 }
2568 if (n) {
2569 state = Py_BuildValue("(NO)", state, slots);
2570 if (state == NULL)
2571 goto end;
2572 }
2573 }
2574 }
2575
2576 if (!PyList_Check(obj)) {
2577 listitems = Py_None;
2578 Py_INCREF(listitems);
2579 }
2580 else {
2581 listitems = PyObject_GetIter(obj);
2582 if (listitems == NULL)
2583 goto end;
2584 }
2585
2586 if (!PyDict_Check(obj)) {
2587 dictitems = Py_None;
2588 Py_INCREF(dictitems);
2589 }
2590 else {
2591 dictitems = PyObject_CallMethod(obj, "iteritems", "");
2592 if (dictitems == NULL)
2593 goto end;
2594 }
2595
2596 copy_reg = import_copy_reg();
2597 if (copy_reg == NULL)
2598 goto end;
2599 newobj = PyObject_GetAttrString(copy_reg, "__newobj__");
2600 if (newobj == NULL)
2601 goto end;
2602
2603 n = PyTuple_GET_SIZE(args);
2604 args2 = PyTuple_New(n+1);
2605 if (args2 == NULL)
2606 goto end;
2607 PyTuple_SET_ITEM(args2, 0, cls);
2608 cls = NULL;
2609 for (i = 0; i < n; i++) {
2610 PyObject *v = PyTuple_GET_ITEM(args, i);
2611 Py_INCREF(v);
2612 PyTuple_SET_ITEM(args2, i+1, v);
2613 }
2614
2615 res = Py_BuildValue("(OOOOO)",
2616 newobj, args2, state, listitems, dictitems);
2617
2618 end:
2619 Py_XDECREF(cls);
2620 Py_XDECREF(args);
2621 Py_XDECREF(args2);
Jeremy Hyltond06483c2003-04-09 21:01:42 +00002622 Py_XDECREF(slots);
Guido van Rossum036f9992003-02-21 22:02:54 +00002623 Py_XDECREF(state);
2624 Py_XDECREF(names);
2625 Py_XDECREF(listitems);
2626 Py_XDECREF(dictitems);
2627 Py_XDECREF(copy_reg);
2628 Py_XDECREF(newobj);
2629 return res;
2630}
2631
2632static PyObject *
2633object_reduce_ex(PyObject *self, PyObject *args)
2634{
2635 /* Call copy_reg._reduce_ex(self, proto) */
2636 PyObject *reduce, *copy_reg, *res;
2637 int proto = 0;
2638
2639 if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
2640 return NULL;
2641
2642 reduce = PyObject_GetAttrString(self, "__reduce__");
2643 if (reduce == NULL)
2644 PyErr_Clear();
2645 else {
2646 PyObject *cls, *clsreduce, *objreduce;
2647 int override;
2648 cls = PyObject_GetAttrString(self, "__class__");
2649 if (cls == NULL) {
2650 Py_DECREF(reduce);
2651 return NULL;
2652 }
2653 clsreduce = PyObject_GetAttrString(cls, "__reduce__");
2654 Py_DECREF(cls);
2655 if (clsreduce == NULL) {
2656 Py_DECREF(reduce);
2657 return NULL;
2658 }
2659 objreduce = PyDict_GetItemString(PyBaseObject_Type.tp_dict,
2660 "__reduce__");
2661 override = (clsreduce != objreduce);
2662 Py_DECREF(clsreduce);
2663 if (override) {
2664 res = PyObject_CallObject(reduce, NULL);
2665 Py_DECREF(reduce);
2666 return res;
2667 }
2668 else
2669 Py_DECREF(reduce);
2670 }
2671
2672 if (proto >= 2)
2673 return reduce_2(self);
2674
2675 copy_reg = import_copy_reg();
Guido van Rossum3926a632001-09-25 16:25:58 +00002676 if (!copy_reg)
2677 return NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00002678
Guido van Rossumc53f0092003-02-18 22:05:12 +00002679 res = PyEval_CallMethod(copy_reg, "_reduce_ex", "(Oi)", self, proto);
Guido van Rossum3926a632001-09-25 16:25:58 +00002680 Py_DECREF(copy_reg);
Guido van Rossum036f9992003-02-21 22:02:54 +00002681
Guido van Rossum3926a632001-09-25 16:25:58 +00002682 return res;
2683}
2684
2685static PyMethodDef object_methods[] = {
Guido van Rossumc53f0092003-02-18 22:05:12 +00002686 {"__reduce_ex__", object_reduce_ex, METH_VARARGS,
2687 PyDoc_STR("helper for pickle")},
2688 {"__reduce__", object_reduce_ex, METH_VARARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002689 PyDoc_STR("helper for pickle")},
Guido van Rossum3926a632001-09-25 16:25:58 +00002690 {0}
2691};
2692
Guido van Rossum036f9992003-02-21 22:02:54 +00002693
Tim Peters6d6c1a32001-08-02 04:15:00 +00002694PyTypeObject PyBaseObject_Type = {
2695 PyObject_HEAD_INIT(&PyType_Type)
2696 0, /* ob_size */
2697 "object", /* tp_name */
2698 sizeof(PyObject), /* tp_basicsize */
2699 0, /* tp_itemsize */
2700 (destructor)object_dealloc, /* tp_dealloc */
2701 0, /* tp_print */
2702 0, /* tp_getattr */
2703 0, /* tp_setattr */
2704 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002705 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002706 0, /* tp_as_number */
2707 0, /* tp_as_sequence */
2708 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002709 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002710 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002711 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002712 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002713 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002714 0, /* tp_as_buffer */
2715 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002716 PyDoc_STR("The most base type"), /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002717 0, /* tp_traverse */
2718 0, /* tp_clear */
2719 0, /* tp_richcompare */
2720 0, /* tp_weaklistoffset */
2721 0, /* tp_iter */
2722 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00002723 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002724 0, /* tp_members */
2725 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002726 0, /* tp_base */
2727 0, /* tp_dict */
2728 0, /* tp_descr_get */
2729 0, /* tp_descr_set */
2730 0, /* tp_dictoffset */
2731 object_init, /* tp_init */
2732 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossum298e4212003-02-13 16:30:16 +00002733 object_new, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002734 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002735};
2736
2737
2738/* Initialize the __dict__ in a type object */
2739
2740static int
2741add_methods(PyTypeObject *type, PyMethodDef *meth)
2742{
Guido van Rossum687ae002001-10-15 22:03:32 +00002743 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002744
2745 for (; meth->ml_name != NULL; meth++) {
2746 PyObject *descr;
2747 if (PyDict_GetItemString(dict, meth->ml_name))
2748 continue;
Fred Drake7bf97152002-03-28 05:33:33 +00002749 if (meth->ml_flags & METH_CLASS) {
2750 if (meth->ml_flags & METH_STATIC) {
2751 PyErr_SetString(PyExc_ValueError,
2752 "method cannot be both class and static");
2753 return -1;
2754 }
Tim Petersbca1cbc2002-12-09 22:56:13 +00002755 descr = PyDescr_NewClassMethod(type, meth);
Fred Drake7bf97152002-03-28 05:33:33 +00002756 }
2757 else if (meth->ml_flags & METH_STATIC) {
Guido van Rossum9af48ff2003-02-11 17:12:46 +00002758 PyObject *cfunc = PyCFunction_New(meth, NULL);
2759 if (cfunc == NULL)
2760 return -1;
2761 descr = PyStaticMethod_New(cfunc);
2762 Py_DECREF(cfunc);
Fred Drake7bf97152002-03-28 05:33:33 +00002763 }
2764 else {
2765 descr = PyDescr_NewMethod(type, meth);
2766 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002767 if (descr == NULL)
2768 return -1;
Fred Drake7bf97152002-03-28 05:33:33 +00002769 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002770 return -1;
2771 Py_DECREF(descr);
2772 }
2773 return 0;
2774}
2775
2776static int
Guido van Rossum6f799372001-09-20 20:46:19 +00002777add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002778{
Guido van Rossum687ae002001-10-15 22:03:32 +00002779 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002780
2781 for (; memb->name != NULL; memb++) {
2782 PyObject *descr;
2783 if (PyDict_GetItemString(dict, memb->name))
2784 continue;
2785 descr = PyDescr_NewMember(type, memb);
2786 if (descr == NULL)
2787 return -1;
2788 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
2789 return -1;
2790 Py_DECREF(descr);
2791 }
2792 return 0;
2793}
2794
2795static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00002796add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002797{
Guido van Rossum687ae002001-10-15 22:03:32 +00002798 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002799
2800 for (; gsp->name != NULL; gsp++) {
2801 PyObject *descr;
2802 if (PyDict_GetItemString(dict, gsp->name))
2803 continue;
2804 descr = PyDescr_NewGetSet(type, gsp);
2805
2806 if (descr == NULL)
2807 return -1;
2808 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
2809 return -1;
2810 Py_DECREF(descr);
2811 }
2812 return 0;
2813}
2814
Guido van Rossum13d52f02001-08-10 21:24:08 +00002815static void
2816inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002817{
2818 int oldsize, newsize;
2819
Guido van Rossum13d52f02001-08-10 21:24:08 +00002820 /* Special flag magic */
2821 if (!type->tp_as_buffer && base->tp_as_buffer) {
2822 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
2823 type->tp_flags |=
2824 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
2825 }
2826 if (!type->tp_as_sequence && base->tp_as_sequence) {
2827 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
2828 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
2829 }
2830 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
2831 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
2832 if ((!type->tp_as_number && base->tp_as_number) ||
2833 (!type->tp_as_sequence && base->tp_as_sequence)) {
2834 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
2835 if (!type->tp_as_number && !type->tp_as_sequence) {
2836 type->tp_flags |= base->tp_flags &
2837 Py_TPFLAGS_HAVE_INPLACEOPS;
2838 }
2839 }
2840 /* Wow */
2841 }
2842 if (!type->tp_as_number && base->tp_as_number) {
2843 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
2844 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
2845 }
2846
2847 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00002848 oldsize = base->tp_basicsize;
2849 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
2850 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
2851 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00002852 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
2853 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00002854 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00002855 if (type->tp_traverse == NULL)
2856 type->tp_traverse = base->tp_traverse;
2857 if (type->tp_clear == NULL)
2858 type->tp_clear = base->tp_clear;
2859 }
2860 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
Guido van Rossumf884b742001-12-17 17:14:22 +00002861 /* The condition below could use some explanation.
2862 It appears that tp_new is not inherited for static types
2863 whose base class is 'object'; this seems to be a precaution
2864 so that old extension types don't suddenly become
2865 callable (object.__new__ wouldn't insure the invariants
2866 that the extension type's own factory function ensures).
2867 Heap types, of course, are under our control, so they do
2868 inherit tp_new; static extension types that specify some
2869 other built-in type as the default are considered
2870 new-style-aware so they also inherit object.__new__. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002871 if (base != &PyBaseObject_Type ||
2872 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2873 if (type->tp_new == NULL)
2874 type->tp_new = base->tp_new;
2875 }
2876 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00002877 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00002878
2879 /* Copy other non-function slots */
2880
2881#undef COPYVAL
2882#define COPYVAL(SLOT) \
2883 if (type->SLOT == 0) type->SLOT = base->SLOT
2884
2885 COPYVAL(tp_itemsize);
2886 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
2887 COPYVAL(tp_weaklistoffset);
2888 }
2889 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2890 COPYVAL(tp_dictoffset);
2891 }
Guido van Rossum13d52f02001-08-10 21:24:08 +00002892}
2893
2894static void
2895inherit_slots(PyTypeObject *type, PyTypeObject *base)
2896{
2897 PyTypeObject *basebase;
2898
2899#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00002900#undef COPYSLOT
2901#undef COPYNUM
2902#undef COPYSEQ
2903#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00002904#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00002905
2906#define SLOTDEFINED(SLOT) \
2907 (base->SLOT != 0 && \
2908 (basebase == NULL || base->SLOT != basebase->SLOT))
2909
Tim Peters6d6c1a32001-08-02 04:15:00 +00002910#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00002911 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00002912
2913#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
2914#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
2915#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00002916#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002917
Guido van Rossum13d52f02001-08-10 21:24:08 +00002918 /* This won't inherit indirect slots (from tp_as_number etc.)
2919 if type doesn't provide the space. */
2920
2921 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
2922 basebase = base->tp_base;
2923 if (basebase->tp_as_number == NULL)
2924 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002925 COPYNUM(nb_add);
2926 COPYNUM(nb_subtract);
2927 COPYNUM(nb_multiply);
2928 COPYNUM(nb_divide);
2929 COPYNUM(nb_remainder);
2930 COPYNUM(nb_divmod);
2931 COPYNUM(nb_power);
2932 COPYNUM(nb_negative);
2933 COPYNUM(nb_positive);
2934 COPYNUM(nb_absolute);
2935 COPYNUM(nb_nonzero);
2936 COPYNUM(nb_invert);
2937 COPYNUM(nb_lshift);
2938 COPYNUM(nb_rshift);
2939 COPYNUM(nb_and);
2940 COPYNUM(nb_xor);
2941 COPYNUM(nb_or);
2942 COPYNUM(nb_coerce);
2943 COPYNUM(nb_int);
2944 COPYNUM(nb_long);
2945 COPYNUM(nb_float);
2946 COPYNUM(nb_oct);
2947 COPYNUM(nb_hex);
2948 COPYNUM(nb_inplace_add);
2949 COPYNUM(nb_inplace_subtract);
2950 COPYNUM(nb_inplace_multiply);
2951 COPYNUM(nb_inplace_divide);
2952 COPYNUM(nb_inplace_remainder);
2953 COPYNUM(nb_inplace_power);
2954 COPYNUM(nb_inplace_lshift);
2955 COPYNUM(nb_inplace_rshift);
2956 COPYNUM(nb_inplace_and);
2957 COPYNUM(nb_inplace_xor);
2958 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00002959 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
2960 COPYNUM(nb_true_divide);
2961 COPYNUM(nb_floor_divide);
2962 COPYNUM(nb_inplace_true_divide);
2963 COPYNUM(nb_inplace_floor_divide);
2964 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002965 }
2966
Guido van Rossum13d52f02001-08-10 21:24:08 +00002967 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
2968 basebase = base->tp_base;
2969 if (basebase->tp_as_sequence == NULL)
2970 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002971 COPYSEQ(sq_length);
2972 COPYSEQ(sq_concat);
2973 COPYSEQ(sq_repeat);
2974 COPYSEQ(sq_item);
2975 COPYSEQ(sq_slice);
2976 COPYSEQ(sq_ass_item);
2977 COPYSEQ(sq_ass_slice);
2978 COPYSEQ(sq_contains);
2979 COPYSEQ(sq_inplace_concat);
2980 COPYSEQ(sq_inplace_repeat);
2981 }
2982
Guido van Rossum13d52f02001-08-10 21:24:08 +00002983 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
2984 basebase = base->tp_base;
2985 if (basebase->tp_as_mapping == NULL)
2986 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002987 COPYMAP(mp_length);
2988 COPYMAP(mp_subscript);
2989 COPYMAP(mp_ass_subscript);
2990 }
2991
Tim Petersfc57ccb2001-10-12 02:38:24 +00002992 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
2993 basebase = base->tp_base;
2994 if (basebase->tp_as_buffer == NULL)
2995 basebase = NULL;
2996 COPYBUF(bf_getreadbuffer);
2997 COPYBUF(bf_getwritebuffer);
2998 COPYBUF(bf_getsegcount);
2999 COPYBUF(bf_getcharbuffer);
3000 }
3001
Guido van Rossum13d52f02001-08-10 21:24:08 +00003002 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003003
Tim Peters6d6c1a32001-08-02 04:15:00 +00003004 COPYSLOT(tp_dealloc);
3005 COPYSLOT(tp_print);
3006 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
3007 type->tp_getattr = base->tp_getattr;
3008 type->tp_getattro = base->tp_getattro;
3009 }
3010 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
3011 type->tp_setattr = base->tp_setattr;
3012 type->tp_setattro = base->tp_setattro;
3013 }
3014 /* tp_compare see tp_richcompare */
3015 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003016 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003017 COPYSLOT(tp_call);
3018 COPYSLOT(tp_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003019 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003020 if (type->tp_compare == NULL &&
3021 type->tp_richcompare == NULL &&
3022 type->tp_hash == NULL)
3023 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003024 type->tp_compare = base->tp_compare;
3025 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003026 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003027 }
3028 }
3029 else {
3030 COPYSLOT(tp_compare);
3031 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003032 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
3033 COPYSLOT(tp_iter);
3034 COPYSLOT(tp_iternext);
3035 }
3036 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
3037 COPYSLOT(tp_descr_get);
3038 COPYSLOT(tp_descr_set);
3039 COPYSLOT(tp_dictoffset);
3040 COPYSLOT(tp_init);
3041 COPYSLOT(tp_alloc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003042 COPYSLOT(tp_free);
Guido van Rossumcc8fe042002-04-05 17:10:16 +00003043 COPYSLOT(tp_is_gc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003044 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003045}
3046
Jeremy Hylton938ace62002-07-17 16:30:39 +00003047static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00003048
Tim Peters6d6c1a32001-08-02 04:15:00 +00003049int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00003050PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003051{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003052 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003053 PyTypeObject *base;
3054 int i, n;
3055
Guido van Rossumcab05802002-06-10 15:29:03 +00003056 if (type->tp_flags & Py_TPFLAGS_READY) {
3057 assert(type->tp_dict != NULL);
Guido van Rossumd614f972001-08-10 17:39:49 +00003058 return 0;
Guido van Rossumcab05802002-06-10 15:29:03 +00003059 }
Guido van Rossumd614f972001-08-10 17:39:49 +00003060 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00003061
3062 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003063
Tim Peters36eb4df2003-03-23 03:33:13 +00003064#ifdef Py_TRACE_REFS
3065 /* PyType_Ready is the closest thing we have to a choke point
3066 * for type objects, so is the best place I can think of to try
3067 * to get type objects into the doubly-linked list of all objects.
3068 * Still, not all type objects go thru PyType_Ready.
3069 */
Tim Peters7571a0f2003-03-23 17:52:28 +00003070 _Py_AddToAllObjects((PyObject *)type, 0);
Tim Peters36eb4df2003-03-23 03:33:13 +00003071#endif
3072
Tim Peters6d6c1a32001-08-02 04:15:00 +00003073 /* Initialize tp_base (defaults to BaseObject unless that's us) */
3074 base = type->tp_base;
3075 if (base == NULL && type != &PyBaseObject_Type)
3076 base = type->tp_base = &PyBaseObject_Type;
3077
Guido van Rossum323a9cf2002-08-14 17:26:30 +00003078 /* Initialize the base class */
3079 if (base && base->tp_dict == NULL) {
3080 if (PyType_Ready(base) < 0)
3081 goto error;
3082 }
3083
Guido van Rossum0986d822002-04-08 01:38:42 +00003084 /* Initialize ob_type if NULL. This means extensions that want to be
3085 compilable separately on Windows can call PyType_Ready() instead of
3086 initializing the ob_type field of their type objects. */
3087 if (type->ob_type == NULL)
3088 type->ob_type = base->ob_type;
3089
Tim Peters6d6c1a32001-08-02 04:15:00 +00003090 /* Initialize tp_bases */
3091 bases = type->tp_bases;
3092 if (bases == NULL) {
3093 if (base == NULL)
3094 bases = PyTuple_New(0);
3095 else
3096 bases = Py_BuildValue("(O)", base);
3097 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003098 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003099 type->tp_bases = bases;
3100 }
3101
Guido van Rossum687ae002001-10-15 22:03:32 +00003102 /* Initialize tp_dict */
3103 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003104 if (dict == NULL) {
3105 dict = PyDict_New();
3106 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003107 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00003108 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003109 }
3110
Guido van Rossum687ae002001-10-15 22:03:32 +00003111 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003112 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003113 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003114 if (type->tp_methods != NULL) {
3115 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003116 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003117 }
3118 if (type->tp_members != NULL) {
3119 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003120 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003121 }
3122 if (type->tp_getset != NULL) {
3123 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003124 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003125 }
3126
Tim Peters6d6c1a32001-08-02 04:15:00 +00003127 /* Calculate method resolution order */
3128 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00003129 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003130 }
3131
Guido van Rossum13d52f02001-08-10 21:24:08 +00003132 /* Inherit special flags from dominant base */
3133 if (type->tp_base != NULL)
3134 inherit_special(type, type->tp_base);
3135
Tim Peters6d6c1a32001-08-02 04:15:00 +00003136 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003137 bases = type->tp_mro;
3138 assert(bases != NULL);
3139 assert(PyTuple_Check(bases));
3140 n = PyTuple_GET_SIZE(bases);
3141 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003142 PyObject *b = PyTuple_GET_ITEM(bases, i);
3143 if (PyType_Check(b))
3144 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003145 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003146
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003147 /* if the type dictionary doesn't contain a __doc__, set it from
3148 the tp_doc slot.
3149 */
3150 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
3151 if (type->tp_doc != NULL) {
3152 PyObject *doc = PyString_FromString(type->tp_doc);
3153 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
3154 Py_DECREF(doc);
3155 } else {
Guido van Rossumd4641072002-04-03 02:13:37 +00003156 PyDict_SetItemString(type->tp_dict,
3157 "__doc__", Py_None);
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003158 }
3159 }
3160
Guido van Rossum13d52f02001-08-10 21:24:08 +00003161 /* Some more special stuff */
3162 base = type->tp_base;
3163 if (base != NULL) {
3164 if (type->tp_as_number == NULL)
3165 type->tp_as_number = base->tp_as_number;
3166 if (type->tp_as_sequence == NULL)
3167 type->tp_as_sequence = base->tp_as_sequence;
3168 if (type->tp_as_mapping == NULL)
3169 type->tp_as_mapping = base->tp_as_mapping;
Guido van Rossumeea47182003-02-11 20:39:59 +00003170 if (type->tp_as_buffer == NULL)
3171 type->tp_as_buffer = base->tp_as_buffer;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003172 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003173
Guido van Rossum1c450732001-10-08 15:18:27 +00003174 /* Link into each base class's list of subclasses */
3175 bases = type->tp_bases;
3176 n = PyTuple_GET_SIZE(bases);
3177 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003178 PyObject *b = PyTuple_GET_ITEM(bases, i);
3179 if (PyType_Check(b) &&
3180 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00003181 goto error;
3182 }
3183
Guido van Rossum13d52f02001-08-10 21:24:08 +00003184 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00003185 assert(type->tp_dict != NULL);
3186 type->tp_flags =
3187 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003188 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00003189
3190 error:
3191 type->tp_flags &= ~Py_TPFLAGS_READYING;
3192 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003193}
3194
Guido van Rossum1c450732001-10-08 15:18:27 +00003195static int
3196add_subclass(PyTypeObject *base, PyTypeObject *type)
3197{
3198 int i;
3199 PyObject *list, *ref, *new;
3200
3201 list = base->tp_subclasses;
3202 if (list == NULL) {
3203 base->tp_subclasses = list = PyList_New(0);
3204 if (list == NULL)
3205 return -1;
3206 }
3207 assert(PyList_Check(list));
3208 new = PyWeakref_NewRef((PyObject *)type, NULL);
3209 i = PyList_GET_SIZE(list);
3210 while (--i >= 0) {
3211 ref = PyList_GET_ITEM(list, i);
3212 assert(PyWeakref_CheckRef(ref));
Guido van Rossum3930bc32002-10-18 13:51:49 +00003213 if (PyWeakref_GET_OBJECT(ref) == Py_None)
3214 return PyList_SetItem(list, i, new);
Guido van Rossum1c450732001-10-08 15:18:27 +00003215 }
3216 i = PyList_Append(list, new);
3217 Py_DECREF(new);
3218 return i;
3219}
3220
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003221static void
3222remove_subclass(PyTypeObject *base, PyTypeObject *type)
3223{
3224 int i;
3225 PyObject *list, *ref;
3226
3227 list = base->tp_subclasses;
3228 if (list == NULL) {
3229 return;
3230 }
3231 assert(PyList_Check(list));
3232 i = PyList_GET_SIZE(list);
3233 while (--i >= 0) {
3234 ref = PyList_GET_ITEM(list, i);
3235 assert(PyWeakref_CheckRef(ref));
3236 if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
3237 /* this can't fail, right? */
3238 PySequence_DelItem(list, i);
3239 return;
3240 }
3241 }
3242}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003243
3244/* Generic wrappers for overloadable 'operators' such as __getitem__ */
3245
3246/* There's a wrapper *function* for each distinct function typedef used
3247 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
3248 wrapper *table* for each distinct operation (e.g. __len__, __add__).
3249 Most tables have only one entry; the tables for binary operators have two
3250 entries, one regular and one with reversed arguments. */
3251
3252static PyObject *
3253wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
3254{
3255 inquiry func = (inquiry)wrapped;
3256 int res;
3257
3258 if (!PyArg_ParseTuple(args, ""))
3259 return NULL;
3260 res = (*func)(self);
3261 if (res == -1 && PyErr_Occurred())
3262 return NULL;
3263 return PyInt_FromLong((long)res);
3264}
3265
Tim Peters6d6c1a32001-08-02 04:15:00 +00003266static PyObject *
3267wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
3268{
3269 binaryfunc func = (binaryfunc)wrapped;
3270 PyObject *other;
3271
3272 if (!PyArg_ParseTuple(args, "O", &other))
3273 return NULL;
3274 return (*func)(self, other);
3275}
3276
3277static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003278wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
3279{
3280 binaryfunc func = (binaryfunc)wrapped;
3281 PyObject *other;
3282
3283 if (!PyArg_ParseTuple(args, "O", &other))
3284 return NULL;
3285 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003286 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003287 Py_INCREF(Py_NotImplemented);
3288 return Py_NotImplemented;
3289 }
3290 return (*func)(self, other);
3291}
3292
3293static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003294wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3295{
3296 binaryfunc func = (binaryfunc)wrapped;
3297 PyObject *other;
3298
3299 if (!PyArg_ParseTuple(args, "O", &other))
3300 return NULL;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003301 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003302 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003303 Py_INCREF(Py_NotImplemented);
3304 return Py_NotImplemented;
3305 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003306 return (*func)(other, self);
3307}
3308
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003309static PyObject *
3310wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
3311{
3312 coercion func = (coercion)wrapped;
3313 PyObject *other, *res;
3314 int ok;
3315
3316 if (!PyArg_ParseTuple(args, "O", &other))
3317 return NULL;
3318 ok = func(&self, &other);
3319 if (ok < 0)
3320 return NULL;
3321 if (ok > 0) {
3322 Py_INCREF(Py_NotImplemented);
3323 return Py_NotImplemented;
3324 }
3325 res = PyTuple_New(2);
3326 if (res == NULL) {
3327 Py_DECREF(self);
3328 Py_DECREF(other);
3329 return NULL;
3330 }
3331 PyTuple_SET_ITEM(res, 0, self);
3332 PyTuple_SET_ITEM(res, 1, other);
3333 return res;
3334}
3335
Tim Peters6d6c1a32001-08-02 04:15:00 +00003336static PyObject *
3337wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
3338{
3339 ternaryfunc func = (ternaryfunc)wrapped;
3340 PyObject *other;
3341 PyObject *third = Py_None;
3342
3343 /* Note: This wrapper only works for __pow__() */
3344
3345 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
3346 return NULL;
3347 return (*func)(self, other, third);
3348}
3349
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00003350static PyObject *
3351wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3352{
3353 ternaryfunc func = (ternaryfunc)wrapped;
3354 PyObject *other;
3355 PyObject *third = Py_None;
3356
3357 /* Note: This wrapper only works for __pow__() */
3358
3359 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
3360 return NULL;
3361 return (*func)(other, self, third);
3362}
3363
Tim Peters6d6c1a32001-08-02 04:15:00 +00003364static PyObject *
3365wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
3366{
3367 unaryfunc func = (unaryfunc)wrapped;
3368
3369 if (!PyArg_ParseTuple(args, ""))
3370 return NULL;
3371 return (*func)(self);
3372}
3373
Tim Peters6d6c1a32001-08-02 04:15:00 +00003374static PyObject *
3375wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
3376{
3377 intargfunc func = (intargfunc)wrapped;
3378 int i;
3379
3380 if (!PyArg_ParseTuple(args, "i", &i))
3381 return NULL;
3382 return (*func)(self, i);
3383}
3384
Guido van Rossum5d815f32001-08-17 21:57:47 +00003385static int
3386getindex(PyObject *self, PyObject *arg)
3387{
3388 int i;
3389
3390 i = PyInt_AsLong(arg);
3391 if (i == -1 && PyErr_Occurred())
3392 return -1;
3393 if (i < 0) {
3394 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
3395 if (sq && sq->sq_length) {
3396 int n = (*sq->sq_length)(self);
3397 if (n < 0)
3398 return -1;
3399 i += n;
3400 }
3401 }
3402 return i;
3403}
3404
3405static PyObject *
3406wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
3407{
3408 intargfunc func = (intargfunc)wrapped;
3409 PyObject *arg;
3410 int i;
3411
Guido van Rossumf4593e02001-10-03 12:09:30 +00003412 if (PyTuple_GET_SIZE(args) == 1) {
3413 arg = PyTuple_GET_ITEM(args, 0);
3414 i = getindex(self, arg);
3415 if (i == -1 && PyErr_Occurred())
3416 return NULL;
3417 return (*func)(self, i);
3418 }
3419 PyArg_ParseTuple(args, "O", &arg);
3420 assert(PyErr_Occurred());
3421 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003422}
3423
Tim Peters6d6c1a32001-08-02 04:15:00 +00003424static PyObject *
3425wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
3426{
3427 intintargfunc func = (intintargfunc)wrapped;
3428 int i, j;
3429
3430 if (!PyArg_ParseTuple(args, "ii", &i, &j))
3431 return NULL;
3432 return (*func)(self, i, j);
3433}
3434
Tim Peters6d6c1a32001-08-02 04:15:00 +00003435static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003436wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003437{
3438 intobjargproc func = (intobjargproc)wrapped;
3439 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003440 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003441
Guido van Rossum5d815f32001-08-17 21:57:47 +00003442 if (!PyArg_ParseTuple(args, "OO", &arg, &value))
3443 return NULL;
3444 i = getindex(self, arg);
3445 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00003446 return NULL;
3447 res = (*func)(self, i, value);
3448 if (res == -1 && PyErr_Occurred())
3449 return NULL;
3450 Py_INCREF(Py_None);
3451 return Py_None;
3452}
3453
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003454static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003455wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003456{
3457 intobjargproc func = (intobjargproc)wrapped;
3458 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003459 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003460
Guido van Rossum5d815f32001-08-17 21:57:47 +00003461 if (!PyArg_ParseTuple(args, "O", &arg))
3462 return NULL;
3463 i = getindex(self, arg);
3464 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003465 return NULL;
3466 res = (*func)(self, i, NULL);
3467 if (res == -1 && PyErr_Occurred())
3468 return NULL;
3469 Py_INCREF(Py_None);
3470 return Py_None;
3471}
3472
Tim Peters6d6c1a32001-08-02 04:15:00 +00003473static PyObject *
3474wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
3475{
3476 intintobjargproc func = (intintobjargproc)wrapped;
3477 int i, j, res;
3478 PyObject *value;
3479
3480 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
3481 return NULL;
3482 res = (*func)(self, i, j, value);
3483 if (res == -1 && PyErr_Occurred())
3484 return NULL;
3485 Py_INCREF(Py_None);
3486 return Py_None;
3487}
3488
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003489static PyObject *
3490wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
3491{
3492 intintobjargproc func = (intintobjargproc)wrapped;
3493 int i, j, res;
3494
3495 if (!PyArg_ParseTuple(args, "ii", &i, &j))
3496 return NULL;
3497 res = (*func)(self, i, j, NULL);
3498 if (res == -1 && PyErr_Occurred())
3499 return NULL;
3500 Py_INCREF(Py_None);
3501 return Py_None;
3502}
3503
Tim Peters6d6c1a32001-08-02 04:15:00 +00003504/* XXX objobjproc is a misnomer; should be objargpred */
3505static PyObject *
3506wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
3507{
3508 objobjproc func = (objobjproc)wrapped;
3509 int res;
3510 PyObject *value;
3511
3512 if (!PyArg_ParseTuple(args, "O", &value))
3513 return NULL;
3514 res = (*func)(self, value);
3515 if (res == -1 && PyErr_Occurred())
3516 return NULL;
3517 return PyInt_FromLong((long)res);
3518}
3519
Tim Peters6d6c1a32001-08-02 04:15:00 +00003520static PyObject *
3521wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
3522{
3523 objobjargproc func = (objobjargproc)wrapped;
3524 int res;
3525 PyObject *key, *value;
3526
3527 if (!PyArg_ParseTuple(args, "OO", &key, &value))
3528 return NULL;
3529 res = (*func)(self, key, value);
3530 if (res == -1 && PyErr_Occurred())
3531 return NULL;
3532 Py_INCREF(Py_None);
3533 return Py_None;
3534}
3535
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003536static PyObject *
3537wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
3538{
3539 objobjargproc func = (objobjargproc)wrapped;
3540 int res;
3541 PyObject *key;
3542
3543 if (!PyArg_ParseTuple(args, "O", &key))
3544 return NULL;
3545 res = (*func)(self, key, NULL);
3546 if (res == -1 && PyErr_Occurred())
3547 return NULL;
3548 Py_INCREF(Py_None);
3549 return Py_None;
3550}
3551
Tim Peters6d6c1a32001-08-02 04:15:00 +00003552static PyObject *
3553wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
3554{
3555 cmpfunc func = (cmpfunc)wrapped;
3556 int res;
3557 PyObject *other;
3558
3559 if (!PyArg_ParseTuple(args, "O", &other))
3560 return NULL;
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00003561 if (other->ob_type->tp_compare != func &&
3562 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00003563 PyErr_Format(
3564 PyExc_TypeError,
3565 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
3566 self->ob_type->tp_name,
3567 self->ob_type->tp_name,
3568 other->ob_type->tp_name);
3569 return NULL;
3570 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003571 res = (*func)(self, other);
3572 if (PyErr_Occurred())
3573 return NULL;
3574 return PyInt_FromLong((long)res);
3575}
3576
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003577/* Helper to check for object.__setattr__ or __delattr__ applied to a type.
3578 This is called the Verre Carlo hack after its discoverer. */
3579static int
3580hackcheck(PyObject *self, setattrofunc func, char *what)
3581{
3582 PyTypeObject *type = self->ob_type;
3583 while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE)
3584 type = type->tp_base;
3585 if (type->tp_setattro != func) {
3586 PyErr_Format(PyExc_TypeError,
3587 "can't apply this %s to %s object",
3588 what,
3589 type->tp_name);
3590 return 0;
3591 }
3592 return 1;
3593}
3594
Tim Peters6d6c1a32001-08-02 04:15:00 +00003595static PyObject *
3596wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
3597{
3598 setattrofunc func = (setattrofunc)wrapped;
3599 int res;
3600 PyObject *name, *value;
3601
3602 if (!PyArg_ParseTuple(args, "OO", &name, &value))
3603 return NULL;
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003604 if (!hackcheck(self, func, "__setattr__"))
3605 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003606 res = (*func)(self, name, value);
3607 if (res < 0)
3608 return NULL;
3609 Py_INCREF(Py_None);
3610 return Py_None;
3611}
3612
3613static PyObject *
3614wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
3615{
3616 setattrofunc func = (setattrofunc)wrapped;
3617 int res;
3618 PyObject *name;
3619
3620 if (!PyArg_ParseTuple(args, "O", &name))
3621 return NULL;
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003622 if (!hackcheck(self, func, "__delattr__"))
3623 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003624 res = (*func)(self, name, NULL);
3625 if (res < 0)
3626 return NULL;
3627 Py_INCREF(Py_None);
3628 return Py_None;
3629}
3630
Tim Peters6d6c1a32001-08-02 04:15:00 +00003631static PyObject *
3632wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
3633{
3634 hashfunc func = (hashfunc)wrapped;
3635 long res;
3636
3637 if (!PyArg_ParseTuple(args, ""))
3638 return NULL;
3639 res = (*func)(self);
3640 if (res == -1 && PyErr_Occurred())
3641 return NULL;
3642 return PyInt_FromLong(res);
3643}
3644
Tim Peters6d6c1a32001-08-02 04:15:00 +00003645static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00003646wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003647{
3648 ternaryfunc func = (ternaryfunc)wrapped;
3649
Guido van Rossumc8e56452001-10-22 00:43:43 +00003650 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003651}
3652
Tim Peters6d6c1a32001-08-02 04:15:00 +00003653static PyObject *
3654wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
3655{
3656 richcmpfunc func = (richcmpfunc)wrapped;
3657 PyObject *other;
3658
3659 if (!PyArg_ParseTuple(args, "O", &other))
3660 return NULL;
3661 return (*func)(self, other, op);
3662}
3663
3664#undef RICHCMP_WRAPPER
3665#define RICHCMP_WRAPPER(NAME, OP) \
3666static PyObject * \
3667richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
3668{ \
3669 return wrap_richcmpfunc(self, args, wrapped, OP); \
3670}
3671
Jack Jansen8e938b42001-08-08 15:29:49 +00003672RICHCMP_WRAPPER(lt, Py_LT)
3673RICHCMP_WRAPPER(le, Py_LE)
3674RICHCMP_WRAPPER(eq, Py_EQ)
3675RICHCMP_WRAPPER(ne, Py_NE)
3676RICHCMP_WRAPPER(gt, Py_GT)
3677RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003678
Tim Peters6d6c1a32001-08-02 04:15:00 +00003679static PyObject *
3680wrap_next(PyObject *self, PyObject *args, void *wrapped)
3681{
3682 unaryfunc func = (unaryfunc)wrapped;
3683 PyObject *res;
3684
3685 if (!PyArg_ParseTuple(args, ""))
3686 return NULL;
3687 res = (*func)(self);
3688 if (res == NULL && !PyErr_Occurred())
3689 PyErr_SetNone(PyExc_StopIteration);
3690 return res;
3691}
3692
Tim Peters6d6c1a32001-08-02 04:15:00 +00003693static PyObject *
3694wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
3695{
3696 descrgetfunc func = (descrgetfunc)wrapped;
3697 PyObject *obj;
3698 PyObject *type = NULL;
3699
3700 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
3701 return NULL;
Guido van Rossum82ed25c2003-02-11 16:25:43 +00003702 if (obj == Py_None)
3703 obj = NULL;
3704 if (type == Py_None)
3705 type = NULL;
3706 if (type == NULL &&obj == NULL) {
3707 PyErr_SetString(PyExc_TypeError,
3708 "__get__(None, None) is invalid");
3709 return NULL;
3710 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003711 return (*func)(self, obj, type);
3712}
3713
Tim Peters6d6c1a32001-08-02 04:15:00 +00003714static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003715wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003716{
3717 descrsetfunc func = (descrsetfunc)wrapped;
3718 PyObject *obj, *value;
3719 int ret;
3720
3721 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
3722 return NULL;
3723 ret = (*func)(self, obj, value);
3724 if (ret < 0)
3725 return NULL;
3726 Py_INCREF(Py_None);
3727 return Py_None;
3728}
Guido van Rossum22b13872002-08-06 21:41:44 +00003729
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00003730static PyObject *
3731wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
3732{
3733 descrsetfunc func = (descrsetfunc)wrapped;
3734 PyObject *obj;
3735 int ret;
3736
3737 if (!PyArg_ParseTuple(args, "O", &obj))
3738 return NULL;
3739 ret = (*func)(self, obj, NULL);
3740 if (ret < 0)
3741 return NULL;
3742 Py_INCREF(Py_None);
3743 return Py_None;
3744}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003745
Tim Peters6d6c1a32001-08-02 04:15:00 +00003746static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00003747wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003748{
3749 initproc func = (initproc)wrapped;
3750
Guido van Rossumc8e56452001-10-22 00:43:43 +00003751 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003752 return NULL;
3753 Py_INCREF(Py_None);
3754 return Py_None;
3755}
3756
Tim Peters6d6c1a32001-08-02 04:15:00 +00003757static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003758tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003759{
Barry Warsaw60f01882001-08-22 19:24:42 +00003760 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003761 PyObject *arg0, *res;
3762
3763 if (self == NULL || !PyType_Check(self))
3764 Py_FatalError("__new__() called with non-type 'self'");
3765 type = (PyTypeObject *)self;
3766 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003767 PyErr_Format(PyExc_TypeError,
3768 "%s.__new__(): not enough arguments",
3769 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003770 return NULL;
3771 }
3772 arg0 = PyTuple_GET_ITEM(args, 0);
3773 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003774 PyErr_Format(PyExc_TypeError,
3775 "%s.__new__(X): X is not a type object (%s)",
3776 type->tp_name,
3777 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003778 return NULL;
3779 }
3780 subtype = (PyTypeObject *)arg0;
3781 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003782 PyErr_Format(PyExc_TypeError,
3783 "%s.__new__(%s): %s is not a subtype of %s",
3784 type->tp_name,
3785 subtype->tp_name,
3786 subtype->tp_name,
3787 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003788 return NULL;
3789 }
Barry Warsaw60f01882001-08-22 19:24:42 +00003790
3791 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00003792 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00003793 most derived base that's not a heap type is this type. */
3794 staticbase = subtype;
3795 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
3796 staticbase = staticbase->tp_base;
Guido van Rossuma8c60f42001-09-14 19:43:36 +00003797 if (staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003798 PyErr_Format(PyExc_TypeError,
3799 "%s.__new__(%s) is not safe, use %s.__new__()",
3800 type->tp_name,
3801 subtype->tp_name,
3802 staticbase == NULL ? "?" : staticbase->tp_name);
3803 return NULL;
3804 }
3805
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003806 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
3807 if (args == NULL)
3808 return NULL;
3809 res = type->tp_new(subtype, args, kwds);
3810 Py_DECREF(args);
3811 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003812}
3813
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003814static struct PyMethodDef tp_new_methoddef[] = {
3815 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00003816 PyDoc_STR("T.__new__(S, ...) -> "
3817 "a new object with type S, a subtype of T")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00003818 {0}
3819};
3820
3821static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003822add_tp_new_wrapper(PyTypeObject *type)
3823{
Guido van Rossumf040ede2001-08-07 16:40:56 +00003824 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003825
Guido van Rossum687ae002001-10-15 22:03:32 +00003826 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00003827 return 0;
3828 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003829 if (func == NULL)
3830 return -1;
Guido van Rossum687ae002001-10-15 22:03:32 +00003831 return PyDict_SetItemString(type->tp_dict, "__new__", func);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003832}
3833
Guido van Rossumf040ede2001-08-07 16:40:56 +00003834/* Slot wrappers that call the corresponding __foo__ slot. See comments
3835 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003836
Guido van Rossumdc91b992001-08-08 22:26:22 +00003837#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003838static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003839FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003840{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00003841 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003842 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003843}
3844
Guido van Rossumdc91b992001-08-08 22:26:22 +00003845#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003846static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003847FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003848{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003849 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003850 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003851}
3852
Guido van Rossumcd118802003-01-06 22:57:47 +00003853/* Boolean helper for SLOT1BINFULL().
3854 right.__class__ is a nontrivial subclass of left.__class__. */
3855static int
3856method_is_overloaded(PyObject *left, PyObject *right, char *name)
3857{
3858 PyObject *a, *b;
3859 int ok;
3860
3861 b = PyObject_GetAttrString((PyObject *)(right->ob_type), name);
3862 if (b == NULL) {
3863 PyErr_Clear();
3864 /* If right doesn't have it, it's not overloaded */
3865 return 0;
3866 }
3867
3868 a = PyObject_GetAttrString((PyObject *)(left->ob_type), name);
3869 if (a == NULL) {
3870 PyErr_Clear();
3871 Py_DECREF(b);
3872 /* If right has it but left doesn't, it's overloaded */
3873 return 1;
3874 }
3875
3876 ok = PyObject_RichCompareBool(a, b, Py_NE);
3877 Py_DECREF(a);
3878 Py_DECREF(b);
3879 if (ok < 0) {
3880 PyErr_Clear();
3881 return 0;
3882 }
3883
3884 return ok;
3885}
3886
Guido van Rossumdc91b992001-08-08 22:26:22 +00003887
3888#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003889static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003890FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003891{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003892 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00003893 int do_other = self->ob_type != other->ob_type && \
3894 other->ob_type->tp_as_number != NULL && \
3895 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003896 if (self->ob_type->tp_as_number != NULL && \
3897 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
3898 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00003899 if (do_other && \
Guido van Rossumcd118802003-01-06 22:57:47 +00003900 PyType_IsSubtype(other->ob_type, self->ob_type) && \
3901 method_is_overloaded(self, other, ROPSTR)) { \
Guido van Rossum55f20992001-10-01 17:18:22 +00003902 r = call_maybe( \
3903 other, ROPSTR, &rcache_str, "(O)", self); \
3904 if (r != Py_NotImplemented) \
3905 return r; \
3906 Py_DECREF(r); \
3907 do_other = 0; \
3908 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00003909 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00003910 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003911 if (r != Py_NotImplemented || \
3912 other->ob_type == self->ob_type) \
3913 return r; \
3914 Py_DECREF(r); \
3915 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00003916 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00003917 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00003918 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003919 } \
3920 Py_INCREF(Py_NotImplemented); \
3921 return Py_NotImplemented; \
3922}
3923
3924#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
3925 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
3926
3927#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
3928static PyObject * \
3929FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
3930{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003931 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003932 return call_method(self, OPSTR, &cache_str, \
3933 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003934}
3935
3936static int
3937slot_sq_length(PyObject *self)
3938{
Guido van Rossum2730b132001-08-28 18:22:14 +00003939 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00003940 PyObject *res = call_method(self, "__len__", &len_str, "()");
Guido van Rossum26111622001-10-01 16:42:49 +00003941 int len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003942
3943 if (res == NULL)
3944 return -1;
Guido van Rossum26111622001-10-01 16:42:49 +00003945 len = (int)PyInt_AsLong(res);
3946 Py_DECREF(res);
Jeremy Hylton73a088e2002-07-25 16:43:29 +00003947 if (len == -1 && PyErr_Occurred())
3948 return -1;
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00003949 if (len < 0) {
Guido van Rossum22b13872002-08-06 21:41:44 +00003950 PyErr_SetString(PyExc_ValueError,
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00003951 "__len__() should return >= 0");
3952 return -1;
3953 }
Guido van Rossum26111622001-10-01 16:42:49 +00003954 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003955}
3956
Guido van Rossumdc91b992001-08-08 22:26:22 +00003957SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
3958SLOT1(slot_sq_repeat, "__mul__", int, "i")
Guido van Rossumf4593e02001-10-03 12:09:30 +00003959
3960/* Super-optimized version of slot_sq_item.
3961 Other slots could do the same... */
3962static PyObject *
3963slot_sq_item(PyObject *self, int i)
3964{
3965 static PyObject *getitem_str;
3966 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
3967 descrgetfunc f;
3968
3969 if (getitem_str == NULL) {
3970 getitem_str = PyString_InternFromString("__getitem__");
3971 if (getitem_str == NULL)
3972 return NULL;
3973 }
3974 func = _PyType_Lookup(self->ob_type, getitem_str);
3975 if (func != NULL) {
Guido van Rossumf4593e02001-10-03 12:09:30 +00003976 if ((f = func->ob_type->tp_descr_get) == NULL)
3977 Py_INCREF(func);
Neal Norwitz673cd822002-10-18 16:33:13 +00003978 else {
Guido van Rossumf4593e02001-10-03 12:09:30 +00003979 func = f(func, self, (PyObject *)(self->ob_type));
Neal Norwitz673cd822002-10-18 16:33:13 +00003980 if (func == NULL) {
3981 return NULL;
3982 }
3983 }
Guido van Rossumf4593e02001-10-03 12:09:30 +00003984 ival = PyInt_FromLong(i);
3985 if (ival != NULL) {
3986 args = PyTuple_New(1);
3987 if (args != NULL) {
3988 PyTuple_SET_ITEM(args, 0, ival);
3989 retval = PyObject_Call(func, args, NULL);
3990 Py_XDECREF(args);
3991 Py_XDECREF(func);
3992 return retval;
3993 }
3994 }
3995 }
3996 else {
3997 PyErr_SetObject(PyExc_AttributeError, getitem_str);
3998 }
3999 Py_XDECREF(args);
4000 Py_XDECREF(ival);
4001 Py_XDECREF(func);
4002 return NULL;
4003}
4004
Guido van Rossumdc91b992001-08-08 22:26:22 +00004005SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004006
4007static int
4008slot_sq_ass_item(PyObject *self, int index, PyObject *value)
4009{
4010 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004011 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004012
4013 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004014 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004015 "(i)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004016 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004017 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004018 "(iO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004019 if (res == NULL)
4020 return -1;
4021 Py_DECREF(res);
4022 return 0;
4023}
4024
4025static int
4026slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
4027{
4028 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004029 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004030
4031 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004032 res = call_method(self, "__delslice__", &delslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004033 "(ii)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004034 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004035 res = call_method(self, "__setslice__", &setslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004036 "(iiO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004037 if (res == NULL)
4038 return -1;
4039 Py_DECREF(res);
4040 return 0;
4041}
4042
4043static int
4044slot_sq_contains(PyObject *self, PyObject *value)
4045{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004046 PyObject *func, *res, *args;
Tim Petersbf9b2442003-03-23 05:35:36 +00004047 int result = -1;
4048
Guido van Rossum60718732001-08-28 17:47:51 +00004049 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004050
Guido van Rossum55f20992001-10-01 17:18:22 +00004051 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004052 if (func != NULL) {
4053 args = Py_BuildValue("(O)", value);
4054 if (args == NULL)
4055 res = NULL;
4056 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004057 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004058 Py_DECREF(args);
4059 }
4060 Py_DECREF(func);
Tim Petersbf9b2442003-03-23 05:35:36 +00004061 if (res != NULL) {
4062 result = PyObject_IsTrue(res);
4063 Py_DECREF(res);
4064 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004065 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004066 else if (! PyErr_Occurred()) {
4067 result = _PySequence_IterSearch(self, value,
4068 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004069 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004070 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004071}
4072
Guido van Rossumdc91b992001-08-08 22:26:22 +00004073SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
4074SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004075
4076#define slot_mp_length slot_sq_length
4077
Guido van Rossumdc91b992001-08-08 22:26:22 +00004078SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004079
4080static int
4081slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
4082{
4083 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004084 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004085
4086 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004087 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004088 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004089 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004090 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004091 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004092 if (res == NULL)
4093 return -1;
4094 Py_DECREF(res);
4095 return 0;
4096}
4097
Guido van Rossumdc91b992001-08-08 22:26:22 +00004098SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
4099SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
4100SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
4101SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
4102SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
4103SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
4104
Jeremy Hylton938ace62002-07-17 16:30:39 +00004105static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00004106
4107SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
4108 nb_power, "__pow__", "__rpow__")
4109
4110static PyObject *
4111slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
4112{
Guido van Rossum2730b132001-08-28 18:22:14 +00004113 static PyObject *pow_str;
4114
Guido van Rossumdc91b992001-08-08 22:26:22 +00004115 if (modulus == Py_None)
4116 return slot_nb_power_binary(self, other);
Guido van Rossum23094982002-06-10 14:30:43 +00004117 /* Three-arg power doesn't use __rpow__. But ternary_op
4118 can call this when the second argument's type uses
4119 slot_nb_power, so check before calling self.__pow__. */
4120 if (self->ob_type->tp_as_number != NULL &&
4121 self->ob_type->tp_as_number->nb_power == slot_nb_power) {
4122 return call_method(self, "__pow__", &pow_str,
4123 "(OO)", other, modulus);
4124 }
4125 Py_INCREF(Py_NotImplemented);
4126 return Py_NotImplemented;
Guido van Rossumdc91b992001-08-08 22:26:22 +00004127}
4128
4129SLOT0(slot_nb_negative, "__neg__")
4130SLOT0(slot_nb_positive, "__pos__")
4131SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004132
4133static int
4134slot_nb_nonzero(PyObject *self)
4135{
Tim Petersea7f75d2002-12-07 21:39:16 +00004136 PyObject *func, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00004137 static PyObject *nonzero_str, *len_str;
Tim Petersea7f75d2002-12-07 21:39:16 +00004138 int result = -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004139
Guido van Rossum55f20992001-10-01 17:18:22 +00004140 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004141 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00004142 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00004143 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00004144 func = lookup_maybe(self, "__len__", &len_str);
Tim Petersea7f75d2002-12-07 21:39:16 +00004145 if (func == NULL)
4146 return PyErr_Occurred() ? -1 : 1;
4147 }
4148 args = PyTuple_New(0);
4149 if (args != NULL) {
4150 PyObject *temp = PyObject_Call(func, args, NULL);
4151 Py_DECREF(args);
4152 if (temp != NULL) {
4153 result = PyObject_IsTrue(temp);
4154 Py_DECREF(temp);
Guido van Rossum55f20992001-10-01 17:18:22 +00004155 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004156 }
Guido van Rossum55f20992001-10-01 17:18:22 +00004157 Py_DECREF(func);
Tim Petersea7f75d2002-12-07 21:39:16 +00004158 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004159}
4160
Guido van Rossumdc91b992001-08-08 22:26:22 +00004161SLOT0(slot_nb_invert, "__invert__")
4162SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
4163SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
4164SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
4165SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
4166SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004167
4168static int
4169slot_nb_coerce(PyObject **a, PyObject **b)
4170{
4171 static PyObject *coerce_str;
4172 PyObject *self = *a, *other = *b;
4173
4174 if (self->ob_type->tp_as_number != NULL &&
4175 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
4176 PyObject *r;
4177 r = call_maybe(
4178 self, "__coerce__", &coerce_str, "(O)", other);
4179 if (r == NULL)
4180 return -1;
4181 if (r == Py_NotImplemented) {
4182 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004183 }
Guido van Rossum55f20992001-10-01 17:18:22 +00004184 else {
4185 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
4186 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004187 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00004188 Py_DECREF(r);
4189 return -1;
4190 }
4191 *a = PyTuple_GET_ITEM(r, 0);
4192 Py_INCREF(*a);
4193 *b = PyTuple_GET_ITEM(r, 1);
4194 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004195 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00004196 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004197 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004198 }
4199 if (other->ob_type->tp_as_number != NULL &&
4200 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
4201 PyObject *r;
4202 r = call_maybe(
4203 other, "__coerce__", &coerce_str, "(O)", self);
4204 if (r == NULL)
4205 return -1;
4206 if (r == Py_NotImplemented) {
4207 Py_DECREF(r);
4208 return 1;
4209 }
4210 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
4211 PyErr_SetString(PyExc_TypeError,
4212 "__coerce__ didn't return a 2-tuple");
4213 Py_DECREF(r);
4214 return -1;
4215 }
4216 *a = PyTuple_GET_ITEM(r, 1);
4217 Py_INCREF(*a);
4218 *b = PyTuple_GET_ITEM(r, 0);
4219 Py_INCREF(*b);
4220 Py_DECREF(r);
4221 return 0;
4222 }
4223 return 1;
4224}
4225
Guido van Rossumdc91b992001-08-08 22:26:22 +00004226SLOT0(slot_nb_int, "__int__")
4227SLOT0(slot_nb_long, "__long__")
4228SLOT0(slot_nb_float, "__float__")
4229SLOT0(slot_nb_oct, "__oct__")
4230SLOT0(slot_nb_hex, "__hex__")
4231SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
4232SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
4233SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
4234SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
4235SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Guido van Rossum6e5680f2002-10-15 01:01:53 +00004236SLOT1(slot_nb_inplace_power, "__ipow__", PyObject *, "O")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004237SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
4238SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
4239SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
4240SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
4241SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
4242SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
4243 "__floordiv__", "__rfloordiv__")
4244SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
4245SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
4246SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004247
4248static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00004249half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004250{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004251 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004252 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004253 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004254
Guido van Rossum60718732001-08-28 17:47:51 +00004255 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004256 if (func == NULL) {
4257 PyErr_Clear();
4258 }
4259 else {
4260 args = Py_BuildValue("(O)", other);
4261 if (args == NULL)
4262 res = NULL;
4263 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004264 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004265 Py_DECREF(args);
4266 }
Raymond Hettingerab5dae32002-06-24 13:08:16 +00004267 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004268 if (res != Py_NotImplemented) {
4269 if (res == NULL)
4270 return -2;
4271 c = PyInt_AsLong(res);
4272 Py_DECREF(res);
4273 if (c == -1 && PyErr_Occurred())
4274 return -2;
4275 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
4276 }
4277 Py_DECREF(res);
4278 }
4279 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004280}
4281
Guido van Rossumab3b0342001-09-18 20:38:53 +00004282/* This slot is published for the benefit of try_3way_compare in object.c */
4283int
4284_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00004285{
4286 int c;
4287
Guido van Rossumab3b0342001-09-18 20:38:53 +00004288 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004289 c = half_compare(self, other);
4290 if (c <= 1)
4291 return c;
4292 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00004293 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004294 c = half_compare(other, self);
4295 if (c < -1)
4296 return -2;
4297 if (c <= 1)
4298 return -c;
4299 }
4300 return (void *)self < (void *)other ? -1 :
4301 (void *)self > (void *)other ? 1 : 0;
4302}
4303
4304static PyObject *
4305slot_tp_repr(PyObject *self)
4306{
4307 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004308 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004309
Guido van Rossum60718732001-08-28 17:47:51 +00004310 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004311 if (func != NULL) {
4312 res = PyEval_CallObject(func, NULL);
4313 Py_DECREF(func);
4314 return res;
4315 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00004316 PyErr_Clear();
4317 return PyString_FromFormat("<%s object at %p>",
4318 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004319}
4320
4321static PyObject *
4322slot_tp_str(PyObject *self)
4323{
4324 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004325 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004326
Guido van Rossum60718732001-08-28 17:47:51 +00004327 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004328 if (func != NULL) {
4329 res = PyEval_CallObject(func, NULL);
4330 Py_DECREF(func);
4331 return res;
4332 }
4333 else {
4334 PyErr_Clear();
4335 return slot_tp_repr(self);
4336 }
4337}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004338
4339static long
4340slot_tp_hash(PyObject *self)
4341{
Tim Peters61ce0a92002-12-06 23:38:02 +00004342 PyObject *func;
Guido van Rossum60718732001-08-28 17:47:51 +00004343 static PyObject *hash_str, *eq_str, *cmp_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004344 long h;
4345
Guido van Rossum60718732001-08-28 17:47:51 +00004346 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004347
4348 if (func != NULL) {
Tim Peters61ce0a92002-12-06 23:38:02 +00004349 PyObject *res = PyEval_CallObject(func, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004350 Py_DECREF(func);
4351 if (res == NULL)
4352 return -1;
4353 h = PyInt_AsLong(res);
Tim Peters61ce0a92002-12-06 23:38:02 +00004354 Py_DECREF(res);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004355 }
4356 else {
4357 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004358 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004359 if (func == NULL) {
4360 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004361 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004362 }
4363 if (func != NULL) {
4364 Py_DECREF(func);
4365 PyErr_SetString(PyExc_TypeError, "unhashable type");
4366 return -1;
4367 }
4368 PyErr_Clear();
4369 h = _Py_HashPointer((void *)self);
4370 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004371 if (h == -1 && !PyErr_Occurred())
4372 h = -2;
4373 return h;
4374}
4375
4376static PyObject *
4377slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
4378{
Guido van Rossum60718732001-08-28 17:47:51 +00004379 static PyObject *call_str;
4380 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004381 PyObject *res;
4382
4383 if (meth == NULL)
4384 return NULL;
4385 res = PyObject_Call(meth, args, kwds);
4386 Py_DECREF(meth);
4387 return res;
4388}
4389
Guido van Rossum14a6f832001-10-17 13:59:09 +00004390/* There are two slot dispatch functions for tp_getattro.
4391
4392 - slot_tp_getattro() is used when __getattribute__ is overridden
4393 but no __getattr__ hook is present;
4394
4395 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
4396
Guido van Rossumc334df52002-04-04 23:44:47 +00004397 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
4398 detects the absence of __getattr__ and then installs the simpler slot if
4399 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00004400
Tim Peters6d6c1a32001-08-02 04:15:00 +00004401static PyObject *
4402slot_tp_getattro(PyObject *self, PyObject *name)
4403{
Guido van Rossum14a6f832001-10-17 13:59:09 +00004404 static PyObject *getattribute_str = NULL;
4405 return call_method(self, "__getattribute__", &getattribute_str,
4406 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004407}
4408
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004409static PyObject *
4410slot_tp_getattr_hook(PyObject *self, PyObject *name)
4411{
4412 PyTypeObject *tp = self->ob_type;
4413 PyObject *getattr, *getattribute, *res;
4414 static PyObject *getattribute_str = NULL;
4415 static PyObject *getattr_str = NULL;
4416
4417 if (getattr_str == NULL) {
4418 getattr_str = PyString_InternFromString("__getattr__");
4419 if (getattr_str == NULL)
4420 return NULL;
4421 }
4422 if (getattribute_str == NULL) {
4423 getattribute_str =
4424 PyString_InternFromString("__getattribute__");
4425 if (getattribute_str == NULL)
4426 return NULL;
4427 }
4428 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004429 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004430 /* No __getattr__ hook: use a simpler dispatcher */
4431 tp->tp_getattro = slot_tp_getattro;
4432 return slot_tp_getattro(self, name);
4433 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004434 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004435 if (getattribute == NULL ||
4436 (getattribute->ob_type == &PyWrapperDescr_Type &&
4437 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
4438 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004439 res = PyObject_GenericGetAttr(self, name);
4440 else
4441 res = PyObject_CallFunction(getattribute, "OO", self, name);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004442 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004443 PyErr_Clear();
4444 res = PyObject_CallFunction(getattr, "OO", self, name);
4445 }
4446 return res;
4447}
4448
Tim Peters6d6c1a32001-08-02 04:15:00 +00004449static int
4450slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
4451{
4452 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004453 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004454
4455 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004456 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004457 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004458 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004459 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004460 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004461 if (res == NULL)
4462 return -1;
4463 Py_DECREF(res);
4464 return 0;
4465}
4466
4467/* Map rich comparison operators to their __xx__ namesakes */
4468static char *name_op[] = {
4469 "__lt__",
4470 "__le__",
4471 "__eq__",
4472 "__ne__",
4473 "__gt__",
4474 "__ge__",
4475};
4476
4477static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00004478half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004479{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004480 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004481 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00004482
Guido van Rossum60718732001-08-28 17:47:51 +00004483 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004484 if (func == NULL) {
4485 PyErr_Clear();
4486 Py_INCREF(Py_NotImplemented);
4487 return Py_NotImplemented;
4488 }
4489 args = Py_BuildValue("(O)", other);
4490 if (args == NULL)
4491 res = NULL;
4492 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004493 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004494 Py_DECREF(args);
4495 }
4496 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004497 return res;
4498}
4499
Guido van Rossumb8f63662001-08-15 23:57:02 +00004500/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
4501static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
4502
4503static PyObject *
4504slot_tp_richcompare(PyObject *self, PyObject *other, int op)
4505{
4506 PyObject *res;
4507
4508 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
4509 res = half_richcompare(self, other, op);
4510 if (res != Py_NotImplemented)
4511 return res;
4512 Py_DECREF(res);
4513 }
4514 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
4515 res = half_richcompare(other, self, swapped_op[op]);
4516 if (res != Py_NotImplemented) {
4517 return res;
4518 }
4519 Py_DECREF(res);
4520 }
4521 Py_INCREF(Py_NotImplemented);
4522 return Py_NotImplemented;
4523}
4524
4525static PyObject *
4526slot_tp_iter(PyObject *self)
4527{
4528 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004529 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004530
Guido van Rossum60718732001-08-28 17:47:51 +00004531 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004532 if (func != NULL) {
Guido van Rossum84b2bed2002-08-16 17:01:09 +00004533 PyObject *args;
4534 args = res = PyTuple_New(0);
4535 if (args != NULL) {
4536 res = PyObject_Call(func, args, NULL);
4537 Py_DECREF(args);
4538 }
4539 Py_DECREF(func);
4540 return res;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004541 }
4542 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004543 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004544 if (func == NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00004545 PyErr_SetString(PyExc_TypeError,
4546 "iteration over non-sequence");
Guido van Rossumb8f63662001-08-15 23:57:02 +00004547 return NULL;
4548 }
4549 Py_DECREF(func);
4550 return PySeqIter_New(self);
4551}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004552
4553static PyObject *
4554slot_tp_iternext(PyObject *self)
4555{
Guido van Rossum2730b132001-08-28 18:22:14 +00004556 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00004557 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004558}
4559
Guido van Rossum1a493502001-08-17 16:47:50 +00004560static PyObject *
4561slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4562{
4563 PyTypeObject *tp = self->ob_type;
4564 PyObject *get;
4565 static PyObject *get_str = NULL;
4566
4567 if (get_str == NULL) {
4568 get_str = PyString_InternFromString("__get__");
4569 if (get_str == NULL)
4570 return NULL;
4571 }
4572 get = _PyType_Lookup(tp, get_str);
4573 if (get == NULL) {
4574 /* Avoid further slowdowns */
4575 if (tp->tp_descr_get == slot_tp_descr_get)
4576 tp->tp_descr_get = NULL;
4577 Py_INCREF(self);
4578 return self;
4579 }
Guido van Rossum2c252392001-08-24 10:13:31 +00004580 if (obj == NULL)
4581 obj = Py_None;
4582 if (type == NULL)
4583 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00004584 return PyObject_CallFunction(get, "OOO", self, obj, type);
4585}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004586
4587static int
4588slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
4589{
Guido van Rossum2c252392001-08-24 10:13:31 +00004590 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004591 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00004592
4593 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00004594 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004595 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00004596 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004597 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004598 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004599 if (res == NULL)
4600 return -1;
4601 Py_DECREF(res);
4602 return 0;
4603}
4604
4605static int
4606slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
4607{
Guido van Rossum60718732001-08-28 17:47:51 +00004608 static PyObject *init_str;
4609 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004610 PyObject *res;
4611
4612 if (meth == NULL)
4613 return -1;
4614 res = PyObject_Call(meth, args, kwds);
4615 Py_DECREF(meth);
4616 if (res == NULL)
4617 return -1;
4618 Py_DECREF(res);
4619 return 0;
4620}
4621
4622static PyObject *
4623slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4624{
Guido van Rossum7bed2132002-08-08 21:57:53 +00004625 static PyObject *new_str;
4626 PyObject *func;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004627 PyObject *newargs, *x;
4628 int i, n;
4629
Guido van Rossum7bed2132002-08-08 21:57:53 +00004630 if (new_str == NULL) {
4631 new_str = PyString_InternFromString("__new__");
4632 if (new_str == NULL)
4633 return NULL;
4634 }
4635 func = PyObject_GetAttr((PyObject *)type, new_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004636 if (func == NULL)
4637 return NULL;
4638 assert(PyTuple_Check(args));
4639 n = PyTuple_GET_SIZE(args);
4640 newargs = PyTuple_New(n+1);
4641 if (newargs == NULL)
4642 return NULL;
4643 Py_INCREF(type);
4644 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
4645 for (i = 0; i < n; i++) {
4646 x = PyTuple_GET_ITEM(args, i);
4647 Py_INCREF(x);
4648 PyTuple_SET_ITEM(newargs, i+1, x);
4649 }
4650 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00004651 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004652 Py_DECREF(func);
4653 return x;
4654}
4655
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004656static void
4657slot_tp_del(PyObject *self)
4658{
4659 static PyObject *del_str = NULL;
4660 PyObject *del, *res;
4661 PyObject *error_type, *error_value, *error_traceback;
4662
4663 /* Temporarily resurrect the object. */
4664 assert(self->ob_refcnt == 0);
4665 self->ob_refcnt = 1;
4666
4667 /* Save the current exception, if any. */
4668 PyErr_Fetch(&error_type, &error_value, &error_traceback);
4669
4670 /* Execute __del__ method, if any. */
4671 del = lookup_maybe(self, "__del__", &del_str);
4672 if (del != NULL) {
4673 res = PyEval_CallObject(del, NULL);
4674 if (res == NULL)
4675 PyErr_WriteUnraisable(del);
4676 else
4677 Py_DECREF(res);
4678 Py_DECREF(del);
4679 }
4680
4681 /* Restore the saved exception. */
4682 PyErr_Restore(error_type, error_value, error_traceback);
4683
4684 /* Undo the temporary resurrection; can't use DECREF here, it would
4685 * cause a recursive call.
4686 */
4687 assert(self->ob_refcnt > 0);
4688 if (--self->ob_refcnt == 0)
4689 return; /* this is the normal path out */
4690
4691 /* __del__ resurrected it! Make it look like the original Py_DECREF
4692 * never happened.
4693 */
4694 {
4695 int refcnt = self->ob_refcnt;
4696 _Py_NewReference(self);
4697 self->ob_refcnt = refcnt;
4698 }
4699 assert(!PyType_IS_GC(self->ob_type) ||
4700 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
4701 /* If Py_REF_DEBUG, the original decref dropped _Py_RefTotal, but
4702 * _Py_NewReference bumped it again, so that's a wash.
4703 * If Py_TRACE_REFS, _Py_NewReference re-added self to the object
4704 * chain, so no more to do there either.
4705 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
4706 * _Py_NewReference bumped tp_allocs: both of those need to be
4707 * undone.
4708 */
4709#ifdef COUNT_ALLOCS
4710 --self->ob_type->tp_frees;
4711 --self->ob_type->tp_allocs;
4712#endif
4713}
4714
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004715
4716/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
Tim Petersbf9b2442003-03-23 05:35:36 +00004717 functions. The offsets here are relative to the 'PyHeapTypeObject'
Guido van Rossume5c691a2003-03-07 15:13:17 +00004718 structure, which incorporates the additional structures used for numbers,
4719 sequences and mappings.
4720 Note that multiple names may map to the same slot (e.g. __eq__,
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004721 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00004722 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
4723 terminated with an all-zero entry. (This table is further initialized and
4724 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004725
Guido van Rossum6d204072001-10-21 00:44:31 +00004726typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004727
4728#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00004729#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004730#undef ETSLOT
4731#undef SQSLOT
4732#undef MPSLOT
4733#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00004734#undef UNSLOT
4735#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004736#undef BINSLOT
4737#undef RBINSLOT
4738
Guido van Rossum6d204072001-10-21 00:44:31 +00004739#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004740 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
4741 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00004742#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
4743 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004744 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00004745#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Guido van Rossume5c691a2003-03-07 15:13:17 +00004746 {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004747 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00004748#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4749 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
4750#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4751 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
4752#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4753 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
4754#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4755 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
4756 "x." NAME "() <==> " DOC)
4757#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4758 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
4759 "x." NAME "(y) <==> x" DOC "y")
4760#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
4761 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
4762 "x." NAME "(y) <==> x" DOC "y")
4763#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
4764 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
4765 "x." NAME "(y) <==> y" DOC "x")
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004766
4767static slotdef slotdefs[] = {
Guido van Rossum6d204072001-10-21 00:44:31 +00004768 SQSLOT("__len__", sq_length, slot_sq_length, wrap_inquiry,
4769 "x.__len__() <==> len(x)"),
4770 SQSLOT("__add__", sq_concat, slot_sq_concat, wrap_binaryfunc,
4771 "x.__add__(y) <==> x+y"),
4772 SQSLOT("__mul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
4773 "x.__mul__(n) <==> x*n"),
4774 SQSLOT("__rmul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
4775 "x.__rmul__(n) <==> n*x"),
4776 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
4777 "x.__getitem__(y) <==> x[y]"),
4778 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_intintargfunc,
4779 "x.__getslice__(i, j) <==> x[i:j]"),
4780 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
4781 "x.__setitem__(i, y) <==> x[i]=y"),
4782 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
4783 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004784 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Guido van Rossum6d204072001-10-21 00:44:31 +00004785 wrap_intintobjargproc,
4786 "x.__setslice__(i, j, y) <==> x[i:j]=y"),
4787 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
4788 "x.__delslice__(i, j) <==> del x[i:j]"),
4789 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
4790 "x.__contains__(y) <==> y in x"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004791 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat,
Guido van Rossum6d204072001-10-21 00:44:31 +00004792 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004793 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat,
Guido van Rossum6d204072001-10-21 00:44:31 +00004794 wrap_intargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004795
Guido van Rossum6d204072001-10-21 00:44:31 +00004796 MPSLOT("__len__", mp_length, slot_mp_length, wrap_inquiry,
4797 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00004798 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004799 wrap_binaryfunc,
4800 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004801 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004802 wrap_objobjargproc,
4803 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004804 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004805 wrap_delitem,
4806 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004807
Guido van Rossum6d204072001-10-21 00:44:31 +00004808 BINSLOT("__add__", nb_add, slot_nb_add,
4809 "+"),
4810 RBINSLOT("__radd__", nb_add, slot_nb_add,
4811 "+"),
4812 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
4813 "-"),
4814 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
4815 "-"),
4816 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
4817 "*"),
4818 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
4819 "*"),
4820 BINSLOT("__div__", nb_divide, slot_nb_divide,
4821 "/"),
4822 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
4823 "/"),
4824 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
4825 "%"),
4826 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
4827 "%"),
4828 BINSLOT("__divmod__", nb_divmod, slot_nb_divmod,
4829 "divmod(x, y)"),
4830 RBINSLOT("__rdivmod__", nb_divmod, slot_nb_divmod,
4831 "divmod(y, x)"),
4832 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
4833 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
4834 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
4835 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
4836 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
4837 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
4838 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
4839 "abs(x)"),
Guido van Rossumdfce3bf2002-03-10 14:11:16 +00004840 UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquiry,
Guido van Rossum6d204072001-10-21 00:44:31 +00004841 "x != 0"),
4842 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
4843 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
4844 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
4845 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
4846 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
4847 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
4848 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
4849 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
4850 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
4851 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
4852 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
4853 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
4854 "x.__coerce__(y) <==> coerce(x, y)"),
4855 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
4856 "int(x)"),
4857 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
4858 "long(x)"),
4859 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
4860 "float(x)"),
4861 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
4862 "oct(x)"),
4863 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
4864 "hex(x)"),
4865 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
4866 wrap_binaryfunc, "+"),
4867 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
4868 wrap_binaryfunc, "-"),
4869 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
4870 wrap_binaryfunc, "*"),
4871 IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
4872 wrap_binaryfunc, "/"),
4873 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
4874 wrap_binaryfunc, "%"),
4875 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
Guido van Rossum6e5680f2002-10-15 01:01:53 +00004876 wrap_binaryfunc, "**"),
Guido van Rossum6d204072001-10-21 00:44:31 +00004877 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
4878 wrap_binaryfunc, "<<"),
4879 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
4880 wrap_binaryfunc, ">>"),
4881 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
4882 wrap_binaryfunc, "&"),
4883 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
4884 wrap_binaryfunc, "^"),
4885 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
4886 wrap_binaryfunc, "|"),
4887 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
4888 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
4889 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
4890 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
4891 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
4892 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
4893 IBSLOT("__itruediv__", nb_inplace_true_divide,
4894 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004895
Guido van Rossum6d204072001-10-21 00:44:31 +00004896 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
4897 "x.__str__() <==> str(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00004898 TPSLOT("__str__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00004899 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
4900 "x.__repr__() <==> repr(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00004901 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00004902 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
4903 "x.__cmp__(y) <==> cmp(x,y)"),
4904 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
4905 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00004906 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
4907 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004908 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00004909 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
4910 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
4911 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
4912 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
4913 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
4914 "x.__setattr__('name', value) <==> x.name = value"),
4915 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
4916 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
4917 "x.__delattr__('name') <==> del x.name"),
4918 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
4919 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
4920 "x.__lt__(y) <==> x<y"),
4921 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
4922 "x.__le__(y) <==> x<=y"),
4923 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
4924 "x.__eq__(y) <==> x==y"),
4925 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
4926 "x.__ne__(y) <==> x!=y"),
4927 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
4928 "x.__gt__(y) <==> x>y"),
4929 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
4930 "x.__ge__(y) <==> x>=y"),
4931 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
4932 "x.__iter__() <==> iter(x)"),
4933 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
4934 "x.next() -> the next value, or raise StopIteration"),
4935 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
4936 "descr.__get__(obj[, type]) -> value"),
4937 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
4938 "descr.__set__(obj, value)"),
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004939 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
4940 wrap_descr_delete, "descr.__delete__(obj)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00004941 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00004942 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00004943 "see x.__class__.__doc__ for signature",
4944 PyWrapperFlag_KEYWORDS),
4945 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004946 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004947 {NULL}
4948};
4949
Guido van Rossumc334df52002-04-04 23:44:47 +00004950/* Given a type pointer and an offset gotten from a slotdef entry, return a
4951 pointer to the actual slot. This is not quite the same as simply adding
4952 the offset to the type pointer, since it takes care to indirect through the
4953 proper indirection pointer (as_buffer, etc.); it returns NULL if the
4954 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004955static void **
4956slotptr(PyTypeObject *type, int offset)
4957{
4958 char *ptr;
4959
Guido van Rossume5c691a2003-03-07 15:13:17 +00004960 /* Note: this depends on the order of the members of PyHeapTypeObject! */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004961 assert(offset >= 0);
Guido van Rossume5c691a2003-03-07 15:13:17 +00004962 assert(offset < offsetof(PyHeapTypeObject, as_buffer));
4963 if (offset >= offsetof(PyHeapTypeObject, as_sequence)) {
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004964 ptr = (void *)type->tp_as_sequence;
Guido van Rossume5c691a2003-03-07 15:13:17 +00004965 offset -= offsetof(PyHeapTypeObject, as_sequence);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004966 }
Guido van Rossume5c691a2003-03-07 15:13:17 +00004967 else if (offset >= offsetof(PyHeapTypeObject, as_mapping)) {
Guido van Rossum09638c12002-06-13 19:17:46 +00004968 ptr = (void *)type->tp_as_mapping;
Guido van Rossume5c691a2003-03-07 15:13:17 +00004969 offset -= offsetof(PyHeapTypeObject, as_mapping);
Guido van Rossum09638c12002-06-13 19:17:46 +00004970 }
Guido van Rossume5c691a2003-03-07 15:13:17 +00004971 else if (offset >= offsetof(PyHeapTypeObject, as_number)) {
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004972 ptr = (void *)type->tp_as_number;
Guido van Rossume5c691a2003-03-07 15:13:17 +00004973 offset -= offsetof(PyHeapTypeObject, as_number);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004974 }
4975 else {
4976 ptr = (void *)type;
4977 }
4978 if (ptr != NULL)
4979 ptr += offset;
4980 return (void **)ptr;
4981}
Guido van Rossumf040ede2001-08-07 16:40:56 +00004982
Guido van Rossumc334df52002-04-04 23:44:47 +00004983/* Length of array of slotdef pointers used to store slots with the
4984 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
4985 the same __name__, for any __name__. Since that's a static property, it is
4986 appropriate to declare fixed-size arrays for this. */
4987#define MAX_EQUIV 10
4988
4989/* Return a slot pointer for a given name, but ONLY if the attribute has
4990 exactly one slot function. The name must be an interned string. */
4991static void **
4992resolve_slotdups(PyTypeObject *type, PyObject *name)
4993{
4994 /* XXX Maybe this could be optimized more -- but is it worth it? */
4995
4996 /* pname and ptrs act as a little cache */
4997 static PyObject *pname;
4998 static slotdef *ptrs[MAX_EQUIV];
4999 slotdef *p, **pp;
5000 void **res, **ptr;
5001
5002 if (pname != name) {
5003 /* Collect all slotdefs that match name into ptrs. */
5004 pname = name;
5005 pp = ptrs;
5006 for (p = slotdefs; p->name_strobj; p++) {
5007 if (p->name_strobj == name)
5008 *pp++ = p;
5009 }
5010 *pp = NULL;
5011 }
5012
5013 /* Look in all matching slots of the type; if exactly one of these has
5014 a filled-in slot, return its value. Otherwise return NULL. */
5015 res = NULL;
5016 for (pp = ptrs; *pp; pp++) {
5017 ptr = slotptr(type, (*pp)->offset);
5018 if (ptr == NULL || *ptr == NULL)
5019 continue;
5020 if (res != NULL)
5021 return NULL;
5022 res = ptr;
5023 }
5024 return res;
5025}
5026
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005027/* Common code for update_slots_callback() and fixup_slot_dispatchers(). This
Guido van Rossumc334df52002-04-04 23:44:47 +00005028 does some incredibly complex thinking and then sticks something into the
5029 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
5030 interests, and then stores a generic wrapper or a specific function into
5031 the slot.) Return a pointer to the next slotdef with a different offset,
5032 because that's convenient for fixup_slot_dispatchers(). */
5033static slotdef *
5034update_one_slot(PyTypeObject *type, slotdef *p)
5035{
5036 PyObject *descr;
5037 PyWrapperDescrObject *d;
5038 void *generic = NULL, *specific = NULL;
5039 int use_generic = 0;
5040 int offset = p->offset;
5041 void **ptr = slotptr(type, offset);
5042
5043 if (ptr == NULL) {
5044 do {
5045 ++p;
5046 } while (p->offset == offset);
5047 return p;
5048 }
5049 do {
5050 descr = _PyType_Lookup(type, p->name_strobj);
5051 if (descr == NULL)
5052 continue;
5053 if (descr->ob_type == &PyWrapperDescr_Type) {
5054 void **tptr = resolve_slotdups(type, p->name_strobj);
5055 if (tptr == NULL || tptr == ptr)
5056 generic = p->function;
5057 d = (PyWrapperDescrObject *)descr;
5058 if (d->d_base->wrapper == p->wrapper &&
5059 PyType_IsSubtype(type, d->d_type))
5060 {
5061 if (specific == NULL ||
5062 specific == d->d_wrapped)
5063 specific = d->d_wrapped;
5064 else
5065 use_generic = 1;
5066 }
5067 }
Guido van Rossum721f62e2002-08-09 02:14:34 +00005068 else if (descr->ob_type == &PyCFunction_Type &&
5069 PyCFunction_GET_FUNCTION(descr) ==
5070 (PyCFunction)tp_new_wrapper &&
5071 strcmp(p->name, "__new__") == 0)
5072 {
5073 /* The __new__ wrapper is not a wrapper descriptor,
5074 so must be special-cased differently.
5075 If we don't do this, creating an instance will
5076 always use slot_tp_new which will look up
5077 __new__ in the MRO which will call tp_new_wrapper
5078 which will look through the base classes looking
5079 for a static base and call its tp_new (usually
5080 PyType_GenericNew), after performing various
5081 sanity checks and constructing a new argument
5082 list. Cut all that nonsense short -- this speeds
5083 up instance creation tremendously. */
5084 specific = type->tp_new;
5085 /* XXX I'm not 100% sure that there isn't a hole
5086 in this reasoning that requires additional
5087 sanity checks. I'll buy the first person to
5088 point out a bug in this reasoning a beer. */
5089 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005090 else {
5091 use_generic = 1;
5092 generic = p->function;
5093 }
5094 } while ((++p)->offset == offset);
5095 if (specific && !use_generic)
5096 *ptr = specific;
5097 else
5098 *ptr = generic;
5099 return p;
5100}
5101
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005102/* In the type, update the slots whose slotdefs are gathered in the pp array.
5103 This is a callback for update_subclasses(). */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005104static int
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005105update_slots_callback(PyTypeObject *type, void *data)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005106{
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005107 slotdef **pp = (slotdef **)data;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005108
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005109 for (; *pp; pp++)
Guido van Rossumc334df52002-04-04 23:44:47 +00005110 update_one_slot(type, *pp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005111 return 0;
5112}
5113
Guido van Rossumc334df52002-04-04 23:44:47 +00005114/* Comparison function for qsort() to compare slotdefs by their offset, and
5115 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005116static int
5117slotdef_cmp(const void *aa, const void *bb)
5118{
5119 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
5120 int c = a->offset - b->offset;
5121 if (c != 0)
5122 return c;
5123 else
5124 return a - b;
5125}
5126
Guido van Rossumc334df52002-04-04 23:44:47 +00005127/* Initialize the slotdefs table by adding interned string objects for the
5128 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005129static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005130init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005131{
5132 slotdef *p;
5133 static int initialized = 0;
5134
5135 if (initialized)
5136 return;
5137 for (p = slotdefs; p->name; p++) {
5138 p->name_strobj = PyString_InternFromString(p->name);
5139 if (!p->name_strobj)
Guido van Rossumc334df52002-04-04 23:44:47 +00005140 Py_FatalError("Out of memory interning slotdef names");
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005141 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005142 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
5143 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005144 initialized = 1;
5145}
5146
Guido van Rossumc334df52002-04-04 23:44:47 +00005147/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005148static int
5149update_slot(PyTypeObject *type, PyObject *name)
5150{
Guido van Rossumc334df52002-04-04 23:44:47 +00005151 slotdef *ptrs[MAX_EQUIV];
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005152 slotdef *p;
5153 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005154 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005155
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005156 init_slotdefs();
5157 pp = ptrs;
5158 for (p = slotdefs; p->name; p++) {
5159 /* XXX assume name is interned! */
5160 if (p->name_strobj == name)
5161 *pp++ = p;
5162 }
5163 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005164 for (pp = ptrs; *pp; pp++) {
5165 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005166 offset = p->offset;
5167 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005168 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005169 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005170 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005171 if (ptrs[0] == NULL)
5172 return 0; /* Not an attribute that affects any slots */
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005173 return update_subclasses(type, name,
5174 update_slots_callback, (void *)ptrs);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005175}
5176
Guido van Rossumc334df52002-04-04 23:44:47 +00005177/* Store the proper functions in the slot dispatches at class (type)
5178 definition time, based upon which operations the class overrides in its
5179 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00005180static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005181fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005182{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005183 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005184
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005185 init_slotdefs();
Guido van Rossumc334df52002-04-04 23:44:47 +00005186 for (p = slotdefs; p->name; )
5187 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005188}
Guido van Rossum705f0f52001-08-24 16:47:00 +00005189
Michael W. Hudson98bbc492002-11-26 14:47:27 +00005190static void
5191update_all_slots(PyTypeObject* type)
5192{
5193 slotdef *p;
5194
5195 init_slotdefs();
5196 for (p = slotdefs; p->name; p++) {
5197 /* update_slot returns int but can't actually fail */
5198 update_slot(type, p->name_strobj);
5199 }
5200}
5201
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005202/* recurse_down_subclasses() and update_subclasses() are mutually
5203 recursive functions to call a callback for all subclasses,
5204 but refraining from recursing into subclasses that define 'name'. */
5205
5206static int
5207update_subclasses(PyTypeObject *type, PyObject *name,
5208 update_callback callback, void *data)
5209{
5210 if (callback(type, data) < 0)
5211 return -1;
5212 return recurse_down_subclasses(type, name, callback, data);
5213}
5214
5215static int
5216recurse_down_subclasses(PyTypeObject *type, PyObject *name,
5217 update_callback callback, void *data)
5218{
5219 PyTypeObject *subclass;
5220 PyObject *ref, *subclasses, *dict;
5221 int i, n;
5222
5223 subclasses = type->tp_subclasses;
5224 if (subclasses == NULL)
5225 return 0;
5226 assert(PyList_Check(subclasses));
5227 n = PyList_GET_SIZE(subclasses);
5228 for (i = 0; i < n; i++) {
5229 ref = PyList_GET_ITEM(subclasses, i);
5230 assert(PyWeakref_CheckRef(ref));
5231 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
5232 assert(subclass != NULL);
5233 if ((PyObject *)subclass == Py_None)
5234 continue;
5235 assert(PyType_Check(subclass));
5236 /* Avoid recursing down into unaffected classes */
5237 dict = subclass->tp_dict;
5238 if (dict != NULL && PyDict_Check(dict) &&
5239 PyDict_GetItem(dict, name) != NULL)
5240 continue;
5241 if (update_subclasses(subclass, name, callback, data) < 0)
5242 return -1;
5243 }
5244 return 0;
5245}
5246
Guido van Rossum6d204072001-10-21 00:44:31 +00005247/* This function is called by PyType_Ready() to populate the type's
5248 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00005249 function slot (like tp_repr) that's defined in the type, one or more
5250 corresponding descriptors are added in the type's tp_dict dictionary
5251 under the appropriate name (like __repr__). Some function slots
5252 cause more than one descriptor to be added (for example, the nb_add
5253 slot adds both __add__ and __radd__ descriptors) and some function
5254 slots compete for the same descriptor (for example both sq_item and
5255 mp_subscript generate a __getitem__ descriptor).
5256
5257 In the latter case, the first slotdef entry encoutered wins. Since
Tim Petersbf9b2442003-03-23 05:35:36 +00005258 slotdef entries are sorted by the offset of the slot in the
Guido van Rossume5c691a2003-03-07 15:13:17 +00005259 PyHeapTypeObject, this gives us some control over disambiguating
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005260 between competing slots: the members of PyHeapTypeObject are listed
5261 from most general to least general, so the most general slot is
5262 preferred. In particular, because as_mapping comes before as_sequence,
5263 for a type that defines both mp_subscript and sq_item, mp_subscript
5264 wins.
Guido van Rossum09638c12002-06-13 19:17:46 +00005265
5266 This only adds new descriptors and doesn't overwrite entries in
5267 tp_dict that were previously defined. The descriptors contain a
5268 reference to the C function they must call, so that it's safe if they
5269 are copied into a subtype's __dict__ and the subtype has a different
5270 C function in its slot -- calling the method defined by the
5271 descriptor will call the C function that was used to create it,
5272 rather than the C function present in the slot when it is called.
5273 (This is important because a subtype may have a C function in the
5274 slot that calls the method from the dictionary, and we want to avoid
5275 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00005276
5277static int
5278add_operators(PyTypeObject *type)
5279{
5280 PyObject *dict = type->tp_dict;
5281 slotdef *p;
5282 PyObject *descr;
5283 void **ptr;
5284
5285 init_slotdefs();
5286 for (p = slotdefs; p->name; p++) {
5287 if (p->wrapper == NULL)
5288 continue;
5289 ptr = slotptr(type, p->offset);
5290 if (!ptr || !*ptr)
5291 continue;
5292 if (PyDict_GetItem(dict, p->name_strobj))
5293 continue;
5294 descr = PyDescr_NewWrapper(type, p, *ptr);
5295 if (descr == NULL)
5296 return -1;
5297 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
5298 return -1;
5299 Py_DECREF(descr);
5300 }
5301 if (type->tp_new != NULL) {
5302 if (add_tp_new_wrapper(type) < 0)
5303 return -1;
5304 }
5305 return 0;
5306}
5307
Guido van Rossum705f0f52001-08-24 16:47:00 +00005308
5309/* Cooperative 'super' */
5310
5311typedef struct {
5312 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00005313 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005314 PyObject *obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005315 PyTypeObject *obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005316} superobject;
5317
Guido van Rossum6f799372001-09-20 20:46:19 +00005318static PyMemberDef super_members[] = {
5319 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
5320 "the class invoking super()"},
5321 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
5322 "the instance invoking super(); may be None"},
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005323 {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
5324 "the type of the the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005325 {0}
5326};
5327
Guido van Rossum705f0f52001-08-24 16:47:00 +00005328static void
5329super_dealloc(PyObject *self)
5330{
5331 superobject *su = (superobject *)self;
5332
Guido van Rossum048eb752001-10-02 21:24:57 +00005333 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005334 Py_XDECREF(su->obj);
5335 Py_XDECREF(su->type);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005336 Py_XDECREF(su->obj_type);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005337 self->ob_type->tp_free(self);
5338}
5339
5340static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005341super_repr(PyObject *self)
5342{
5343 superobject *su = (superobject *)self;
5344
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005345 if (su->obj_type)
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005346 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005347 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005348 su->type ? su->type->tp_name : "NULL",
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005349 su->obj_type->tp_name);
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005350 else
5351 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005352 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005353 su->type ? su->type->tp_name : "NULL");
5354}
5355
5356static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00005357super_getattro(PyObject *self, PyObject *name)
5358{
5359 superobject *su = (superobject *)self;
5360
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005361 if (su->obj_type != NULL) {
Tim Petersa91e9642001-11-14 23:32:33 +00005362 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005363 PyTypeObject *starttype;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005364 descrgetfunc f;
5365 int i, n;
5366
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005367 starttype = su->obj_type;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005368 mro = starttype->tp_mro;
5369
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005370 if (mro == NULL)
5371 n = 0;
5372 else {
5373 assert(PyTuple_Check(mro));
5374 n = PyTuple_GET_SIZE(mro);
5375 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005376 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00005377 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00005378 break;
5379 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005380 i++;
5381 res = NULL;
5382 for (; i < n; i++) {
5383 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00005384 if (PyType_Check(tmp))
5385 dict = ((PyTypeObject *)tmp)->tp_dict;
5386 else if (PyClass_Check(tmp))
5387 dict = ((PyClassObject *)tmp)->cl_dict;
5388 else
5389 continue;
5390 res = PyDict_GetItem(dict, name);
Guido van Rossum2fd02eb2003-04-14 21:20:26 +00005391 /* Skip data descriptors because when obj_type is a
5392 metaclass, we don't want to return its __class__
5393 descriptor. See supers() in test_descr.py. */
5394 if (res != NULL && !PyDescr_IsData(res)) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00005395 Py_INCREF(res);
5396 f = res->ob_type->tp_descr_get;
5397 if (f != NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00005398 tmp = f(res, su->obj,
5399 (PyObject *)starttype);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005400 Py_DECREF(res);
5401 res = tmp;
5402 }
5403 return res;
5404 }
5405 }
5406 }
5407 return PyObject_GenericGetAttr(self, name);
5408}
5409
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005410static PyTypeObject *
Guido van Rossum5b443c62001-12-03 15:38:28 +00005411supercheck(PyTypeObject *type, PyObject *obj)
5412{
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005413 /* Check that a super() call makes sense. Return a type object.
5414
5415 obj can be a new-style class, or an instance of one:
5416
5417 - If it is a class, it must be a subclass of 'type'. This case is
5418 used for class methods; the return value is obj.
5419
5420 - If it is an instance, it must be an instance of 'type'. This is
5421 the normal case; the return value is obj.__class__.
5422
5423 But... when obj is an instance, we want to allow for the case where
5424 obj->ob_type is not a subclass of type, but obj.__class__ is!
5425 This will allow using super() with a proxy for obj.
5426 */
5427
Guido van Rossum8e80a722003-02-18 19:22:22 +00005428 /* Check for first bullet above (special case) */
5429 if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
5430 Py_INCREF(obj);
5431 return (PyTypeObject *)obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005432 }
Guido van Rossum8e80a722003-02-18 19:22:22 +00005433
5434 /* Normal case */
5435 if (PyType_IsSubtype(obj->ob_type, type)) {
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005436 Py_INCREF(obj->ob_type);
5437 return obj->ob_type;
5438 }
5439 else {
5440 /* Try the slow way */
5441 static PyObject *class_str = NULL;
5442 PyObject *class_attr;
5443
5444 if (class_str == NULL) {
5445 class_str = PyString_FromString("__class__");
5446 if (class_str == NULL)
5447 return NULL;
5448 }
5449
5450 class_attr = PyObject_GetAttr(obj, class_str);
5451
5452 if (class_attr != NULL &&
5453 PyType_Check(class_attr) &&
5454 (PyTypeObject *)class_attr != obj->ob_type)
5455 {
5456 int ok = PyType_IsSubtype(
5457 (PyTypeObject *)class_attr, type);
5458 if (ok)
5459 return (PyTypeObject *)class_attr;
5460 }
5461
5462 if (class_attr == NULL)
5463 PyErr_Clear();
5464 else
5465 Py_DECREF(class_attr);
5466 }
5467
Tim Peters97e5ff52003-02-18 19:32:50 +00005468 PyErr_SetString(PyExc_TypeError,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005469 "super(type, obj): "
5470 "obj must be an instance or subtype of type");
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005471 return NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005472}
5473
Guido van Rossum705f0f52001-08-24 16:47:00 +00005474static PyObject *
5475super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5476{
5477 superobject *su = (superobject *)self;
5478 superobject *new;
5479
5480 if (obj == NULL || obj == Py_None || su->obj != NULL) {
5481 /* Not binding to an object, or already bound */
5482 Py_INCREF(self);
5483 return self;
5484 }
Guido van Rossum5b443c62001-12-03 15:38:28 +00005485 if (su->ob_type != &PySuper_Type)
5486 /* If su is an instance of a subclass of super,
5487 call its type */
5488 return PyObject_CallFunction((PyObject *)su->ob_type,
5489 "OO", su->type, obj);
5490 else {
5491 /* Inline the common case */
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005492 PyTypeObject *obj_type = supercheck(su->type, obj);
5493 if (obj_type == NULL)
Guido van Rossum5b443c62001-12-03 15:38:28 +00005494 return NULL;
5495 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
5496 NULL, NULL);
5497 if (new == NULL)
5498 return NULL;
5499 Py_INCREF(su->type);
5500 Py_INCREF(obj);
5501 new->type = su->type;
5502 new->obj = obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005503 new->obj_type = obj_type;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005504 return (PyObject *)new;
5505 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005506}
5507
5508static int
5509super_init(PyObject *self, PyObject *args, PyObject *kwds)
5510{
5511 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00005512 PyTypeObject *type;
5513 PyObject *obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005514 PyTypeObject *obj_type = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005515
5516 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
5517 return -1;
5518 if (obj == Py_None)
5519 obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005520 if (obj != NULL) {
5521 obj_type = supercheck(type, obj);
5522 if (obj_type == NULL)
5523 return -1;
5524 Py_INCREF(obj);
5525 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005526 Py_INCREF(type);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005527 su->type = type;
5528 su->obj = obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005529 su->obj_type = obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005530 return 0;
5531}
5532
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005533PyDoc_STRVAR(super_doc,
Guido van Rossum705f0f52001-08-24 16:47:00 +00005534"super(type) -> unbound super object\n"
5535"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00005536"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00005537"Typical use to call a cooperative superclass method:\n"
5538"class C(B):\n"
5539" def meth(self, arg):\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005540" super(C, self).meth(arg)");
Guido van Rossum705f0f52001-08-24 16:47:00 +00005541
Guido van Rossum048eb752001-10-02 21:24:57 +00005542static int
5543super_traverse(PyObject *self, visitproc visit, void *arg)
5544{
5545 superobject *su = (superobject *)self;
5546 int err;
5547
5548#define VISIT(SLOT) \
5549 if (SLOT) { \
5550 err = visit((PyObject *)(SLOT), arg); \
5551 if (err) \
5552 return err; \
5553 }
5554
5555 VISIT(su->obj);
5556 VISIT(su->type);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005557 VISIT(su->obj_type);
Guido van Rossum048eb752001-10-02 21:24:57 +00005558
5559#undef VISIT
5560
5561 return 0;
5562}
5563
Guido van Rossum705f0f52001-08-24 16:47:00 +00005564PyTypeObject PySuper_Type = {
5565 PyObject_HEAD_INIT(&PyType_Type)
5566 0, /* ob_size */
5567 "super", /* tp_name */
5568 sizeof(superobject), /* tp_basicsize */
5569 0, /* tp_itemsize */
5570 /* methods */
5571 super_dealloc, /* tp_dealloc */
5572 0, /* tp_print */
5573 0, /* tp_getattr */
5574 0, /* tp_setattr */
5575 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005576 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005577 0, /* tp_as_number */
5578 0, /* tp_as_sequence */
5579 0, /* tp_as_mapping */
5580 0, /* tp_hash */
5581 0, /* tp_call */
5582 0, /* tp_str */
5583 super_getattro, /* tp_getattro */
5584 0, /* tp_setattro */
5585 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00005586 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
5587 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005588 super_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00005589 super_traverse, /* tp_traverse */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005590 0, /* tp_clear */
5591 0, /* tp_richcompare */
5592 0, /* tp_weaklistoffset */
5593 0, /* tp_iter */
5594 0, /* tp_iternext */
5595 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005596 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005597 0, /* tp_getset */
5598 0, /* tp_base */
5599 0, /* tp_dict */
5600 super_descr_get, /* tp_descr_get */
5601 0, /* tp_descr_set */
5602 0, /* tp_dictoffset */
5603 super_init, /* tp_init */
5604 PyType_GenericAlloc, /* tp_alloc */
5605 PyType_GenericNew, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00005606 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005607};