blob: fea6e15a672800666622a313a0fc5e4b3e0a21fd [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);
2622 Py_XDECREF(state);
2623 Py_XDECREF(names);
2624 Py_XDECREF(listitems);
2625 Py_XDECREF(dictitems);
2626 Py_XDECREF(copy_reg);
2627 Py_XDECREF(newobj);
2628 return res;
2629}
2630
2631static PyObject *
2632object_reduce_ex(PyObject *self, PyObject *args)
2633{
2634 /* Call copy_reg._reduce_ex(self, proto) */
2635 PyObject *reduce, *copy_reg, *res;
2636 int proto = 0;
2637
2638 if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
2639 return NULL;
2640
2641 reduce = PyObject_GetAttrString(self, "__reduce__");
2642 if (reduce == NULL)
2643 PyErr_Clear();
2644 else {
2645 PyObject *cls, *clsreduce, *objreduce;
2646 int override;
2647 cls = PyObject_GetAttrString(self, "__class__");
2648 if (cls == NULL) {
2649 Py_DECREF(reduce);
2650 return NULL;
2651 }
2652 clsreduce = PyObject_GetAttrString(cls, "__reduce__");
2653 Py_DECREF(cls);
2654 if (clsreduce == NULL) {
2655 Py_DECREF(reduce);
2656 return NULL;
2657 }
2658 objreduce = PyDict_GetItemString(PyBaseObject_Type.tp_dict,
2659 "__reduce__");
2660 override = (clsreduce != objreduce);
2661 Py_DECREF(clsreduce);
2662 if (override) {
2663 res = PyObject_CallObject(reduce, NULL);
2664 Py_DECREF(reduce);
2665 return res;
2666 }
2667 else
2668 Py_DECREF(reduce);
2669 }
2670
2671 if (proto >= 2)
2672 return reduce_2(self);
2673
2674 copy_reg = import_copy_reg();
Guido van Rossum3926a632001-09-25 16:25:58 +00002675 if (!copy_reg)
2676 return NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00002677
Guido van Rossumc53f0092003-02-18 22:05:12 +00002678 res = PyEval_CallMethod(copy_reg, "_reduce_ex", "(Oi)", self, proto);
Guido van Rossum3926a632001-09-25 16:25:58 +00002679 Py_DECREF(copy_reg);
Guido van Rossum036f9992003-02-21 22:02:54 +00002680
Guido van Rossum3926a632001-09-25 16:25:58 +00002681 return res;
2682}
2683
2684static PyMethodDef object_methods[] = {
Guido van Rossumc53f0092003-02-18 22:05:12 +00002685 {"__reduce_ex__", object_reduce_ex, METH_VARARGS,
2686 PyDoc_STR("helper for pickle")},
2687 {"__reduce__", object_reduce_ex, METH_VARARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002688 PyDoc_STR("helper for pickle")},
Guido van Rossum3926a632001-09-25 16:25:58 +00002689 {0}
2690};
2691
Guido van Rossum036f9992003-02-21 22:02:54 +00002692
Tim Peters6d6c1a32001-08-02 04:15:00 +00002693PyTypeObject PyBaseObject_Type = {
2694 PyObject_HEAD_INIT(&PyType_Type)
2695 0, /* ob_size */
2696 "object", /* tp_name */
2697 sizeof(PyObject), /* tp_basicsize */
2698 0, /* tp_itemsize */
2699 (destructor)object_dealloc, /* tp_dealloc */
2700 0, /* tp_print */
2701 0, /* tp_getattr */
2702 0, /* tp_setattr */
2703 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002704 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002705 0, /* tp_as_number */
2706 0, /* tp_as_sequence */
2707 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002708 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002709 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002710 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002711 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002712 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002713 0, /* tp_as_buffer */
2714 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002715 PyDoc_STR("The most base type"), /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002716 0, /* tp_traverse */
2717 0, /* tp_clear */
2718 0, /* tp_richcompare */
2719 0, /* tp_weaklistoffset */
2720 0, /* tp_iter */
2721 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00002722 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002723 0, /* tp_members */
2724 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002725 0, /* tp_base */
2726 0, /* tp_dict */
2727 0, /* tp_descr_get */
2728 0, /* tp_descr_set */
2729 0, /* tp_dictoffset */
2730 object_init, /* tp_init */
2731 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossum298e4212003-02-13 16:30:16 +00002732 object_new, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002733 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002734};
2735
2736
2737/* Initialize the __dict__ in a type object */
2738
2739static int
2740add_methods(PyTypeObject *type, PyMethodDef *meth)
2741{
Guido van Rossum687ae002001-10-15 22:03:32 +00002742 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002743
2744 for (; meth->ml_name != NULL; meth++) {
2745 PyObject *descr;
2746 if (PyDict_GetItemString(dict, meth->ml_name))
2747 continue;
Fred Drake7bf97152002-03-28 05:33:33 +00002748 if (meth->ml_flags & METH_CLASS) {
2749 if (meth->ml_flags & METH_STATIC) {
2750 PyErr_SetString(PyExc_ValueError,
2751 "method cannot be both class and static");
2752 return -1;
2753 }
Tim Petersbca1cbc2002-12-09 22:56:13 +00002754 descr = PyDescr_NewClassMethod(type, meth);
Fred Drake7bf97152002-03-28 05:33:33 +00002755 }
2756 else if (meth->ml_flags & METH_STATIC) {
Guido van Rossum9af48ff2003-02-11 17:12:46 +00002757 PyObject *cfunc = PyCFunction_New(meth, NULL);
2758 if (cfunc == NULL)
2759 return -1;
2760 descr = PyStaticMethod_New(cfunc);
2761 Py_DECREF(cfunc);
Fred Drake7bf97152002-03-28 05:33:33 +00002762 }
2763 else {
2764 descr = PyDescr_NewMethod(type, meth);
2765 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002766 if (descr == NULL)
2767 return -1;
Fred Drake7bf97152002-03-28 05:33:33 +00002768 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002769 return -1;
2770 Py_DECREF(descr);
2771 }
2772 return 0;
2773}
2774
2775static int
Guido van Rossum6f799372001-09-20 20:46:19 +00002776add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002777{
Guido van Rossum687ae002001-10-15 22:03:32 +00002778 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002779
2780 for (; memb->name != NULL; memb++) {
2781 PyObject *descr;
2782 if (PyDict_GetItemString(dict, memb->name))
2783 continue;
2784 descr = PyDescr_NewMember(type, memb);
2785 if (descr == NULL)
2786 return -1;
2787 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
2788 return -1;
2789 Py_DECREF(descr);
2790 }
2791 return 0;
2792}
2793
2794static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00002795add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002796{
Guido van Rossum687ae002001-10-15 22:03:32 +00002797 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002798
2799 for (; gsp->name != NULL; gsp++) {
2800 PyObject *descr;
2801 if (PyDict_GetItemString(dict, gsp->name))
2802 continue;
2803 descr = PyDescr_NewGetSet(type, gsp);
2804
2805 if (descr == NULL)
2806 return -1;
2807 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
2808 return -1;
2809 Py_DECREF(descr);
2810 }
2811 return 0;
2812}
2813
Guido van Rossum13d52f02001-08-10 21:24:08 +00002814static void
2815inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002816{
2817 int oldsize, newsize;
2818
Guido van Rossum13d52f02001-08-10 21:24:08 +00002819 /* Special flag magic */
2820 if (!type->tp_as_buffer && base->tp_as_buffer) {
2821 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
2822 type->tp_flags |=
2823 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
2824 }
2825 if (!type->tp_as_sequence && base->tp_as_sequence) {
2826 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
2827 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
2828 }
2829 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
2830 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
2831 if ((!type->tp_as_number && base->tp_as_number) ||
2832 (!type->tp_as_sequence && base->tp_as_sequence)) {
2833 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
2834 if (!type->tp_as_number && !type->tp_as_sequence) {
2835 type->tp_flags |= base->tp_flags &
2836 Py_TPFLAGS_HAVE_INPLACEOPS;
2837 }
2838 }
2839 /* Wow */
2840 }
2841 if (!type->tp_as_number && base->tp_as_number) {
2842 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
2843 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
2844 }
2845
2846 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00002847 oldsize = base->tp_basicsize;
2848 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
2849 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
2850 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00002851 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
2852 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00002853 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00002854 if (type->tp_traverse == NULL)
2855 type->tp_traverse = base->tp_traverse;
2856 if (type->tp_clear == NULL)
2857 type->tp_clear = base->tp_clear;
2858 }
2859 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
Guido van Rossumf884b742001-12-17 17:14:22 +00002860 /* The condition below could use some explanation.
2861 It appears that tp_new is not inherited for static types
2862 whose base class is 'object'; this seems to be a precaution
2863 so that old extension types don't suddenly become
2864 callable (object.__new__ wouldn't insure the invariants
2865 that the extension type's own factory function ensures).
2866 Heap types, of course, are under our control, so they do
2867 inherit tp_new; static extension types that specify some
2868 other built-in type as the default are considered
2869 new-style-aware so they also inherit object.__new__. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002870 if (base != &PyBaseObject_Type ||
2871 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2872 if (type->tp_new == NULL)
2873 type->tp_new = base->tp_new;
2874 }
2875 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00002876 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00002877
2878 /* Copy other non-function slots */
2879
2880#undef COPYVAL
2881#define COPYVAL(SLOT) \
2882 if (type->SLOT == 0) type->SLOT = base->SLOT
2883
2884 COPYVAL(tp_itemsize);
2885 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
2886 COPYVAL(tp_weaklistoffset);
2887 }
2888 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2889 COPYVAL(tp_dictoffset);
2890 }
Guido van Rossum13d52f02001-08-10 21:24:08 +00002891}
2892
2893static void
2894inherit_slots(PyTypeObject *type, PyTypeObject *base)
2895{
2896 PyTypeObject *basebase;
2897
2898#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00002899#undef COPYSLOT
2900#undef COPYNUM
2901#undef COPYSEQ
2902#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00002903#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00002904
2905#define SLOTDEFINED(SLOT) \
2906 (base->SLOT != 0 && \
2907 (basebase == NULL || base->SLOT != basebase->SLOT))
2908
Tim Peters6d6c1a32001-08-02 04:15:00 +00002909#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00002910 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00002911
2912#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
2913#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
2914#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00002915#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002916
Guido van Rossum13d52f02001-08-10 21:24:08 +00002917 /* This won't inherit indirect slots (from tp_as_number etc.)
2918 if type doesn't provide the space. */
2919
2920 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
2921 basebase = base->tp_base;
2922 if (basebase->tp_as_number == NULL)
2923 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002924 COPYNUM(nb_add);
2925 COPYNUM(nb_subtract);
2926 COPYNUM(nb_multiply);
2927 COPYNUM(nb_divide);
2928 COPYNUM(nb_remainder);
2929 COPYNUM(nb_divmod);
2930 COPYNUM(nb_power);
2931 COPYNUM(nb_negative);
2932 COPYNUM(nb_positive);
2933 COPYNUM(nb_absolute);
2934 COPYNUM(nb_nonzero);
2935 COPYNUM(nb_invert);
2936 COPYNUM(nb_lshift);
2937 COPYNUM(nb_rshift);
2938 COPYNUM(nb_and);
2939 COPYNUM(nb_xor);
2940 COPYNUM(nb_or);
2941 COPYNUM(nb_coerce);
2942 COPYNUM(nb_int);
2943 COPYNUM(nb_long);
2944 COPYNUM(nb_float);
2945 COPYNUM(nb_oct);
2946 COPYNUM(nb_hex);
2947 COPYNUM(nb_inplace_add);
2948 COPYNUM(nb_inplace_subtract);
2949 COPYNUM(nb_inplace_multiply);
2950 COPYNUM(nb_inplace_divide);
2951 COPYNUM(nb_inplace_remainder);
2952 COPYNUM(nb_inplace_power);
2953 COPYNUM(nb_inplace_lshift);
2954 COPYNUM(nb_inplace_rshift);
2955 COPYNUM(nb_inplace_and);
2956 COPYNUM(nb_inplace_xor);
2957 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00002958 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
2959 COPYNUM(nb_true_divide);
2960 COPYNUM(nb_floor_divide);
2961 COPYNUM(nb_inplace_true_divide);
2962 COPYNUM(nb_inplace_floor_divide);
2963 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002964 }
2965
Guido van Rossum13d52f02001-08-10 21:24:08 +00002966 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
2967 basebase = base->tp_base;
2968 if (basebase->tp_as_sequence == NULL)
2969 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002970 COPYSEQ(sq_length);
2971 COPYSEQ(sq_concat);
2972 COPYSEQ(sq_repeat);
2973 COPYSEQ(sq_item);
2974 COPYSEQ(sq_slice);
2975 COPYSEQ(sq_ass_item);
2976 COPYSEQ(sq_ass_slice);
2977 COPYSEQ(sq_contains);
2978 COPYSEQ(sq_inplace_concat);
2979 COPYSEQ(sq_inplace_repeat);
2980 }
2981
Guido van Rossum13d52f02001-08-10 21:24:08 +00002982 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
2983 basebase = base->tp_base;
2984 if (basebase->tp_as_mapping == NULL)
2985 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002986 COPYMAP(mp_length);
2987 COPYMAP(mp_subscript);
2988 COPYMAP(mp_ass_subscript);
2989 }
2990
Tim Petersfc57ccb2001-10-12 02:38:24 +00002991 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
2992 basebase = base->tp_base;
2993 if (basebase->tp_as_buffer == NULL)
2994 basebase = NULL;
2995 COPYBUF(bf_getreadbuffer);
2996 COPYBUF(bf_getwritebuffer);
2997 COPYBUF(bf_getsegcount);
2998 COPYBUF(bf_getcharbuffer);
2999 }
3000
Guido van Rossum13d52f02001-08-10 21:24:08 +00003001 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003002
Tim Peters6d6c1a32001-08-02 04:15:00 +00003003 COPYSLOT(tp_dealloc);
3004 COPYSLOT(tp_print);
3005 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
3006 type->tp_getattr = base->tp_getattr;
3007 type->tp_getattro = base->tp_getattro;
3008 }
3009 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
3010 type->tp_setattr = base->tp_setattr;
3011 type->tp_setattro = base->tp_setattro;
3012 }
3013 /* tp_compare see tp_richcompare */
3014 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003015 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003016 COPYSLOT(tp_call);
3017 COPYSLOT(tp_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003018 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003019 if (type->tp_compare == NULL &&
3020 type->tp_richcompare == NULL &&
3021 type->tp_hash == NULL)
3022 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003023 type->tp_compare = base->tp_compare;
3024 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003025 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003026 }
3027 }
3028 else {
3029 COPYSLOT(tp_compare);
3030 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003031 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
3032 COPYSLOT(tp_iter);
3033 COPYSLOT(tp_iternext);
3034 }
3035 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
3036 COPYSLOT(tp_descr_get);
3037 COPYSLOT(tp_descr_set);
3038 COPYSLOT(tp_dictoffset);
3039 COPYSLOT(tp_init);
3040 COPYSLOT(tp_alloc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003041 COPYSLOT(tp_free);
Guido van Rossumcc8fe042002-04-05 17:10:16 +00003042 COPYSLOT(tp_is_gc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003043 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003044}
3045
Jeremy Hylton938ace62002-07-17 16:30:39 +00003046static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00003047
Tim Peters6d6c1a32001-08-02 04:15:00 +00003048int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00003049PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003050{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003051 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003052 PyTypeObject *base;
3053 int i, n;
3054
Guido van Rossumcab05802002-06-10 15:29:03 +00003055 if (type->tp_flags & Py_TPFLAGS_READY) {
3056 assert(type->tp_dict != NULL);
Guido van Rossumd614f972001-08-10 17:39:49 +00003057 return 0;
Guido van Rossumcab05802002-06-10 15:29:03 +00003058 }
Guido van Rossumd614f972001-08-10 17:39:49 +00003059 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00003060
3061 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003062
Tim Peters36eb4df2003-03-23 03:33:13 +00003063#ifdef Py_TRACE_REFS
3064 /* PyType_Ready is the closest thing we have to a choke point
3065 * for type objects, so is the best place I can think of to try
3066 * to get type objects into the doubly-linked list of all objects.
3067 * Still, not all type objects go thru PyType_Ready.
3068 */
Tim Peters7571a0f2003-03-23 17:52:28 +00003069 _Py_AddToAllObjects((PyObject *)type, 0);
Tim Peters36eb4df2003-03-23 03:33:13 +00003070#endif
3071
Tim Peters6d6c1a32001-08-02 04:15:00 +00003072 /* Initialize tp_base (defaults to BaseObject unless that's us) */
3073 base = type->tp_base;
3074 if (base == NULL && type != &PyBaseObject_Type)
3075 base = type->tp_base = &PyBaseObject_Type;
3076
Guido van Rossum323a9cf2002-08-14 17:26:30 +00003077 /* Initialize the base class */
3078 if (base && base->tp_dict == NULL) {
3079 if (PyType_Ready(base) < 0)
3080 goto error;
3081 }
3082
Guido van Rossum0986d822002-04-08 01:38:42 +00003083 /* Initialize ob_type if NULL. This means extensions that want to be
3084 compilable separately on Windows can call PyType_Ready() instead of
3085 initializing the ob_type field of their type objects. */
3086 if (type->ob_type == NULL)
3087 type->ob_type = base->ob_type;
3088
Tim Peters6d6c1a32001-08-02 04:15:00 +00003089 /* Initialize tp_bases */
3090 bases = type->tp_bases;
3091 if (bases == NULL) {
3092 if (base == NULL)
3093 bases = PyTuple_New(0);
3094 else
3095 bases = Py_BuildValue("(O)", base);
3096 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003097 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003098 type->tp_bases = bases;
3099 }
3100
Guido van Rossum687ae002001-10-15 22:03:32 +00003101 /* Initialize tp_dict */
3102 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003103 if (dict == NULL) {
3104 dict = PyDict_New();
3105 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003106 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00003107 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003108 }
3109
Guido van Rossum687ae002001-10-15 22:03:32 +00003110 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003111 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003112 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003113 if (type->tp_methods != NULL) {
3114 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003115 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003116 }
3117 if (type->tp_members != NULL) {
3118 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003119 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003120 }
3121 if (type->tp_getset != NULL) {
3122 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003123 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003124 }
3125
Tim Peters6d6c1a32001-08-02 04:15:00 +00003126 /* Calculate method resolution order */
3127 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00003128 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003129 }
3130
Guido van Rossum13d52f02001-08-10 21:24:08 +00003131 /* Inherit special flags from dominant base */
3132 if (type->tp_base != NULL)
3133 inherit_special(type, type->tp_base);
3134
Tim Peters6d6c1a32001-08-02 04:15:00 +00003135 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003136 bases = type->tp_mro;
3137 assert(bases != NULL);
3138 assert(PyTuple_Check(bases));
3139 n = PyTuple_GET_SIZE(bases);
3140 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003141 PyObject *b = PyTuple_GET_ITEM(bases, i);
3142 if (PyType_Check(b))
3143 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003144 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003145
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003146 /* if the type dictionary doesn't contain a __doc__, set it from
3147 the tp_doc slot.
3148 */
3149 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
3150 if (type->tp_doc != NULL) {
3151 PyObject *doc = PyString_FromString(type->tp_doc);
3152 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
3153 Py_DECREF(doc);
3154 } else {
Guido van Rossumd4641072002-04-03 02:13:37 +00003155 PyDict_SetItemString(type->tp_dict,
3156 "__doc__", Py_None);
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003157 }
3158 }
3159
Guido van Rossum13d52f02001-08-10 21:24:08 +00003160 /* Some more special stuff */
3161 base = type->tp_base;
3162 if (base != NULL) {
3163 if (type->tp_as_number == NULL)
3164 type->tp_as_number = base->tp_as_number;
3165 if (type->tp_as_sequence == NULL)
3166 type->tp_as_sequence = base->tp_as_sequence;
3167 if (type->tp_as_mapping == NULL)
3168 type->tp_as_mapping = base->tp_as_mapping;
Guido van Rossumeea47182003-02-11 20:39:59 +00003169 if (type->tp_as_buffer == NULL)
3170 type->tp_as_buffer = base->tp_as_buffer;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003171 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003172
Guido van Rossum1c450732001-10-08 15:18:27 +00003173 /* Link into each base class's list of subclasses */
3174 bases = type->tp_bases;
3175 n = PyTuple_GET_SIZE(bases);
3176 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003177 PyObject *b = PyTuple_GET_ITEM(bases, i);
3178 if (PyType_Check(b) &&
3179 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00003180 goto error;
3181 }
3182
Guido van Rossum13d52f02001-08-10 21:24:08 +00003183 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00003184 assert(type->tp_dict != NULL);
3185 type->tp_flags =
3186 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003187 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00003188
3189 error:
3190 type->tp_flags &= ~Py_TPFLAGS_READYING;
3191 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003192}
3193
Guido van Rossum1c450732001-10-08 15:18:27 +00003194static int
3195add_subclass(PyTypeObject *base, PyTypeObject *type)
3196{
3197 int i;
3198 PyObject *list, *ref, *new;
3199
3200 list = base->tp_subclasses;
3201 if (list == NULL) {
3202 base->tp_subclasses = list = PyList_New(0);
3203 if (list == NULL)
3204 return -1;
3205 }
3206 assert(PyList_Check(list));
3207 new = PyWeakref_NewRef((PyObject *)type, NULL);
3208 i = PyList_GET_SIZE(list);
3209 while (--i >= 0) {
3210 ref = PyList_GET_ITEM(list, i);
3211 assert(PyWeakref_CheckRef(ref));
Guido van Rossum3930bc32002-10-18 13:51:49 +00003212 if (PyWeakref_GET_OBJECT(ref) == Py_None)
3213 return PyList_SetItem(list, i, new);
Guido van Rossum1c450732001-10-08 15:18:27 +00003214 }
3215 i = PyList_Append(list, new);
3216 Py_DECREF(new);
3217 return i;
3218}
3219
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003220static void
3221remove_subclass(PyTypeObject *base, PyTypeObject *type)
3222{
3223 int i;
3224 PyObject *list, *ref;
3225
3226 list = base->tp_subclasses;
3227 if (list == NULL) {
3228 return;
3229 }
3230 assert(PyList_Check(list));
3231 i = PyList_GET_SIZE(list);
3232 while (--i >= 0) {
3233 ref = PyList_GET_ITEM(list, i);
3234 assert(PyWeakref_CheckRef(ref));
3235 if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
3236 /* this can't fail, right? */
3237 PySequence_DelItem(list, i);
3238 return;
3239 }
3240 }
3241}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003242
3243/* Generic wrappers for overloadable 'operators' such as __getitem__ */
3244
3245/* There's a wrapper *function* for each distinct function typedef used
3246 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
3247 wrapper *table* for each distinct operation (e.g. __len__, __add__).
3248 Most tables have only one entry; the tables for binary operators have two
3249 entries, one regular and one with reversed arguments. */
3250
3251static PyObject *
3252wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
3253{
3254 inquiry func = (inquiry)wrapped;
3255 int res;
3256
3257 if (!PyArg_ParseTuple(args, ""))
3258 return NULL;
3259 res = (*func)(self);
3260 if (res == -1 && PyErr_Occurred())
3261 return NULL;
3262 return PyInt_FromLong((long)res);
3263}
3264
Tim Peters6d6c1a32001-08-02 04:15:00 +00003265static PyObject *
3266wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
3267{
3268 binaryfunc func = (binaryfunc)wrapped;
3269 PyObject *other;
3270
3271 if (!PyArg_ParseTuple(args, "O", &other))
3272 return NULL;
3273 return (*func)(self, other);
3274}
3275
3276static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003277wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
3278{
3279 binaryfunc func = (binaryfunc)wrapped;
3280 PyObject *other;
3281
3282 if (!PyArg_ParseTuple(args, "O", &other))
3283 return NULL;
3284 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003285 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003286 Py_INCREF(Py_NotImplemented);
3287 return Py_NotImplemented;
3288 }
3289 return (*func)(self, other);
3290}
3291
3292static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003293wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3294{
3295 binaryfunc func = (binaryfunc)wrapped;
3296 PyObject *other;
3297
3298 if (!PyArg_ParseTuple(args, "O", &other))
3299 return NULL;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003300 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003301 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003302 Py_INCREF(Py_NotImplemented);
3303 return Py_NotImplemented;
3304 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003305 return (*func)(other, self);
3306}
3307
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003308static PyObject *
3309wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
3310{
3311 coercion func = (coercion)wrapped;
3312 PyObject *other, *res;
3313 int ok;
3314
3315 if (!PyArg_ParseTuple(args, "O", &other))
3316 return NULL;
3317 ok = func(&self, &other);
3318 if (ok < 0)
3319 return NULL;
3320 if (ok > 0) {
3321 Py_INCREF(Py_NotImplemented);
3322 return Py_NotImplemented;
3323 }
3324 res = PyTuple_New(2);
3325 if (res == NULL) {
3326 Py_DECREF(self);
3327 Py_DECREF(other);
3328 return NULL;
3329 }
3330 PyTuple_SET_ITEM(res, 0, self);
3331 PyTuple_SET_ITEM(res, 1, other);
3332 return res;
3333}
3334
Tim Peters6d6c1a32001-08-02 04:15:00 +00003335static PyObject *
3336wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
3337{
3338 ternaryfunc func = (ternaryfunc)wrapped;
3339 PyObject *other;
3340 PyObject *third = Py_None;
3341
3342 /* Note: This wrapper only works for __pow__() */
3343
3344 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
3345 return NULL;
3346 return (*func)(self, other, third);
3347}
3348
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00003349static PyObject *
3350wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3351{
3352 ternaryfunc func = (ternaryfunc)wrapped;
3353 PyObject *other;
3354 PyObject *third = Py_None;
3355
3356 /* Note: This wrapper only works for __pow__() */
3357
3358 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
3359 return NULL;
3360 return (*func)(other, self, third);
3361}
3362
Tim Peters6d6c1a32001-08-02 04:15:00 +00003363static PyObject *
3364wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
3365{
3366 unaryfunc func = (unaryfunc)wrapped;
3367
3368 if (!PyArg_ParseTuple(args, ""))
3369 return NULL;
3370 return (*func)(self);
3371}
3372
Tim Peters6d6c1a32001-08-02 04:15:00 +00003373static PyObject *
3374wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
3375{
3376 intargfunc func = (intargfunc)wrapped;
3377 int i;
3378
3379 if (!PyArg_ParseTuple(args, "i", &i))
3380 return NULL;
3381 return (*func)(self, i);
3382}
3383
Guido van Rossum5d815f32001-08-17 21:57:47 +00003384static int
3385getindex(PyObject *self, PyObject *arg)
3386{
3387 int i;
3388
3389 i = PyInt_AsLong(arg);
3390 if (i == -1 && PyErr_Occurred())
3391 return -1;
3392 if (i < 0) {
3393 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
3394 if (sq && sq->sq_length) {
3395 int n = (*sq->sq_length)(self);
3396 if (n < 0)
3397 return -1;
3398 i += n;
3399 }
3400 }
3401 return i;
3402}
3403
3404static PyObject *
3405wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
3406{
3407 intargfunc func = (intargfunc)wrapped;
3408 PyObject *arg;
3409 int i;
3410
Guido van Rossumf4593e02001-10-03 12:09:30 +00003411 if (PyTuple_GET_SIZE(args) == 1) {
3412 arg = PyTuple_GET_ITEM(args, 0);
3413 i = getindex(self, arg);
3414 if (i == -1 && PyErr_Occurred())
3415 return NULL;
3416 return (*func)(self, i);
3417 }
3418 PyArg_ParseTuple(args, "O", &arg);
3419 assert(PyErr_Occurred());
3420 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003421}
3422
Tim Peters6d6c1a32001-08-02 04:15:00 +00003423static PyObject *
3424wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
3425{
3426 intintargfunc func = (intintargfunc)wrapped;
3427 int i, j;
3428
3429 if (!PyArg_ParseTuple(args, "ii", &i, &j))
3430 return NULL;
3431 return (*func)(self, i, j);
3432}
3433
Tim Peters6d6c1a32001-08-02 04:15:00 +00003434static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003435wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003436{
3437 intobjargproc func = (intobjargproc)wrapped;
3438 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003439 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003440
Guido van Rossum5d815f32001-08-17 21:57:47 +00003441 if (!PyArg_ParseTuple(args, "OO", &arg, &value))
3442 return NULL;
3443 i = getindex(self, arg);
3444 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00003445 return NULL;
3446 res = (*func)(self, i, value);
3447 if (res == -1 && PyErr_Occurred())
3448 return NULL;
3449 Py_INCREF(Py_None);
3450 return Py_None;
3451}
3452
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003453static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003454wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003455{
3456 intobjargproc func = (intobjargproc)wrapped;
3457 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003458 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003459
Guido van Rossum5d815f32001-08-17 21:57:47 +00003460 if (!PyArg_ParseTuple(args, "O", &arg))
3461 return NULL;
3462 i = getindex(self, arg);
3463 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003464 return NULL;
3465 res = (*func)(self, i, NULL);
3466 if (res == -1 && PyErr_Occurred())
3467 return NULL;
3468 Py_INCREF(Py_None);
3469 return Py_None;
3470}
3471
Tim Peters6d6c1a32001-08-02 04:15:00 +00003472static PyObject *
3473wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
3474{
3475 intintobjargproc func = (intintobjargproc)wrapped;
3476 int i, j, res;
3477 PyObject *value;
3478
3479 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
3480 return NULL;
3481 res = (*func)(self, i, j, value);
3482 if (res == -1 && PyErr_Occurred())
3483 return NULL;
3484 Py_INCREF(Py_None);
3485 return Py_None;
3486}
3487
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003488static PyObject *
3489wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
3490{
3491 intintobjargproc func = (intintobjargproc)wrapped;
3492 int i, j, res;
3493
3494 if (!PyArg_ParseTuple(args, "ii", &i, &j))
3495 return NULL;
3496 res = (*func)(self, i, j, NULL);
3497 if (res == -1 && PyErr_Occurred())
3498 return NULL;
3499 Py_INCREF(Py_None);
3500 return Py_None;
3501}
3502
Tim Peters6d6c1a32001-08-02 04:15:00 +00003503/* XXX objobjproc is a misnomer; should be objargpred */
3504static PyObject *
3505wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
3506{
3507 objobjproc func = (objobjproc)wrapped;
3508 int res;
3509 PyObject *value;
3510
3511 if (!PyArg_ParseTuple(args, "O", &value))
3512 return NULL;
3513 res = (*func)(self, value);
3514 if (res == -1 && PyErr_Occurred())
3515 return NULL;
3516 return PyInt_FromLong((long)res);
3517}
3518
Tim Peters6d6c1a32001-08-02 04:15:00 +00003519static PyObject *
3520wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
3521{
3522 objobjargproc func = (objobjargproc)wrapped;
3523 int res;
3524 PyObject *key, *value;
3525
3526 if (!PyArg_ParseTuple(args, "OO", &key, &value))
3527 return NULL;
3528 res = (*func)(self, key, value);
3529 if (res == -1 && PyErr_Occurred())
3530 return NULL;
3531 Py_INCREF(Py_None);
3532 return Py_None;
3533}
3534
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003535static PyObject *
3536wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
3537{
3538 objobjargproc func = (objobjargproc)wrapped;
3539 int res;
3540 PyObject *key;
3541
3542 if (!PyArg_ParseTuple(args, "O", &key))
3543 return NULL;
3544 res = (*func)(self, key, NULL);
3545 if (res == -1 && PyErr_Occurred())
3546 return NULL;
3547 Py_INCREF(Py_None);
3548 return Py_None;
3549}
3550
Tim Peters6d6c1a32001-08-02 04:15:00 +00003551static PyObject *
3552wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
3553{
3554 cmpfunc func = (cmpfunc)wrapped;
3555 int res;
3556 PyObject *other;
3557
3558 if (!PyArg_ParseTuple(args, "O", &other))
3559 return NULL;
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00003560 if (other->ob_type->tp_compare != func &&
3561 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00003562 PyErr_Format(
3563 PyExc_TypeError,
3564 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
3565 self->ob_type->tp_name,
3566 self->ob_type->tp_name,
3567 other->ob_type->tp_name);
3568 return NULL;
3569 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003570 res = (*func)(self, other);
3571 if (PyErr_Occurred())
3572 return NULL;
3573 return PyInt_FromLong((long)res);
3574}
3575
Tim Peters6d6c1a32001-08-02 04:15:00 +00003576static PyObject *
3577wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
3578{
3579 setattrofunc func = (setattrofunc)wrapped;
3580 int res;
3581 PyObject *name, *value;
3582
3583 if (!PyArg_ParseTuple(args, "OO", &name, &value))
3584 return NULL;
3585 res = (*func)(self, name, value);
3586 if (res < 0)
3587 return NULL;
3588 Py_INCREF(Py_None);
3589 return Py_None;
3590}
3591
3592static PyObject *
3593wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
3594{
3595 setattrofunc func = (setattrofunc)wrapped;
3596 int res;
3597 PyObject *name;
3598
3599 if (!PyArg_ParseTuple(args, "O", &name))
3600 return NULL;
3601 res = (*func)(self, name, NULL);
3602 if (res < 0)
3603 return NULL;
3604 Py_INCREF(Py_None);
3605 return Py_None;
3606}
3607
Tim Peters6d6c1a32001-08-02 04:15:00 +00003608static PyObject *
3609wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
3610{
3611 hashfunc func = (hashfunc)wrapped;
3612 long res;
3613
3614 if (!PyArg_ParseTuple(args, ""))
3615 return NULL;
3616 res = (*func)(self);
3617 if (res == -1 && PyErr_Occurred())
3618 return NULL;
3619 return PyInt_FromLong(res);
3620}
3621
Tim Peters6d6c1a32001-08-02 04:15:00 +00003622static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00003623wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003624{
3625 ternaryfunc func = (ternaryfunc)wrapped;
3626
Guido van Rossumc8e56452001-10-22 00:43:43 +00003627 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003628}
3629
Tim Peters6d6c1a32001-08-02 04:15:00 +00003630static PyObject *
3631wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
3632{
3633 richcmpfunc func = (richcmpfunc)wrapped;
3634 PyObject *other;
3635
3636 if (!PyArg_ParseTuple(args, "O", &other))
3637 return NULL;
3638 return (*func)(self, other, op);
3639}
3640
3641#undef RICHCMP_WRAPPER
3642#define RICHCMP_WRAPPER(NAME, OP) \
3643static PyObject * \
3644richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
3645{ \
3646 return wrap_richcmpfunc(self, args, wrapped, OP); \
3647}
3648
Jack Jansen8e938b42001-08-08 15:29:49 +00003649RICHCMP_WRAPPER(lt, Py_LT)
3650RICHCMP_WRAPPER(le, Py_LE)
3651RICHCMP_WRAPPER(eq, Py_EQ)
3652RICHCMP_WRAPPER(ne, Py_NE)
3653RICHCMP_WRAPPER(gt, Py_GT)
3654RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003655
Tim Peters6d6c1a32001-08-02 04:15:00 +00003656static PyObject *
3657wrap_next(PyObject *self, PyObject *args, void *wrapped)
3658{
3659 unaryfunc func = (unaryfunc)wrapped;
3660 PyObject *res;
3661
3662 if (!PyArg_ParseTuple(args, ""))
3663 return NULL;
3664 res = (*func)(self);
3665 if (res == NULL && !PyErr_Occurred())
3666 PyErr_SetNone(PyExc_StopIteration);
3667 return res;
3668}
3669
Tim Peters6d6c1a32001-08-02 04:15:00 +00003670static PyObject *
3671wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
3672{
3673 descrgetfunc func = (descrgetfunc)wrapped;
3674 PyObject *obj;
3675 PyObject *type = NULL;
3676
3677 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
3678 return NULL;
Guido van Rossum82ed25c2003-02-11 16:25:43 +00003679 if (obj == Py_None)
3680 obj = NULL;
3681 if (type == Py_None)
3682 type = NULL;
3683 if (type == NULL &&obj == NULL) {
3684 PyErr_SetString(PyExc_TypeError,
3685 "__get__(None, None) is invalid");
3686 return NULL;
3687 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003688 return (*func)(self, obj, type);
3689}
3690
Tim Peters6d6c1a32001-08-02 04:15:00 +00003691static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003692wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003693{
3694 descrsetfunc func = (descrsetfunc)wrapped;
3695 PyObject *obj, *value;
3696 int ret;
3697
3698 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
3699 return NULL;
3700 ret = (*func)(self, obj, value);
3701 if (ret < 0)
3702 return NULL;
3703 Py_INCREF(Py_None);
3704 return Py_None;
3705}
Guido van Rossum22b13872002-08-06 21:41:44 +00003706
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00003707static PyObject *
3708wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
3709{
3710 descrsetfunc func = (descrsetfunc)wrapped;
3711 PyObject *obj;
3712 int ret;
3713
3714 if (!PyArg_ParseTuple(args, "O", &obj))
3715 return NULL;
3716 ret = (*func)(self, obj, NULL);
3717 if (ret < 0)
3718 return NULL;
3719 Py_INCREF(Py_None);
3720 return Py_None;
3721}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003722
Tim Peters6d6c1a32001-08-02 04:15:00 +00003723static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00003724wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003725{
3726 initproc func = (initproc)wrapped;
3727
Guido van Rossumc8e56452001-10-22 00:43:43 +00003728 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003729 return NULL;
3730 Py_INCREF(Py_None);
3731 return Py_None;
3732}
3733
Tim Peters6d6c1a32001-08-02 04:15:00 +00003734static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003735tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003736{
Barry Warsaw60f01882001-08-22 19:24:42 +00003737 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003738 PyObject *arg0, *res;
3739
3740 if (self == NULL || !PyType_Check(self))
3741 Py_FatalError("__new__() called with non-type 'self'");
3742 type = (PyTypeObject *)self;
3743 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003744 PyErr_Format(PyExc_TypeError,
3745 "%s.__new__(): not enough arguments",
3746 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003747 return NULL;
3748 }
3749 arg0 = PyTuple_GET_ITEM(args, 0);
3750 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003751 PyErr_Format(PyExc_TypeError,
3752 "%s.__new__(X): X is not a type object (%s)",
3753 type->tp_name,
3754 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003755 return NULL;
3756 }
3757 subtype = (PyTypeObject *)arg0;
3758 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003759 PyErr_Format(PyExc_TypeError,
3760 "%s.__new__(%s): %s is not a subtype of %s",
3761 type->tp_name,
3762 subtype->tp_name,
3763 subtype->tp_name,
3764 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003765 return NULL;
3766 }
Barry Warsaw60f01882001-08-22 19:24:42 +00003767
3768 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00003769 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00003770 most derived base that's not a heap type is this type. */
3771 staticbase = subtype;
3772 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
3773 staticbase = staticbase->tp_base;
Guido van Rossuma8c60f42001-09-14 19:43:36 +00003774 if (staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003775 PyErr_Format(PyExc_TypeError,
3776 "%s.__new__(%s) is not safe, use %s.__new__()",
3777 type->tp_name,
3778 subtype->tp_name,
3779 staticbase == NULL ? "?" : staticbase->tp_name);
3780 return NULL;
3781 }
3782
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003783 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
3784 if (args == NULL)
3785 return NULL;
3786 res = type->tp_new(subtype, args, kwds);
3787 Py_DECREF(args);
3788 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003789}
3790
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003791static struct PyMethodDef tp_new_methoddef[] = {
3792 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00003793 PyDoc_STR("T.__new__(S, ...) -> "
3794 "a new object with type S, a subtype of T")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00003795 {0}
3796};
3797
3798static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003799add_tp_new_wrapper(PyTypeObject *type)
3800{
Guido van Rossumf040ede2001-08-07 16:40:56 +00003801 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003802
Guido van Rossum687ae002001-10-15 22:03:32 +00003803 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00003804 return 0;
3805 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003806 if (func == NULL)
3807 return -1;
Guido van Rossum687ae002001-10-15 22:03:32 +00003808 return PyDict_SetItemString(type->tp_dict, "__new__", func);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003809}
3810
Guido van Rossumf040ede2001-08-07 16:40:56 +00003811/* Slot wrappers that call the corresponding __foo__ slot. See comments
3812 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003813
Guido van Rossumdc91b992001-08-08 22:26:22 +00003814#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003815static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003816FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003817{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00003818 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003819 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003820}
3821
Guido van Rossumdc91b992001-08-08 22:26:22 +00003822#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003823static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003824FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003825{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003826 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003827 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003828}
3829
Guido van Rossumcd118802003-01-06 22:57:47 +00003830/* Boolean helper for SLOT1BINFULL().
3831 right.__class__ is a nontrivial subclass of left.__class__. */
3832static int
3833method_is_overloaded(PyObject *left, PyObject *right, char *name)
3834{
3835 PyObject *a, *b;
3836 int ok;
3837
3838 b = PyObject_GetAttrString((PyObject *)(right->ob_type), name);
3839 if (b == NULL) {
3840 PyErr_Clear();
3841 /* If right doesn't have it, it's not overloaded */
3842 return 0;
3843 }
3844
3845 a = PyObject_GetAttrString((PyObject *)(left->ob_type), name);
3846 if (a == NULL) {
3847 PyErr_Clear();
3848 Py_DECREF(b);
3849 /* If right has it but left doesn't, it's overloaded */
3850 return 1;
3851 }
3852
3853 ok = PyObject_RichCompareBool(a, b, Py_NE);
3854 Py_DECREF(a);
3855 Py_DECREF(b);
3856 if (ok < 0) {
3857 PyErr_Clear();
3858 return 0;
3859 }
3860
3861 return ok;
3862}
3863
Guido van Rossumdc91b992001-08-08 22:26:22 +00003864
3865#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003866static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003867FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003868{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003869 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00003870 int do_other = self->ob_type != other->ob_type && \
3871 other->ob_type->tp_as_number != NULL && \
3872 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003873 if (self->ob_type->tp_as_number != NULL && \
3874 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
3875 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00003876 if (do_other && \
Guido van Rossumcd118802003-01-06 22:57:47 +00003877 PyType_IsSubtype(other->ob_type, self->ob_type) && \
3878 method_is_overloaded(self, other, ROPSTR)) { \
Guido van Rossum55f20992001-10-01 17:18:22 +00003879 r = call_maybe( \
3880 other, ROPSTR, &rcache_str, "(O)", self); \
3881 if (r != Py_NotImplemented) \
3882 return r; \
3883 Py_DECREF(r); \
3884 do_other = 0; \
3885 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00003886 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00003887 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003888 if (r != Py_NotImplemented || \
3889 other->ob_type == self->ob_type) \
3890 return r; \
3891 Py_DECREF(r); \
3892 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00003893 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00003894 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00003895 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003896 } \
3897 Py_INCREF(Py_NotImplemented); \
3898 return Py_NotImplemented; \
3899}
3900
3901#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
3902 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
3903
3904#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
3905static PyObject * \
3906FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
3907{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003908 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003909 return call_method(self, OPSTR, &cache_str, \
3910 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003911}
3912
3913static int
3914slot_sq_length(PyObject *self)
3915{
Guido van Rossum2730b132001-08-28 18:22:14 +00003916 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00003917 PyObject *res = call_method(self, "__len__", &len_str, "()");
Guido van Rossum26111622001-10-01 16:42:49 +00003918 int len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003919
3920 if (res == NULL)
3921 return -1;
Guido van Rossum26111622001-10-01 16:42:49 +00003922 len = (int)PyInt_AsLong(res);
3923 Py_DECREF(res);
Jeremy Hylton73a088e2002-07-25 16:43:29 +00003924 if (len == -1 && PyErr_Occurred())
3925 return -1;
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00003926 if (len < 0) {
Guido van Rossum22b13872002-08-06 21:41:44 +00003927 PyErr_SetString(PyExc_ValueError,
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00003928 "__len__() should return >= 0");
3929 return -1;
3930 }
Guido van Rossum26111622001-10-01 16:42:49 +00003931 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003932}
3933
Guido van Rossumdc91b992001-08-08 22:26:22 +00003934SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
3935SLOT1(slot_sq_repeat, "__mul__", int, "i")
Guido van Rossumf4593e02001-10-03 12:09:30 +00003936
3937/* Super-optimized version of slot_sq_item.
3938 Other slots could do the same... */
3939static PyObject *
3940slot_sq_item(PyObject *self, int i)
3941{
3942 static PyObject *getitem_str;
3943 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
3944 descrgetfunc f;
3945
3946 if (getitem_str == NULL) {
3947 getitem_str = PyString_InternFromString("__getitem__");
3948 if (getitem_str == NULL)
3949 return NULL;
3950 }
3951 func = _PyType_Lookup(self->ob_type, getitem_str);
3952 if (func != NULL) {
Guido van Rossumf4593e02001-10-03 12:09:30 +00003953 if ((f = func->ob_type->tp_descr_get) == NULL)
3954 Py_INCREF(func);
Neal Norwitz673cd822002-10-18 16:33:13 +00003955 else {
Guido van Rossumf4593e02001-10-03 12:09:30 +00003956 func = f(func, self, (PyObject *)(self->ob_type));
Neal Norwitz673cd822002-10-18 16:33:13 +00003957 if (func == NULL) {
3958 return NULL;
3959 }
3960 }
Guido van Rossumf4593e02001-10-03 12:09:30 +00003961 ival = PyInt_FromLong(i);
3962 if (ival != NULL) {
3963 args = PyTuple_New(1);
3964 if (args != NULL) {
3965 PyTuple_SET_ITEM(args, 0, ival);
3966 retval = PyObject_Call(func, args, NULL);
3967 Py_XDECREF(args);
3968 Py_XDECREF(func);
3969 return retval;
3970 }
3971 }
3972 }
3973 else {
3974 PyErr_SetObject(PyExc_AttributeError, getitem_str);
3975 }
3976 Py_XDECREF(args);
3977 Py_XDECREF(ival);
3978 Py_XDECREF(func);
3979 return NULL;
3980}
3981
Guido van Rossumdc91b992001-08-08 22:26:22 +00003982SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003983
3984static int
3985slot_sq_ass_item(PyObject *self, int index, PyObject *value)
3986{
3987 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003988 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003989
3990 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003991 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003992 "(i)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003993 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003994 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003995 "(iO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003996 if (res == NULL)
3997 return -1;
3998 Py_DECREF(res);
3999 return 0;
4000}
4001
4002static int
4003slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
4004{
4005 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004006 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004007
4008 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004009 res = call_method(self, "__delslice__", &delslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004010 "(ii)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004011 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004012 res = call_method(self, "__setslice__", &setslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004013 "(iiO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004014 if (res == NULL)
4015 return -1;
4016 Py_DECREF(res);
4017 return 0;
4018}
4019
4020static int
4021slot_sq_contains(PyObject *self, PyObject *value)
4022{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004023 PyObject *func, *res, *args;
Tim Petersbf9b2442003-03-23 05:35:36 +00004024 int result = -1;
4025
Guido van Rossum60718732001-08-28 17:47:51 +00004026 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004027
Guido van Rossum55f20992001-10-01 17:18:22 +00004028 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004029 if (func != NULL) {
4030 args = Py_BuildValue("(O)", value);
4031 if (args == NULL)
4032 res = NULL;
4033 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004034 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004035 Py_DECREF(args);
4036 }
4037 Py_DECREF(func);
Tim Petersbf9b2442003-03-23 05:35:36 +00004038 if (res != NULL) {
4039 result = PyObject_IsTrue(res);
4040 Py_DECREF(res);
4041 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004042 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004043 else if (! PyErr_Occurred()) {
4044 result = _PySequence_IterSearch(self, value,
4045 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004046 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004047 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004048}
4049
Guido van Rossumdc91b992001-08-08 22:26:22 +00004050SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
4051SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004052
4053#define slot_mp_length slot_sq_length
4054
Guido van Rossumdc91b992001-08-08 22:26:22 +00004055SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004056
4057static int
4058slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
4059{
4060 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004061 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004062
4063 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004064 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004065 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004066 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004067 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004068 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004069 if (res == NULL)
4070 return -1;
4071 Py_DECREF(res);
4072 return 0;
4073}
4074
Guido van Rossumdc91b992001-08-08 22:26:22 +00004075SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
4076SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
4077SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
4078SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
4079SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
4080SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
4081
Jeremy Hylton938ace62002-07-17 16:30:39 +00004082static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00004083
4084SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
4085 nb_power, "__pow__", "__rpow__")
4086
4087static PyObject *
4088slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
4089{
Guido van Rossum2730b132001-08-28 18:22:14 +00004090 static PyObject *pow_str;
4091
Guido van Rossumdc91b992001-08-08 22:26:22 +00004092 if (modulus == Py_None)
4093 return slot_nb_power_binary(self, other);
Guido van Rossum23094982002-06-10 14:30:43 +00004094 /* Three-arg power doesn't use __rpow__. But ternary_op
4095 can call this when the second argument's type uses
4096 slot_nb_power, so check before calling self.__pow__. */
4097 if (self->ob_type->tp_as_number != NULL &&
4098 self->ob_type->tp_as_number->nb_power == slot_nb_power) {
4099 return call_method(self, "__pow__", &pow_str,
4100 "(OO)", other, modulus);
4101 }
4102 Py_INCREF(Py_NotImplemented);
4103 return Py_NotImplemented;
Guido van Rossumdc91b992001-08-08 22:26:22 +00004104}
4105
4106SLOT0(slot_nb_negative, "__neg__")
4107SLOT0(slot_nb_positive, "__pos__")
4108SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004109
4110static int
4111slot_nb_nonzero(PyObject *self)
4112{
Tim Petersea7f75d2002-12-07 21:39:16 +00004113 PyObject *func, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00004114 static PyObject *nonzero_str, *len_str;
Tim Petersea7f75d2002-12-07 21:39:16 +00004115 int result = -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004116
Guido van Rossum55f20992001-10-01 17:18:22 +00004117 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004118 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00004119 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00004120 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00004121 func = lookup_maybe(self, "__len__", &len_str);
Tim Petersea7f75d2002-12-07 21:39:16 +00004122 if (func == NULL)
4123 return PyErr_Occurred() ? -1 : 1;
4124 }
4125 args = PyTuple_New(0);
4126 if (args != NULL) {
4127 PyObject *temp = PyObject_Call(func, args, NULL);
4128 Py_DECREF(args);
4129 if (temp != NULL) {
4130 result = PyObject_IsTrue(temp);
4131 Py_DECREF(temp);
Guido van Rossum55f20992001-10-01 17:18:22 +00004132 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004133 }
Guido van Rossum55f20992001-10-01 17:18:22 +00004134 Py_DECREF(func);
Tim Petersea7f75d2002-12-07 21:39:16 +00004135 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004136}
4137
Guido van Rossumdc91b992001-08-08 22:26:22 +00004138SLOT0(slot_nb_invert, "__invert__")
4139SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
4140SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
4141SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
4142SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
4143SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004144
4145static int
4146slot_nb_coerce(PyObject **a, PyObject **b)
4147{
4148 static PyObject *coerce_str;
4149 PyObject *self = *a, *other = *b;
4150
4151 if (self->ob_type->tp_as_number != NULL &&
4152 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
4153 PyObject *r;
4154 r = call_maybe(
4155 self, "__coerce__", &coerce_str, "(O)", other);
4156 if (r == NULL)
4157 return -1;
4158 if (r == Py_NotImplemented) {
4159 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004160 }
Guido van Rossum55f20992001-10-01 17:18:22 +00004161 else {
4162 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
4163 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004164 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00004165 Py_DECREF(r);
4166 return -1;
4167 }
4168 *a = PyTuple_GET_ITEM(r, 0);
4169 Py_INCREF(*a);
4170 *b = PyTuple_GET_ITEM(r, 1);
4171 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004172 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00004173 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004174 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004175 }
4176 if (other->ob_type->tp_as_number != NULL &&
4177 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
4178 PyObject *r;
4179 r = call_maybe(
4180 other, "__coerce__", &coerce_str, "(O)", self);
4181 if (r == NULL)
4182 return -1;
4183 if (r == Py_NotImplemented) {
4184 Py_DECREF(r);
4185 return 1;
4186 }
4187 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
4188 PyErr_SetString(PyExc_TypeError,
4189 "__coerce__ didn't return a 2-tuple");
4190 Py_DECREF(r);
4191 return -1;
4192 }
4193 *a = PyTuple_GET_ITEM(r, 1);
4194 Py_INCREF(*a);
4195 *b = PyTuple_GET_ITEM(r, 0);
4196 Py_INCREF(*b);
4197 Py_DECREF(r);
4198 return 0;
4199 }
4200 return 1;
4201}
4202
Guido van Rossumdc91b992001-08-08 22:26:22 +00004203SLOT0(slot_nb_int, "__int__")
4204SLOT0(slot_nb_long, "__long__")
4205SLOT0(slot_nb_float, "__float__")
4206SLOT0(slot_nb_oct, "__oct__")
4207SLOT0(slot_nb_hex, "__hex__")
4208SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
4209SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
4210SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
4211SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
4212SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Guido van Rossum6e5680f2002-10-15 01:01:53 +00004213SLOT1(slot_nb_inplace_power, "__ipow__", PyObject *, "O")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004214SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
4215SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
4216SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
4217SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
4218SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
4219SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
4220 "__floordiv__", "__rfloordiv__")
4221SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
4222SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
4223SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004224
4225static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00004226half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004227{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004228 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004229 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004230 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004231
Guido van Rossum60718732001-08-28 17:47:51 +00004232 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004233 if (func == NULL) {
4234 PyErr_Clear();
4235 }
4236 else {
4237 args = Py_BuildValue("(O)", other);
4238 if (args == NULL)
4239 res = NULL;
4240 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004241 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004242 Py_DECREF(args);
4243 }
Raymond Hettingerab5dae32002-06-24 13:08:16 +00004244 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004245 if (res != Py_NotImplemented) {
4246 if (res == NULL)
4247 return -2;
4248 c = PyInt_AsLong(res);
4249 Py_DECREF(res);
4250 if (c == -1 && PyErr_Occurred())
4251 return -2;
4252 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
4253 }
4254 Py_DECREF(res);
4255 }
4256 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004257}
4258
Guido van Rossumab3b0342001-09-18 20:38:53 +00004259/* This slot is published for the benefit of try_3way_compare in object.c */
4260int
4261_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00004262{
4263 int c;
4264
Guido van Rossumab3b0342001-09-18 20:38:53 +00004265 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004266 c = half_compare(self, other);
4267 if (c <= 1)
4268 return c;
4269 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00004270 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004271 c = half_compare(other, self);
4272 if (c < -1)
4273 return -2;
4274 if (c <= 1)
4275 return -c;
4276 }
4277 return (void *)self < (void *)other ? -1 :
4278 (void *)self > (void *)other ? 1 : 0;
4279}
4280
4281static PyObject *
4282slot_tp_repr(PyObject *self)
4283{
4284 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004285 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004286
Guido van Rossum60718732001-08-28 17:47:51 +00004287 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004288 if (func != NULL) {
4289 res = PyEval_CallObject(func, NULL);
4290 Py_DECREF(func);
4291 return res;
4292 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00004293 PyErr_Clear();
4294 return PyString_FromFormat("<%s object at %p>",
4295 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004296}
4297
4298static PyObject *
4299slot_tp_str(PyObject *self)
4300{
4301 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004302 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004303
Guido van Rossum60718732001-08-28 17:47:51 +00004304 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004305 if (func != NULL) {
4306 res = PyEval_CallObject(func, NULL);
4307 Py_DECREF(func);
4308 return res;
4309 }
4310 else {
4311 PyErr_Clear();
4312 return slot_tp_repr(self);
4313 }
4314}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004315
4316static long
4317slot_tp_hash(PyObject *self)
4318{
Tim Peters61ce0a92002-12-06 23:38:02 +00004319 PyObject *func;
Guido van Rossum60718732001-08-28 17:47:51 +00004320 static PyObject *hash_str, *eq_str, *cmp_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004321 long h;
4322
Guido van Rossum60718732001-08-28 17:47:51 +00004323 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004324
4325 if (func != NULL) {
Tim Peters61ce0a92002-12-06 23:38:02 +00004326 PyObject *res = PyEval_CallObject(func, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004327 Py_DECREF(func);
4328 if (res == NULL)
4329 return -1;
4330 h = PyInt_AsLong(res);
Tim Peters61ce0a92002-12-06 23:38:02 +00004331 Py_DECREF(res);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004332 }
4333 else {
4334 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004335 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004336 if (func == NULL) {
4337 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004338 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004339 }
4340 if (func != NULL) {
4341 Py_DECREF(func);
4342 PyErr_SetString(PyExc_TypeError, "unhashable type");
4343 return -1;
4344 }
4345 PyErr_Clear();
4346 h = _Py_HashPointer((void *)self);
4347 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004348 if (h == -1 && !PyErr_Occurred())
4349 h = -2;
4350 return h;
4351}
4352
4353static PyObject *
4354slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
4355{
Guido van Rossum60718732001-08-28 17:47:51 +00004356 static PyObject *call_str;
4357 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004358 PyObject *res;
4359
4360 if (meth == NULL)
4361 return NULL;
4362 res = PyObject_Call(meth, args, kwds);
4363 Py_DECREF(meth);
4364 return res;
4365}
4366
Guido van Rossum14a6f832001-10-17 13:59:09 +00004367/* There are two slot dispatch functions for tp_getattro.
4368
4369 - slot_tp_getattro() is used when __getattribute__ is overridden
4370 but no __getattr__ hook is present;
4371
4372 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
4373
Guido van Rossumc334df52002-04-04 23:44:47 +00004374 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
4375 detects the absence of __getattr__ and then installs the simpler slot if
4376 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00004377
Tim Peters6d6c1a32001-08-02 04:15:00 +00004378static PyObject *
4379slot_tp_getattro(PyObject *self, PyObject *name)
4380{
Guido van Rossum14a6f832001-10-17 13:59:09 +00004381 static PyObject *getattribute_str = NULL;
4382 return call_method(self, "__getattribute__", &getattribute_str,
4383 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004384}
4385
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004386static PyObject *
4387slot_tp_getattr_hook(PyObject *self, PyObject *name)
4388{
4389 PyTypeObject *tp = self->ob_type;
4390 PyObject *getattr, *getattribute, *res;
4391 static PyObject *getattribute_str = NULL;
4392 static PyObject *getattr_str = NULL;
4393
4394 if (getattr_str == NULL) {
4395 getattr_str = PyString_InternFromString("__getattr__");
4396 if (getattr_str == NULL)
4397 return NULL;
4398 }
4399 if (getattribute_str == NULL) {
4400 getattribute_str =
4401 PyString_InternFromString("__getattribute__");
4402 if (getattribute_str == NULL)
4403 return NULL;
4404 }
4405 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004406 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004407 /* No __getattr__ hook: use a simpler dispatcher */
4408 tp->tp_getattro = slot_tp_getattro;
4409 return slot_tp_getattro(self, name);
4410 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004411 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004412 if (getattribute == NULL ||
4413 (getattribute->ob_type == &PyWrapperDescr_Type &&
4414 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
4415 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004416 res = PyObject_GenericGetAttr(self, name);
4417 else
4418 res = PyObject_CallFunction(getattribute, "OO", self, name);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004419 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004420 PyErr_Clear();
4421 res = PyObject_CallFunction(getattr, "OO", self, name);
4422 }
4423 return res;
4424}
4425
Tim Peters6d6c1a32001-08-02 04:15:00 +00004426static int
4427slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
4428{
4429 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004430 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004431
4432 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004433 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004434 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004435 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004436 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004437 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004438 if (res == NULL)
4439 return -1;
4440 Py_DECREF(res);
4441 return 0;
4442}
4443
4444/* Map rich comparison operators to their __xx__ namesakes */
4445static char *name_op[] = {
4446 "__lt__",
4447 "__le__",
4448 "__eq__",
4449 "__ne__",
4450 "__gt__",
4451 "__ge__",
4452};
4453
4454static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00004455half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004456{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004457 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004458 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00004459
Guido van Rossum60718732001-08-28 17:47:51 +00004460 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004461 if (func == NULL) {
4462 PyErr_Clear();
4463 Py_INCREF(Py_NotImplemented);
4464 return Py_NotImplemented;
4465 }
4466 args = Py_BuildValue("(O)", other);
4467 if (args == NULL)
4468 res = NULL;
4469 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004470 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004471 Py_DECREF(args);
4472 }
4473 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004474 return res;
4475}
4476
Guido van Rossumb8f63662001-08-15 23:57:02 +00004477/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
4478static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
4479
4480static PyObject *
4481slot_tp_richcompare(PyObject *self, PyObject *other, int op)
4482{
4483 PyObject *res;
4484
4485 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
4486 res = half_richcompare(self, other, op);
4487 if (res != Py_NotImplemented)
4488 return res;
4489 Py_DECREF(res);
4490 }
4491 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
4492 res = half_richcompare(other, self, swapped_op[op]);
4493 if (res != Py_NotImplemented) {
4494 return res;
4495 }
4496 Py_DECREF(res);
4497 }
4498 Py_INCREF(Py_NotImplemented);
4499 return Py_NotImplemented;
4500}
4501
4502static PyObject *
4503slot_tp_iter(PyObject *self)
4504{
4505 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004506 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004507
Guido van Rossum60718732001-08-28 17:47:51 +00004508 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004509 if (func != NULL) {
Guido van Rossum84b2bed2002-08-16 17:01:09 +00004510 PyObject *args;
4511 args = res = PyTuple_New(0);
4512 if (args != NULL) {
4513 res = PyObject_Call(func, args, NULL);
4514 Py_DECREF(args);
4515 }
4516 Py_DECREF(func);
4517 return res;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004518 }
4519 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004520 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004521 if (func == NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00004522 PyErr_SetString(PyExc_TypeError,
4523 "iteration over non-sequence");
Guido van Rossumb8f63662001-08-15 23:57:02 +00004524 return NULL;
4525 }
4526 Py_DECREF(func);
4527 return PySeqIter_New(self);
4528}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004529
4530static PyObject *
4531slot_tp_iternext(PyObject *self)
4532{
Guido van Rossum2730b132001-08-28 18:22:14 +00004533 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00004534 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004535}
4536
Guido van Rossum1a493502001-08-17 16:47:50 +00004537static PyObject *
4538slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4539{
4540 PyTypeObject *tp = self->ob_type;
4541 PyObject *get;
4542 static PyObject *get_str = NULL;
4543
4544 if (get_str == NULL) {
4545 get_str = PyString_InternFromString("__get__");
4546 if (get_str == NULL)
4547 return NULL;
4548 }
4549 get = _PyType_Lookup(tp, get_str);
4550 if (get == NULL) {
4551 /* Avoid further slowdowns */
4552 if (tp->tp_descr_get == slot_tp_descr_get)
4553 tp->tp_descr_get = NULL;
4554 Py_INCREF(self);
4555 return self;
4556 }
Guido van Rossum2c252392001-08-24 10:13:31 +00004557 if (obj == NULL)
4558 obj = Py_None;
4559 if (type == NULL)
4560 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00004561 return PyObject_CallFunction(get, "OOO", self, obj, type);
4562}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004563
4564static int
4565slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
4566{
Guido van Rossum2c252392001-08-24 10:13:31 +00004567 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004568 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00004569
4570 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00004571 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004572 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00004573 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004574 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004575 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004576 if (res == NULL)
4577 return -1;
4578 Py_DECREF(res);
4579 return 0;
4580}
4581
4582static int
4583slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
4584{
Guido van Rossum60718732001-08-28 17:47:51 +00004585 static PyObject *init_str;
4586 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004587 PyObject *res;
4588
4589 if (meth == NULL)
4590 return -1;
4591 res = PyObject_Call(meth, args, kwds);
4592 Py_DECREF(meth);
4593 if (res == NULL)
4594 return -1;
4595 Py_DECREF(res);
4596 return 0;
4597}
4598
4599static PyObject *
4600slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4601{
Guido van Rossum7bed2132002-08-08 21:57:53 +00004602 static PyObject *new_str;
4603 PyObject *func;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004604 PyObject *newargs, *x;
4605 int i, n;
4606
Guido van Rossum7bed2132002-08-08 21:57:53 +00004607 if (new_str == NULL) {
4608 new_str = PyString_InternFromString("__new__");
4609 if (new_str == NULL)
4610 return NULL;
4611 }
4612 func = PyObject_GetAttr((PyObject *)type, new_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004613 if (func == NULL)
4614 return NULL;
4615 assert(PyTuple_Check(args));
4616 n = PyTuple_GET_SIZE(args);
4617 newargs = PyTuple_New(n+1);
4618 if (newargs == NULL)
4619 return NULL;
4620 Py_INCREF(type);
4621 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
4622 for (i = 0; i < n; i++) {
4623 x = PyTuple_GET_ITEM(args, i);
4624 Py_INCREF(x);
4625 PyTuple_SET_ITEM(newargs, i+1, x);
4626 }
4627 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00004628 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004629 Py_DECREF(func);
4630 return x;
4631}
4632
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004633static void
4634slot_tp_del(PyObject *self)
4635{
4636 static PyObject *del_str = NULL;
4637 PyObject *del, *res;
4638 PyObject *error_type, *error_value, *error_traceback;
4639
4640 /* Temporarily resurrect the object. */
4641 assert(self->ob_refcnt == 0);
4642 self->ob_refcnt = 1;
4643
4644 /* Save the current exception, if any. */
4645 PyErr_Fetch(&error_type, &error_value, &error_traceback);
4646
4647 /* Execute __del__ method, if any. */
4648 del = lookup_maybe(self, "__del__", &del_str);
4649 if (del != NULL) {
4650 res = PyEval_CallObject(del, NULL);
4651 if (res == NULL)
4652 PyErr_WriteUnraisable(del);
4653 else
4654 Py_DECREF(res);
4655 Py_DECREF(del);
4656 }
4657
4658 /* Restore the saved exception. */
4659 PyErr_Restore(error_type, error_value, error_traceback);
4660
4661 /* Undo the temporary resurrection; can't use DECREF here, it would
4662 * cause a recursive call.
4663 */
4664 assert(self->ob_refcnt > 0);
4665 if (--self->ob_refcnt == 0)
4666 return; /* this is the normal path out */
4667
4668 /* __del__ resurrected it! Make it look like the original Py_DECREF
4669 * never happened.
4670 */
4671 {
4672 int refcnt = self->ob_refcnt;
4673 _Py_NewReference(self);
4674 self->ob_refcnt = refcnt;
4675 }
4676 assert(!PyType_IS_GC(self->ob_type) ||
4677 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
4678 /* If Py_REF_DEBUG, the original decref dropped _Py_RefTotal, but
4679 * _Py_NewReference bumped it again, so that's a wash.
4680 * If Py_TRACE_REFS, _Py_NewReference re-added self to the object
4681 * chain, so no more to do there either.
4682 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
4683 * _Py_NewReference bumped tp_allocs: both of those need to be
4684 * undone.
4685 */
4686#ifdef COUNT_ALLOCS
4687 --self->ob_type->tp_frees;
4688 --self->ob_type->tp_allocs;
4689#endif
4690}
4691
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004692
4693/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
Tim Petersbf9b2442003-03-23 05:35:36 +00004694 functions. The offsets here are relative to the 'PyHeapTypeObject'
Guido van Rossume5c691a2003-03-07 15:13:17 +00004695 structure, which incorporates the additional structures used for numbers,
4696 sequences and mappings.
4697 Note that multiple names may map to the same slot (e.g. __eq__,
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004698 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00004699 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
4700 terminated with an all-zero entry. (This table is further initialized and
4701 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004702
Guido van Rossum6d204072001-10-21 00:44:31 +00004703typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004704
4705#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00004706#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004707#undef ETSLOT
4708#undef SQSLOT
4709#undef MPSLOT
4710#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00004711#undef UNSLOT
4712#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004713#undef BINSLOT
4714#undef RBINSLOT
4715
Guido van Rossum6d204072001-10-21 00:44:31 +00004716#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004717 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
4718 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00004719#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
4720 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004721 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00004722#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Guido van Rossume5c691a2003-03-07 15:13:17 +00004723 {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004724 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00004725#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4726 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
4727#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4728 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
4729#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4730 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
4731#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4732 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
4733 "x." NAME "() <==> " DOC)
4734#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4735 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
4736 "x." NAME "(y) <==> x" DOC "y")
4737#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
4738 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
4739 "x." NAME "(y) <==> x" DOC "y")
4740#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
4741 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
4742 "x." NAME "(y) <==> y" DOC "x")
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004743
4744static slotdef slotdefs[] = {
Guido van Rossum6d204072001-10-21 00:44:31 +00004745 SQSLOT("__len__", sq_length, slot_sq_length, wrap_inquiry,
4746 "x.__len__() <==> len(x)"),
4747 SQSLOT("__add__", sq_concat, slot_sq_concat, wrap_binaryfunc,
4748 "x.__add__(y) <==> x+y"),
4749 SQSLOT("__mul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
4750 "x.__mul__(n) <==> x*n"),
4751 SQSLOT("__rmul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
4752 "x.__rmul__(n) <==> n*x"),
4753 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
4754 "x.__getitem__(y) <==> x[y]"),
4755 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_intintargfunc,
4756 "x.__getslice__(i, j) <==> x[i:j]"),
4757 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
4758 "x.__setitem__(i, y) <==> x[i]=y"),
4759 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
4760 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004761 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Guido van Rossum6d204072001-10-21 00:44:31 +00004762 wrap_intintobjargproc,
4763 "x.__setslice__(i, j, y) <==> x[i:j]=y"),
4764 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
4765 "x.__delslice__(i, j) <==> del x[i:j]"),
4766 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
4767 "x.__contains__(y) <==> y in x"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004768 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat,
Guido van Rossum6d204072001-10-21 00:44:31 +00004769 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004770 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat,
Guido van Rossum6d204072001-10-21 00:44:31 +00004771 wrap_intargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004772
Guido van Rossum6d204072001-10-21 00:44:31 +00004773 MPSLOT("__len__", mp_length, slot_mp_length, wrap_inquiry,
4774 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00004775 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004776 wrap_binaryfunc,
4777 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004778 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004779 wrap_objobjargproc,
4780 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004781 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004782 wrap_delitem,
4783 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004784
Guido van Rossum6d204072001-10-21 00:44:31 +00004785 BINSLOT("__add__", nb_add, slot_nb_add,
4786 "+"),
4787 RBINSLOT("__radd__", nb_add, slot_nb_add,
4788 "+"),
4789 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
4790 "-"),
4791 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
4792 "-"),
4793 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
4794 "*"),
4795 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
4796 "*"),
4797 BINSLOT("__div__", nb_divide, slot_nb_divide,
4798 "/"),
4799 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
4800 "/"),
4801 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
4802 "%"),
4803 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
4804 "%"),
4805 BINSLOT("__divmod__", nb_divmod, slot_nb_divmod,
4806 "divmod(x, y)"),
4807 RBINSLOT("__rdivmod__", nb_divmod, slot_nb_divmod,
4808 "divmod(y, x)"),
4809 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
4810 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
4811 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
4812 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
4813 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
4814 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
4815 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
4816 "abs(x)"),
Guido van Rossumdfce3bf2002-03-10 14:11:16 +00004817 UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquiry,
Guido van Rossum6d204072001-10-21 00:44:31 +00004818 "x != 0"),
4819 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
4820 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
4821 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
4822 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
4823 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
4824 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
4825 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
4826 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
4827 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
4828 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
4829 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
4830 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
4831 "x.__coerce__(y) <==> coerce(x, y)"),
4832 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
4833 "int(x)"),
4834 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
4835 "long(x)"),
4836 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
4837 "float(x)"),
4838 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
4839 "oct(x)"),
4840 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
4841 "hex(x)"),
4842 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
4843 wrap_binaryfunc, "+"),
4844 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
4845 wrap_binaryfunc, "-"),
4846 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
4847 wrap_binaryfunc, "*"),
4848 IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
4849 wrap_binaryfunc, "/"),
4850 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
4851 wrap_binaryfunc, "%"),
4852 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
Guido van Rossum6e5680f2002-10-15 01:01:53 +00004853 wrap_binaryfunc, "**"),
Guido van Rossum6d204072001-10-21 00:44:31 +00004854 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
4855 wrap_binaryfunc, "<<"),
4856 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
4857 wrap_binaryfunc, ">>"),
4858 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
4859 wrap_binaryfunc, "&"),
4860 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
4861 wrap_binaryfunc, "^"),
4862 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
4863 wrap_binaryfunc, "|"),
4864 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
4865 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
4866 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
4867 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
4868 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
4869 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
4870 IBSLOT("__itruediv__", nb_inplace_true_divide,
4871 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004872
Guido van Rossum6d204072001-10-21 00:44:31 +00004873 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
4874 "x.__str__() <==> str(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00004875 TPSLOT("__str__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00004876 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
4877 "x.__repr__() <==> repr(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00004878 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00004879 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
4880 "x.__cmp__(y) <==> cmp(x,y)"),
4881 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
4882 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00004883 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
4884 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004885 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00004886 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
4887 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
4888 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
4889 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
4890 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
4891 "x.__setattr__('name', value) <==> x.name = value"),
4892 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
4893 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
4894 "x.__delattr__('name') <==> del x.name"),
4895 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
4896 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
4897 "x.__lt__(y) <==> x<y"),
4898 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
4899 "x.__le__(y) <==> x<=y"),
4900 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
4901 "x.__eq__(y) <==> x==y"),
4902 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
4903 "x.__ne__(y) <==> x!=y"),
4904 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
4905 "x.__gt__(y) <==> x>y"),
4906 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
4907 "x.__ge__(y) <==> x>=y"),
4908 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
4909 "x.__iter__() <==> iter(x)"),
4910 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
4911 "x.next() -> the next value, or raise StopIteration"),
4912 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
4913 "descr.__get__(obj[, type]) -> value"),
4914 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
4915 "descr.__set__(obj, value)"),
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004916 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
4917 wrap_descr_delete, "descr.__delete__(obj)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00004918 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00004919 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00004920 "see x.__class__.__doc__ for signature",
4921 PyWrapperFlag_KEYWORDS),
4922 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004923 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004924 {NULL}
4925};
4926
Guido van Rossumc334df52002-04-04 23:44:47 +00004927/* Given a type pointer and an offset gotten from a slotdef entry, return a
4928 pointer to the actual slot. This is not quite the same as simply adding
4929 the offset to the type pointer, since it takes care to indirect through the
4930 proper indirection pointer (as_buffer, etc.); it returns NULL if the
4931 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004932static void **
4933slotptr(PyTypeObject *type, int offset)
4934{
4935 char *ptr;
4936
Guido van Rossume5c691a2003-03-07 15:13:17 +00004937 /* Note: this depends on the order of the members of PyHeapTypeObject! */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004938 assert(offset >= 0);
Guido van Rossume5c691a2003-03-07 15:13:17 +00004939 assert(offset < offsetof(PyHeapTypeObject, as_buffer));
4940 if (offset >= offsetof(PyHeapTypeObject, as_sequence)) {
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004941 ptr = (void *)type->tp_as_sequence;
Guido van Rossume5c691a2003-03-07 15:13:17 +00004942 offset -= offsetof(PyHeapTypeObject, as_sequence);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004943 }
Guido van Rossume5c691a2003-03-07 15:13:17 +00004944 else if (offset >= offsetof(PyHeapTypeObject, as_mapping)) {
Guido van Rossum09638c12002-06-13 19:17:46 +00004945 ptr = (void *)type->tp_as_mapping;
Guido van Rossume5c691a2003-03-07 15:13:17 +00004946 offset -= offsetof(PyHeapTypeObject, as_mapping);
Guido van Rossum09638c12002-06-13 19:17:46 +00004947 }
Guido van Rossume5c691a2003-03-07 15:13:17 +00004948 else if (offset >= offsetof(PyHeapTypeObject, as_number)) {
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004949 ptr = (void *)type->tp_as_number;
Guido van Rossume5c691a2003-03-07 15:13:17 +00004950 offset -= offsetof(PyHeapTypeObject, as_number);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004951 }
4952 else {
4953 ptr = (void *)type;
4954 }
4955 if (ptr != NULL)
4956 ptr += offset;
4957 return (void **)ptr;
4958}
Guido van Rossumf040ede2001-08-07 16:40:56 +00004959
Guido van Rossumc334df52002-04-04 23:44:47 +00004960/* Length of array of slotdef pointers used to store slots with the
4961 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
4962 the same __name__, for any __name__. Since that's a static property, it is
4963 appropriate to declare fixed-size arrays for this. */
4964#define MAX_EQUIV 10
4965
4966/* Return a slot pointer for a given name, but ONLY if the attribute has
4967 exactly one slot function. The name must be an interned string. */
4968static void **
4969resolve_slotdups(PyTypeObject *type, PyObject *name)
4970{
4971 /* XXX Maybe this could be optimized more -- but is it worth it? */
4972
4973 /* pname and ptrs act as a little cache */
4974 static PyObject *pname;
4975 static slotdef *ptrs[MAX_EQUIV];
4976 slotdef *p, **pp;
4977 void **res, **ptr;
4978
4979 if (pname != name) {
4980 /* Collect all slotdefs that match name into ptrs. */
4981 pname = name;
4982 pp = ptrs;
4983 for (p = slotdefs; p->name_strobj; p++) {
4984 if (p->name_strobj == name)
4985 *pp++ = p;
4986 }
4987 *pp = NULL;
4988 }
4989
4990 /* Look in all matching slots of the type; if exactly one of these has
4991 a filled-in slot, return its value. Otherwise return NULL. */
4992 res = NULL;
4993 for (pp = ptrs; *pp; pp++) {
4994 ptr = slotptr(type, (*pp)->offset);
4995 if (ptr == NULL || *ptr == NULL)
4996 continue;
4997 if (res != NULL)
4998 return NULL;
4999 res = ptr;
5000 }
5001 return res;
5002}
5003
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005004/* Common code for update_slots_callback() and fixup_slot_dispatchers(). This
Guido van Rossumc334df52002-04-04 23:44:47 +00005005 does some incredibly complex thinking and then sticks something into the
5006 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
5007 interests, and then stores a generic wrapper or a specific function into
5008 the slot.) Return a pointer to the next slotdef with a different offset,
5009 because that's convenient for fixup_slot_dispatchers(). */
5010static slotdef *
5011update_one_slot(PyTypeObject *type, slotdef *p)
5012{
5013 PyObject *descr;
5014 PyWrapperDescrObject *d;
5015 void *generic = NULL, *specific = NULL;
5016 int use_generic = 0;
5017 int offset = p->offset;
5018 void **ptr = slotptr(type, offset);
5019
5020 if (ptr == NULL) {
5021 do {
5022 ++p;
5023 } while (p->offset == offset);
5024 return p;
5025 }
5026 do {
5027 descr = _PyType_Lookup(type, p->name_strobj);
5028 if (descr == NULL)
5029 continue;
5030 if (descr->ob_type == &PyWrapperDescr_Type) {
5031 void **tptr = resolve_slotdups(type, p->name_strobj);
5032 if (tptr == NULL || tptr == ptr)
5033 generic = p->function;
5034 d = (PyWrapperDescrObject *)descr;
5035 if (d->d_base->wrapper == p->wrapper &&
5036 PyType_IsSubtype(type, d->d_type))
5037 {
5038 if (specific == NULL ||
5039 specific == d->d_wrapped)
5040 specific = d->d_wrapped;
5041 else
5042 use_generic = 1;
5043 }
5044 }
Guido van Rossum721f62e2002-08-09 02:14:34 +00005045 else if (descr->ob_type == &PyCFunction_Type &&
5046 PyCFunction_GET_FUNCTION(descr) ==
5047 (PyCFunction)tp_new_wrapper &&
5048 strcmp(p->name, "__new__") == 0)
5049 {
5050 /* The __new__ wrapper is not a wrapper descriptor,
5051 so must be special-cased differently.
5052 If we don't do this, creating an instance will
5053 always use slot_tp_new which will look up
5054 __new__ in the MRO which will call tp_new_wrapper
5055 which will look through the base classes looking
5056 for a static base and call its tp_new (usually
5057 PyType_GenericNew), after performing various
5058 sanity checks and constructing a new argument
5059 list. Cut all that nonsense short -- this speeds
5060 up instance creation tremendously. */
5061 specific = type->tp_new;
5062 /* XXX I'm not 100% sure that there isn't a hole
5063 in this reasoning that requires additional
5064 sanity checks. I'll buy the first person to
5065 point out a bug in this reasoning a beer. */
5066 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005067 else {
5068 use_generic = 1;
5069 generic = p->function;
5070 }
5071 } while ((++p)->offset == offset);
5072 if (specific && !use_generic)
5073 *ptr = specific;
5074 else
5075 *ptr = generic;
5076 return p;
5077}
5078
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005079/* In the type, update the slots whose slotdefs are gathered in the pp array.
5080 This is a callback for update_subclasses(). */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005081static int
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005082update_slots_callback(PyTypeObject *type, void *data)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005083{
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005084 slotdef **pp = (slotdef **)data;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005085
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005086 for (; *pp; pp++)
Guido van Rossumc334df52002-04-04 23:44:47 +00005087 update_one_slot(type, *pp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005088 return 0;
5089}
5090
Guido van Rossumc334df52002-04-04 23:44:47 +00005091/* Comparison function for qsort() to compare slotdefs by their offset, and
5092 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005093static int
5094slotdef_cmp(const void *aa, const void *bb)
5095{
5096 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
5097 int c = a->offset - b->offset;
5098 if (c != 0)
5099 return c;
5100 else
5101 return a - b;
5102}
5103
Guido van Rossumc334df52002-04-04 23:44:47 +00005104/* Initialize the slotdefs table by adding interned string objects for the
5105 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005106static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005107init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005108{
5109 slotdef *p;
5110 static int initialized = 0;
5111
5112 if (initialized)
5113 return;
5114 for (p = slotdefs; p->name; p++) {
5115 p->name_strobj = PyString_InternFromString(p->name);
5116 if (!p->name_strobj)
Guido van Rossumc334df52002-04-04 23:44:47 +00005117 Py_FatalError("Out of memory interning slotdef names");
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005118 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005119 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
5120 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005121 initialized = 1;
5122}
5123
Guido van Rossumc334df52002-04-04 23:44:47 +00005124/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005125static int
5126update_slot(PyTypeObject *type, PyObject *name)
5127{
Guido van Rossumc334df52002-04-04 23:44:47 +00005128 slotdef *ptrs[MAX_EQUIV];
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005129 slotdef *p;
5130 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005131 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005132
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005133 init_slotdefs();
5134 pp = ptrs;
5135 for (p = slotdefs; p->name; p++) {
5136 /* XXX assume name is interned! */
5137 if (p->name_strobj == name)
5138 *pp++ = p;
5139 }
5140 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005141 for (pp = ptrs; *pp; pp++) {
5142 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005143 offset = p->offset;
5144 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005145 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005146 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005147 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005148 if (ptrs[0] == NULL)
5149 return 0; /* Not an attribute that affects any slots */
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005150 return update_subclasses(type, name,
5151 update_slots_callback, (void *)ptrs);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005152}
5153
Guido van Rossumc334df52002-04-04 23:44:47 +00005154/* Store the proper functions in the slot dispatches at class (type)
5155 definition time, based upon which operations the class overrides in its
5156 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00005157static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005158fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005159{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005160 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005161
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005162 init_slotdefs();
Guido van Rossumc334df52002-04-04 23:44:47 +00005163 for (p = slotdefs; p->name; )
5164 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005165}
Guido van Rossum705f0f52001-08-24 16:47:00 +00005166
Michael W. Hudson98bbc492002-11-26 14:47:27 +00005167static void
5168update_all_slots(PyTypeObject* type)
5169{
5170 slotdef *p;
5171
5172 init_slotdefs();
5173 for (p = slotdefs; p->name; p++) {
5174 /* update_slot returns int but can't actually fail */
5175 update_slot(type, p->name_strobj);
5176 }
5177}
5178
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005179/* recurse_down_subclasses() and update_subclasses() are mutually
5180 recursive functions to call a callback for all subclasses,
5181 but refraining from recursing into subclasses that define 'name'. */
5182
5183static int
5184update_subclasses(PyTypeObject *type, PyObject *name,
5185 update_callback callback, void *data)
5186{
5187 if (callback(type, data) < 0)
5188 return -1;
5189 return recurse_down_subclasses(type, name, callback, data);
5190}
5191
5192static int
5193recurse_down_subclasses(PyTypeObject *type, PyObject *name,
5194 update_callback callback, void *data)
5195{
5196 PyTypeObject *subclass;
5197 PyObject *ref, *subclasses, *dict;
5198 int i, n;
5199
5200 subclasses = type->tp_subclasses;
5201 if (subclasses == NULL)
5202 return 0;
5203 assert(PyList_Check(subclasses));
5204 n = PyList_GET_SIZE(subclasses);
5205 for (i = 0; i < n; i++) {
5206 ref = PyList_GET_ITEM(subclasses, i);
5207 assert(PyWeakref_CheckRef(ref));
5208 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
5209 assert(subclass != NULL);
5210 if ((PyObject *)subclass == Py_None)
5211 continue;
5212 assert(PyType_Check(subclass));
5213 /* Avoid recursing down into unaffected classes */
5214 dict = subclass->tp_dict;
5215 if (dict != NULL && PyDict_Check(dict) &&
5216 PyDict_GetItem(dict, name) != NULL)
5217 continue;
5218 if (update_subclasses(subclass, name, callback, data) < 0)
5219 return -1;
5220 }
5221 return 0;
5222}
5223
Guido van Rossum6d204072001-10-21 00:44:31 +00005224/* This function is called by PyType_Ready() to populate the type's
5225 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00005226 function slot (like tp_repr) that's defined in the type, one or more
5227 corresponding descriptors are added in the type's tp_dict dictionary
5228 under the appropriate name (like __repr__). Some function slots
5229 cause more than one descriptor to be added (for example, the nb_add
5230 slot adds both __add__ and __radd__ descriptors) and some function
5231 slots compete for the same descriptor (for example both sq_item and
5232 mp_subscript generate a __getitem__ descriptor).
5233
5234 In the latter case, the first slotdef entry encoutered wins. Since
Tim Petersbf9b2442003-03-23 05:35:36 +00005235 slotdef entries are sorted by the offset of the slot in the
Guido van Rossume5c691a2003-03-07 15:13:17 +00005236 PyHeapTypeObject, this gives us some control over disambiguating
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005237 between competing slots: the members of PyHeapTypeObject are listed
5238 from most general to least general, so the most general slot is
5239 preferred. In particular, because as_mapping comes before as_sequence,
5240 for a type that defines both mp_subscript and sq_item, mp_subscript
5241 wins.
Guido van Rossum09638c12002-06-13 19:17:46 +00005242
5243 This only adds new descriptors and doesn't overwrite entries in
5244 tp_dict that were previously defined. The descriptors contain a
5245 reference to the C function they must call, so that it's safe if they
5246 are copied into a subtype's __dict__ and the subtype has a different
5247 C function in its slot -- calling the method defined by the
5248 descriptor will call the C function that was used to create it,
5249 rather than the C function present in the slot when it is called.
5250 (This is important because a subtype may have a C function in the
5251 slot that calls the method from the dictionary, and we want to avoid
5252 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00005253
5254static int
5255add_operators(PyTypeObject *type)
5256{
5257 PyObject *dict = type->tp_dict;
5258 slotdef *p;
5259 PyObject *descr;
5260 void **ptr;
5261
5262 init_slotdefs();
5263 for (p = slotdefs; p->name; p++) {
5264 if (p->wrapper == NULL)
5265 continue;
5266 ptr = slotptr(type, p->offset);
5267 if (!ptr || !*ptr)
5268 continue;
5269 if (PyDict_GetItem(dict, p->name_strobj))
5270 continue;
5271 descr = PyDescr_NewWrapper(type, p, *ptr);
5272 if (descr == NULL)
5273 return -1;
5274 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
5275 return -1;
5276 Py_DECREF(descr);
5277 }
5278 if (type->tp_new != NULL) {
5279 if (add_tp_new_wrapper(type) < 0)
5280 return -1;
5281 }
5282 return 0;
5283}
5284
Guido van Rossum705f0f52001-08-24 16:47:00 +00005285
5286/* Cooperative 'super' */
5287
5288typedef struct {
5289 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00005290 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005291 PyObject *obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005292 PyTypeObject *obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005293} superobject;
5294
Guido van Rossum6f799372001-09-20 20:46:19 +00005295static PyMemberDef super_members[] = {
5296 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
5297 "the class invoking super()"},
5298 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
5299 "the instance invoking super(); may be None"},
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005300 {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
5301 "the type of the the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005302 {0}
5303};
5304
Guido van Rossum705f0f52001-08-24 16:47:00 +00005305static void
5306super_dealloc(PyObject *self)
5307{
5308 superobject *su = (superobject *)self;
5309
Guido van Rossum048eb752001-10-02 21:24:57 +00005310 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005311 Py_XDECREF(su->obj);
5312 Py_XDECREF(su->type);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005313 Py_XDECREF(su->obj_type);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005314 self->ob_type->tp_free(self);
5315}
5316
5317static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005318super_repr(PyObject *self)
5319{
5320 superobject *su = (superobject *)self;
5321
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005322 if (su->obj_type)
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005323 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005324 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005325 su->type ? su->type->tp_name : "NULL",
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005326 su->obj_type->tp_name);
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005327 else
5328 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005329 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005330 su->type ? su->type->tp_name : "NULL");
5331}
5332
5333static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00005334super_getattro(PyObject *self, PyObject *name)
5335{
5336 superobject *su = (superobject *)self;
5337
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005338 if (su->obj_type != NULL) {
Tim Petersa91e9642001-11-14 23:32:33 +00005339 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005340 PyTypeObject *starttype;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005341 descrgetfunc f;
5342 int i, n;
5343
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005344 starttype = su->obj_type;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005345 mro = starttype->tp_mro;
5346
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005347 if (mro == NULL)
5348 n = 0;
5349 else {
5350 assert(PyTuple_Check(mro));
5351 n = PyTuple_GET_SIZE(mro);
5352 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005353 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00005354 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00005355 break;
5356 }
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005357#if 0
Guido van Rossume705ef12001-08-29 15:47:06 +00005358 if (i >= n && PyType_Check(su->obj)) {
Guido van Rossum155db9a2002-04-02 17:53:47 +00005359 starttype = (PyTypeObject *)(su->obj);
5360 mro = starttype->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005361 if (mro == NULL)
5362 n = 0;
5363 else {
5364 assert(PyTuple_Check(mro));
5365 n = PyTuple_GET_SIZE(mro);
5366 }
Guido van Rossume705ef12001-08-29 15:47:06 +00005367 for (i = 0; i < n; i++) {
5368 if ((PyObject *)(su->type) ==
5369 PyTuple_GET_ITEM(mro, i))
5370 break;
5371 }
Guido van Rossume705ef12001-08-29 15:47:06 +00005372 }
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005373#endif
Guido van Rossum705f0f52001-08-24 16:47:00 +00005374 i++;
5375 res = NULL;
5376 for (; i < n; i++) {
5377 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00005378 if (PyType_Check(tmp))
5379 dict = ((PyTypeObject *)tmp)->tp_dict;
5380 else if (PyClass_Check(tmp))
5381 dict = ((PyClassObject *)tmp)->cl_dict;
5382 else
5383 continue;
5384 res = PyDict_GetItem(dict, name);
Guido van Rossum5b443c62001-12-03 15:38:28 +00005385 if (res != NULL && !PyDescr_IsData(res)) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00005386 Py_INCREF(res);
5387 f = res->ob_type->tp_descr_get;
5388 if (f != NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00005389 tmp = f(res, su->obj,
5390 (PyObject *)starttype);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005391 Py_DECREF(res);
5392 res = tmp;
5393 }
5394 return res;
5395 }
5396 }
5397 }
5398 return PyObject_GenericGetAttr(self, name);
5399}
5400
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005401static PyTypeObject *
Guido van Rossum5b443c62001-12-03 15:38:28 +00005402supercheck(PyTypeObject *type, PyObject *obj)
5403{
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005404 /* Check that a super() call makes sense. Return a type object.
5405
5406 obj can be a new-style class, or an instance of one:
5407
5408 - If it is a class, it must be a subclass of 'type'. This case is
5409 used for class methods; the return value is obj.
5410
5411 - If it is an instance, it must be an instance of 'type'. This is
5412 the normal case; the return value is obj.__class__.
5413
5414 But... when obj is an instance, we want to allow for the case where
5415 obj->ob_type is not a subclass of type, but obj.__class__ is!
5416 This will allow using super() with a proxy for obj.
5417 */
5418
Guido van Rossum8e80a722003-02-18 19:22:22 +00005419 /* Check for first bullet above (special case) */
5420 if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
5421 Py_INCREF(obj);
5422 return (PyTypeObject *)obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005423 }
Guido van Rossum8e80a722003-02-18 19:22:22 +00005424
5425 /* Normal case */
5426 if (PyType_IsSubtype(obj->ob_type, type)) {
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005427 Py_INCREF(obj->ob_type);
5428 return obj->ob_type;
5429 }
5430 else {
5431 /* Try the slow way */
5432 static PyObject *class_str = NULL;
5433 PyObject *class_attr;
5434
5435 if (class_str == NULL) {
5436 class_str = PyString_FromString("__class__");
5437 if (class_str == NULL)
5438 return NULL;
5439 }
5440
5441 class_attr = PyObject_GetAttr(obj, class_str);
5442
5443 if (class_attr != NULL &&
5444 PyType_Check(class_attr) &&
5445 (PyTypeObject *)class_attr != obj->ob_type)
5446 {
5447 int ok = PyType_IsSubtype(
5448 (PyTypeObject *)class_attr, type);
5449 if (ok)
5450 return (PyTypeObject *)class_attr;
5451 }
5452
5453 if (class_attr == NULL)
5454 PyErr_Clear();
5455 else
5456 Py_DECREF(class_attr);
5457 }
5458
Tim Peters97e5ff52003-02-18 19:32:50 +00005459 PyErr_SetString(PyExc_TypeError,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005460 "super(type, obj): "
5461 "obj must be an instance or subtype of type");
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005462 return NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005463}
5464
Guido van Rossum705f0f52001-08-24 16:47:00 +00005465static PyObject *
5466super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5467{
5468 superobject *su = (superobject *)self;
5469 superobject *new;
5470
5471 if (obj == NULL || obj == Py_None || su->obj != NULL) {
5472 /* Not binding to an object, or already bound */
5473 Py_INCREF(self);
5474 return self;
5475 }
Guido van Rossum5b443c62001-12-03 15:38:28 +00005476 if (su->ob_type != &PySuper_Type)
5477 /* If su is an instance of a subclass of super,
5478 call its type */
5479 return PyObject_CallFunction((PyObject *)su->ob_type,
5480 "OO", su->type, obj);
5481 else {
5482 /* Inline the common case */
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005483 PyTypeObject *obj_type = supercheck(su->type, obj);
5484 if (obj_type == NULL)
Guido van Rossum5b443c62001-12-03 15:38:28 +00005485 return NULL;
5486 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
5487 NULL, NULL);
5488 if (new == NULL)
5489 return NULL;
5490 Py_INCREF(su->type);
5491 Py_INCREF(obj);
5492 new->type = su->type;
5493 new->obj = obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005494 new->obj_type = obj_type;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005495 return (PyObject *)new;
5496 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005497}
5498
5499static int
5500super_init(PyObject *self, PyObject *args, PyObject *kwds)
5501{
5502 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00005503 PyTypeObject *type;
5504 PyObject *obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005505 PyTypeObject *obj_type = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005506
5507 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
5508 return -1;
5509 if (obj == Py_None)
5510 obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005511 if (obj != NULL) {
5512 obj_type = supercheck(type, obj);
5513 if (obj_type == NULL)
5514 return -1;
5515 Py_INCREF(obj);
5516 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005517 Py_INCREF(type);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005518 su->type = type;
5519 su->obj = obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005520 su->obj_type = obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005521 return 0;
5522}
5523
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005524PyDoc_STRVAR(super_doc,
Guido van Rossum705f0f52001-08-24 16:47:00 +00005525"super(type) -> unbound super object\n"
5526"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00005527"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00005528"Typical use to call a cooperative superclass method:\n"
5529"class C(B):\n"
5530" def meth(self, arg):\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005531" super(C, self).meth(arg)");
Guido van Rossum705f0f52001-08-24 16:47:00 +00005532
Guido van Rossum048eb752001-10-02 21:24:57 +00005533static int
5534super_traverse(PyObject *self, visitproc visit, void *arg)
5535{
5536 superobject *su = (superobject *)self;
5537 int err;
5538
5539#define VISIT(SLOT) \
5540 if (SLOT) { \
5541 err = visit((PyObject *)(SLOT), arg); \
5542 if (err) \
5543 return err; \
5544 }
5545
5546 VISIT(su->obj);
5547 VISIT(su->type);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005548 VISIT(su->obj_type);
Guido van Rossum048eb752001-10-02 21:24:57 +00005549
5550#undef VISIT
5551
5552 return 0;
5553}
5554
Guido van Rossum705f0f52001-08-24 16:47:00 +00005555PyTypeObject PySuper_Type = {
5556 PyObject_HEAD_INIT(&PyType_Type)
5557 0, /* ob_size */
5558 "super", /* tp_name */
5559 sizeof(superobject), /* tp_basicsize */
5560 0, /* tp_itemsize */
5561 /* methods */
5562 super_dealloc, /* tp_dealloc */
5563 0, /* tp_print */
5564 0, /* tp_getattr */
5565 0, /* tp_setattr */
5566 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005567 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005568 0, /* tp_as_number */
5569 0, /* tp_as_sequence */
5570 0, /* tp_as_mapping */
5571 0, /* tp_hash */
5572 0, /* tp_call */
5573 0, /* tp_str */
5574 super_getattro, /* tp_getattro */
5575 0, /* tp_setattro */
5576 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00005577 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
5578 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005579 super_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00005580 super_traverse, /* tp_traverse */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005581 0, /* tp_clear */
5582 0, /* tp_richcompare */
5583 0, /* tp_weaklistoffset */
5584 0, /* tp_iter */
5585 0, /* tp_iternext */
5586 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005587 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005588 0, /* tp_getset */
5589 0, /* tp_base */
5590 0, /* tp_dict */
5591 super_descr_get, /* tp_descr_get */
5592 0, /* tp_descr_set */
5593 0, /* tp_dictoffset */
5594 super_init, /* tp_init */
5595 PyType_GenericAlloc, /* tp_alloc */
5596 PyType_GenericNew, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00005597 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005598};