blob: 1c1b1974164329778b1c37ae2cf20f627b23f16e [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* Type object implementation */
2
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003#include "Python.h"
Tim Peters6d6c1a32001-08-02 04:15:00 +00004#include "structmember.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00005
Guido van Rossum9923ffe2002-06-04 19:52:53 +00006#include <ctype.h>
7
Guido van Rossum6f799372001-09-20 20:46:19 +00008static PyMemberDef type_members[] = {
Tim Peters6d6c1a32001-08-02 04:15:00 +00009 {"__basicsize__", T_INT, offsetof(PyTypeObject,tp_basicsize),READONLY},
10 {"__itemsize__", T_INT, offsetof(PyTypeObject, tp_itemsize), READONLY},
11 {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY},
Guido van Rossum9676b222001-08-17 20:32:36 +000012 {"__weakrefoffset__", T_LONG,
Tim Peters6d6c1a32001-08-02 04:15:00 +000013 offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
14 {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY},
15 {"__dictoffset__", T_LONG,
16 offsetof(PyTypeObject, tp_dictoffset), READONLY},
Tim Peters6d6c1a32001-08-02 04:15:00 +000017 {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY},
18 {0}
19};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000020
Guido van Rossumc0b618a1997-05-02 03:12:38 +000021static PyObject *
Guido van Rossumc3542212001-08-16 09:18:56 +000022type_name(PyTypeObject *type, void *context)
23{
24 char *s;
25
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +000026 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
Guido van Rossume5c691a2003-03-07 15:13:17 +000027 PyHeapTypeObject* et = (PyHeapTypeObject*)type;
Tim Petersea7f75d2002-12-07 21:39:16 +000028
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +000029 Py_INCREF(et->name);
30 return et->name;
31 }
32 else {
33 s = strrchr(type->tp_name, '.');
34 if (s == NULL)
35 s = type->tp_name;
36 else
37 s++;
38 return PyString_FromString(s);
39 }
Guido van Rossumc3542212001-08-16 09:18:56 +000040}
41
Michael W. Hudson98bbc492002-11-26 14:47:27 +000042static int
43type_set_name(PyTypeObject *type, PyObject *value, void *context)
44{
Guido van Rossume5c691a2003-03-07 15:13:17 +000045 PyHeapTypeObject* et;
Michael W. Hudson98bbc492002-11-26 14:47:27 +000046
47 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
48 PyErr_Format(PyExc_TypeError,
49 "can't set %s.__name__", type->tp_name);
50 return -1;
51 }
52 if (!value) {
53 PyErr_Format(PyExc_TypeError,
54 "can't delete %s.__name__", type->tp_name);
55 return -1;
56 }
57 if (!PyString_Check(value)) {
58 PyErr_Format(PyExc_TypeError,
59 "can only assign string to %s.__name__, not '%s'",
60 type->tp_name, value->ob_type->tp_name);
61 return -1;
62 }
Tim Petersea7f75d2002-12-07 21:39:16 +000063 if (strlen(PyString_AS_STRING(value))
Michael W. Hudson98bbc492002-11-26 14:47:27 +000064 != (size_t)PyString_GET_SIZE(value)) {
65 PyErr_Format(PyExc_ValueError,
66 "__name__ must not contain null bytes");
67 return -1;
68 }
69
Guido van Rossume5c691a2003-03-07 15:13:17 +000070 et = (PyHeapTypeObject*)type;
Michael W. Hudson98bbc492002-11-26 14:47:27 +000071
72 Py_INCREF(value);
73
74 Py_DECREF(et->name);
75 et->name = value;
76
77 type->tp_name = PyString_AS_STRING(value);
78
79 return 0;
80}
81
Guido van Rossumc3542212001-08-16 09:18:56 +000082static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +000083type_module(PyTypeObject *type, void *context)
Guido van Rossum29ca26e1995-01-07 11:58:15 +000084{
Guido van Rossumc3542212001-08-16 09:18:56 +000085 PyObject *mod;
86 char *s;
87
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +000088 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
89 mod = PyDict_GetItemString(type->tp_dict, "__module__");
90 Py_XINCREF(mod);
Guido van Rossumc3542212001-08-16 09:18:56 +000091 return mod;
92 }
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +000093 else {
94 s = strrchr(type->tp_name, '.');
95 if (s != NULL)
96 return PyString_FromStringAndSize(
97 type->tp_name, (int)(s - type->tp_name));
98 return PyString_FromString("__builtin__");
99 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000100}
101
Guido van Rossum3926a632001-09-25 16:25:58 +0000102static int
103type_set_module(PyTypeObject *type, PyObject *value, void *context)
104{
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000105 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
Guido van Rossum3926a632001-09-25 16:25:58 +0000106 PyErr_Format(PyExc_TypeError,
107 "can't set %s.__module__", type->tp_name);
108 return -1;
109 }
110 if (!value) {
111 PyErr_Format(PyExc_TypeError,
112 "can't delete %s.__module__", type->tp_name);
113 return -1;
114 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000115
Guido van Rossum3926a632001-09-25 16:25:58 +0000116 return PyDict_SetItemString(type->tp_dict, "__module__", value);
117}
118
Tim Peters6d6c1a32001-08-02 04:15:00 +0000119static PyObject *
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000120type_get_bases(PyTypeObject *type, void *context)
121{
122 Py_INCREF(type->tp_bases);
123 return type->tp_bases;
124}
125
126static PyTypeObject *best_base(PyObject *);
127static int mro_internal(PyTypeObject *);
128static int compatible_for_assignment(PyTypeObject *, PyTypeObject *, char *);
129static int add_subclass(PyTypeObject*, PyTypeObject*);
130static void remove_subclass(PyTypeObject *, PyTypeObject *);
131static void update_all_slots(PyTypeObject *);
132
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000133typedef int (*update_callback)(PyTypeObject *, void *);
134static int update_subclasses(PyTypeObject *type, PyObject *name,
135 update_callback callback, void *data);
136static int recurse_down_subclasses(PyTypeObject *type, PyObject *name,
137 update_callback callback, void *data);
138
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000139static int
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000140mro_subclasses(PyTypeObject *type, PyObject* temp)
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000141{
142 PyTypeObject *subclass;
143 PyObject *ref, *subclasses, *old_mro;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000144 int i, n;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000145
146 subclasses = type->tp_subclasses;
147 if (subclasses == NULL)
148 return 0;
149 assert(PyList_Check(subclasses));
150 n = PyList_GET_SIZE(subclasses);
151 for (i = 0; i < n; i++) {
152 ref = PyList_GET_ITEM(subclasses, i);
153 assert(PyWeakref_CheckRef(ref));
154 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
155 assert(subclass != NULL);
156 if ((PyObject *)subclass == Py_None)
157 continue;
158 assert(PyType_Check(subclass));
159 old_mro = subclass->tp_mro;
160 if (mro_internal(subclass) < 0) {
161 subclass->tp_mro = old_mro;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000162 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000163 }
164 else {
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000165 PyObject* tuple;
166 tuple = Py_BuildValue("OO", subclass, old_mro);
167 if (!tuple)
168 return -1;
169 if (PyList_Append(temp, tuple) < 0)
170 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000171 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000172 if (mro_subclasses(subclass, temp) < 0)
173 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000174 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000175 return 0;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000176}
177
178static int
179type_set_bases(PyTypeObject *type, PyObject *value, void *context)
180{
181 int i, r = 0;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000182 PyObject *ob, *temp;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000183 PyTypeObject *new_base, *old_base;
184 PyObject *old_bases, *old_mro;
185
186 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
187 PyErr_Format(PyExc_TypeError,
188 "can't set %s.__bases__", type->tp_name);
189 return -1;
190 }
191 if (!value) {
192 PyErr_Format(PyExc_TypeError,
193 "can't delete %s.__bases__", type->tp_name);
194 return -1;
195 }
196 if (!PyTuple_Check(value)) {
197 PyErr_Format(PyExc_TypeError,
198 "can only assign tuple to %s.__bases__, not %s",
199 type->tp_name, value->ob_type->tp_name);
200 return -1;
201 }
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +0000202 if (PyTuple_GET_SIZE(value) == 0) {
203 PyErr_Format(PyExc_TypeError,
204 "can only assign non-empty tuple to %s.__bases__, not ()",
205 type->tp_name);
206 return -1;
207 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000208 for (i = 0; i < PyTuple_GET_SIZE(value); i++) {
209 ob = PyTuple_GET_ITEM(value, i);
210 if (!PyClass_Check(ob) && !PyType_Check(ob)) {
211 PyErr_Format(
212 PyExc_TypeError,
213 "%s.__bases__ must be tuple of old- or new-style classes, not '%s'",
214 type->tp_name, ob->ob_type->tp_name);
215 return -1;
216 }
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +0000217 if (PyType_Check(ob)) {
218 if (PyType_IsSubtype((PyTypeObject*)ob, type)) {
219 PyErr_SetString(PyExc_TypeError,
220 "a __bases__ item causes an inheritance cycle");
221 return -1;
222 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000223 }
224 }
225
226 new_base = best_base(value);
227
228 if (!new_base) {
229 return -1;
230 }
231
232 if (!compatible_for_assignment(type->tp_base, new_base, "__bases__"))
233 return -1;
234
235 Py_INCREF(new_base);
236 Py_INCREF(value);
237
238 old_bases = type->tp_bases;
239 old_base = type->tp_base;
240 old_mro = type->tp_mro;
241
242 type->tp_bases = value;
243 type->tp_base = new_base;
244
245 if (mro_internal(type) < 0) {
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000246 goto bail;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000247 }
248
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000249 temp = PyList_New(0);
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000250 if (!temp)
251 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000252
253 r = mro_subclasses(type, temp);
254
255 if (r < 0) {
256 for (i = 0; i < PyList_Size(temp); i++) {
257 PyTypeObject* cls;
258 PyObject* mro;
259 PyArg_ParseTuple(PyList_GetItem(temp, i),
260 "OO", &cls, &mro);
261 Py_DECREF(cls->tp_mro);
262 cls->tp_mro = mro;
263 Py_INCREF(cls->tp_mro);
264 }
265 Py_DECREF(temp);
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000266 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000267 }
268
269 Py_DECREF(temp);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000270
271 /* any base that was in __bases__ but now isn't, we
Raymond Hettingera8285862002-12-14 17:17:56 +0000272 need to remove |type| from its tp_subclasses.
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000273 conversely, any class now in __bases__ that wasn't
Raymond Hettingera8285862002-12-14 17:17:56 +0000274 needs to have |type| added to its subclasses. */
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000275
276 /* for now, sod that: just remove from all old_bases,
277 add to all new_bases */
278
279 for (i = PyTuple_GET_SIZE(old_bases) - 1; i >= 0; i--) {
280 ob = PyTuple_GET_ITEM(old_bases, i);
281 if (PyType_Check(ob)) {
282 remove_subclass(
283 (PyTypeObject*)ob, type);
284 }
285 }
286
287 for (i = PyTuple_GET_SIZE(value) - 1; i >= 0; i--) {
288 ob = PyTuple_GET_ITEM(value, i);
289 if (PyType_Check(ob)) {
290 if (add_subclass((PyTypeObject*)ob, type) < 0)
291 r = -1;
292 }
293 }
294
295 update_all_slots(type);
296
297 Py_DECREF(old_bases);
298 Py_DECREF(old_base);
299 Py_DECREF(old_mro);
300
301 return r;
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000302
303 bail:
304 type->tp_bases = old_bases;
305 type->tp_base = old_base;
306 type->tp_mro = old_mro;
Tim Petersea7f75d2002-12-07 21:39:16 +0000307
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000308 Py_DECREF(value);
309 Py_DECREF(new_base);
Tim Petersea7f75d2002-12-07 21:39:16 +0000310
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000311 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000312}
313
314static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000315type_dict(PyTypeObject *type, void *context)
316{
317 if (type->tp_dict == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000318 Py_INCREF(Py_None);
319 return Py_None;
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000320 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000321 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000322}
323
Tim Peters24008312002-03-17 18:56:20 +0000324static PyObject *
325type_get_doc(PyTypeObject *type, void *context)
326{
327 PyObject *result;
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000328 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL)
Tim Peters24008312002-03-17 18:56:20 +0000329 return PyString_FromString(type->tp_doc);
Tim Peters24008312002-03-17 18:56:20 +0000330 result = PyDict_GetItemString(type->tp_dict, "__doc__");
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000331 if (result == NULL) {
332 result = Py_None;
333 Py_INCREF(result);
334 }
335 else if (result->ob_type->tp_descr_get) {
Tim Peters2b858972002-04-18 04:12:28 +0000336 result = result->ob_type->tp_descr_get(result, NULL,
337 (PyObject *)type);
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000338 }
339 else {
340 Py_INCREF(result);
341 }
Tim Peters24008312002-03-17 18:56:20 +0000342 return result;
343}
344
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000345static PyGetSetDef type_getsets[] = {
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000346 {"__name__", (getter)type_name, (setter)type_set_name, NULL},
347 {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL},
Guido van Rossum3926a632001-09-25 16:25:58 +0000348 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000349 {"__dict__", (getter)type_dict, NULL, NULL},
Tim Peters24008312002-03-17 18:56:20 +0000350 {"__doc__", (getter)type_get_doc, NULL, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000351 {0}
352};
353
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000354static int
355type_compare(PyObject *v, PyObject *w)
356{
357 /* This is called with type objects only. So we
358 can just compare the addresses. */
359 Py_uintptr_t vv = (Py_uintptr_t)v;
360 Py_uintptr_t ww = (Py_uintptr_t)w;
361 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
362}
363
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000364static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000365type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000366{
Barry Warsaw7ce36942001-08-24 18:34:26 +0000367 PyObject *mod, *name, *rtn;
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000368 char *kind;
Guido van Rossumc3542212001-08-16 09:18:56 +0000369
370 mod = type_module(type, NULL);
371 if (mod == NULL)
372 PyErr_Clear();
373 else if (!PyString_Check(mod)) {
374 Py_DECREF(mod);
375 mod = NULL;
376 }
377 name = type_name(type, NULL);
378 if (name == NULL)
379 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000380
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000381 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
382 kind = "class";
383 else
384 kind = "type";
385
Barry Warsaw7ce36942001-08-24 18:34:26 +0000386 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__")) {
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000387 rtn = PyString_FromFormat("<%s '%s.%s'>",
388 kind,
Barry Warsaw7ce36942001-08-24 18:34:26 +0000389 PyString_AS_STRING(mod),
390 PyString_AS_STRING(name));
391 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000392 else
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000393 rtn = PyString_FromFormat("<%s '%s'>", kind, type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000394
Guido van Rossumc3542212001-08-16 09:18:56 +0000395 Py_XDECREF(mod);
396 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000397 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000398}
399
Tim Peters6d6c1a32001-08-02 04:15:00 +0000400static PyObject *
401type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
402{
403 PyObject *obj;
404
405 if (type->tp_new == NULL) {
406 PyErr_Format(PyExc_TypeError,
407 "cannot create '%.100s' instances",
408 type->tp_name);
409 return NULL;
410 }
411
Tim Peters3f996e72001-09-13 19:18:27 +0000412 obj = type->tp_new(type, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000413 if (obj != NULL) {
Guido van Rossumf76de622001-10-18 15:49:21 +0000414 /* Ugly exception: when the call was type(something),
415 don't call tp_init on the result. */
416 if (type == &PyType_Type &&
417 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
418 (kwds == NULL ||
419 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
420 return obj;
Guido van Rossum8ace1ab2002-04-06 01:05:01 +0000421 /* If the returned object is not an instance of type,
422 it won't be initialized. */
423 if (!PyType_IsSubtype(obj->ob_type, type))
424 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000425 type = obj->ob_type;
Jeremy Hylton719841e2002-07-16 19:39:38 +0000426 if (PyType_HasFeature(type, Py_TPFLAGS_HAVE_CLASS) &&
427 type->tp_init != NULL &&
Tim Peters6d6c1a32001-08-02 04:15:00 +0000428 type->tp_init(obj, args, kwds) < 0) {
429 Py_DECREF(obj);
430 obj = NULL;
431 }
432 }
433 return obj;
434}
435
436PyObject *
437PyType_GenericAlloc(PyTypeObject *type, int nitems)
438{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000439 PyObject *obj;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000440 const size_t size = _PyObject_VAR_SIZE(type, nitems+1);
441 /* note that we need to add one, for the sentinel */
Tim Peters406fe3b2001-10-06 19:04:01 +0000442
443 if (PyType_IS_GC(type))
Neil Schemenauer09a2ae52002-04-12 03:06:53 +0000444 obj = _PyObject_GC_Malloc(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000445 else
Neil Schemenauerc806c882001-08-29 23:54:54 +0000446 obj = PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000447
Neil Schemenauerc806c882001-08-29 23:54:54 +0000448 if (obj == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000449 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000450
Neil Schemenauerc806c882001-08-29 23:54:54 +0000451 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000452
Tim Peters6d6c1a32001-08-02 04:15:00 +0000453 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
454 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000455
Tim Peters6d6c1a32001-08-02 04:15:00 +0000456 if (type->tp_itemsize == 0)
457 PyObject_INIT(obj, type);
458 else
459 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000460
Tim Peters6d6c1a32001-08-02 04:15:00 +0000461 if (PyType_IS_GC(type))
Neil Schemenauerc806c882001-08-29 23:54:54 +0000462 _PyObject_GC_TRACK(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000463 return obj;
464}
465
466PyObject *
467PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
468{
469 return type->tp_alloc(type, 0);
470}
471
Guido van Rossum9475a232001-10-05 20:51:39 +0000472/* Helpers for subtyping */
473
474static int
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000475traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
476{
477 int i, n;
478 PyMemberDef *mp;
479
480 n = type->ob_size;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000481 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000482 for (i = 0; i < n; i++, mp++) {
483 if (mp->type == T_OBJECT_EX) {
484 char *addr = (char *)self + mp->offset;
485 PyObject *obj = *(PyObject **)addr;
486 if (obj != NULL) {
487 int err = visit(obj, arg);
488 if (err)
489 return err;
490 }
491 }
492 }
493 return 0;
494}
495
496static int
Guido van Rossum9475a232001-10-05 20:51:39 +0000497subtype_traverse(PyObject *self, visitproc visit, void *arg)
498{
499 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000500 traverseproc basetraverse;
Guido van Rossum9475a232001-10-05 20:51:39 +0000501
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000502 /* Find the nearest base with a different tp_traverse,
503 and traverse slots while we're at it */
Guido van Rossum9475a232001-10-05 20:51:39 +0000504 type = self->ob_type;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000505 base = type;
506 while ((basetraverse = base->tp_traverse) == subtype_traverse) {
507 if (base->ob_size) {
508 int err = traverse_slots(base, self, visit, arg);
509 if (err)
510 return err;
511 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000512 base = base->tp_base;
513 assert(base);
514 }
515
516 if (type->tp_dictoffset != base->tp_dictoffset) {
517 PyObject **dictptr = _PyObject_GetDictPtr(self);
518 if (dictptr && *dictptr) {
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000519 int err = visit(*dictptr, arg);
Guido van Rossum9475a232001-10-05 20:51:39 +0000520 if (err)
521 return err;
522 }
523 }
524
Guido van Rossuma3862092002-06-10 15:24:42 +0000525 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
526 /* For a heaptype, the instances count as references
527 to the type. Traverse the type so the collector
528 can find cycles involving this link. */
529 int err = visit((PyObject *)type, arg);
530 if (err)
531 return err;
532 }
533
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000534 if (basetraverse)
535 return basetraverse(self, visit, arg);
536 return 0;
537}
538
539static void
540clear_slots(PyTypeObject *type, PyObject *self)
541{
542 int i, n;
543 PyMemberDef *mp;
544
545 n = type->ob_size;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000546 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000547 for (i = 0; i < n; i++, mp++) {
548 if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
549 char *addr = (char *)self + mp->offset;
550 PyObject *obj = *(PyObject **)addr;
551 if (obj != NULL) {
552 Py_DECREF(obj);
553 *(PyObject **)addr = NULL;
554 }
555 }
556 }
557}
558
559static int
560subtype_clear(PyObject *self)
561{
562 PyTypeObject *type, *base;
563 inquiry baseclear;
564
565 /* Find the nearest base with a different tp_clear
566 and clear slots while we're at it */
567 type = self->ob_type;
568 base = type;
569 while ((baseclear = base->tp_clear) == subtype_clear) {
570 if (base->ob_size)
571 clear_slots(base, self);
572 base = base->tp_base;
573 assert(base);
574 }
575
Guido van Rossuma3862092002-06-10 15:24:42 +0000576 /* There's no need to clear the instance dict (if any);
577 the collector will call its tp_clear handler. */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000578
579 if (baseclear)
580 return baseclear(self);
Guido van Rossum9475a232001-10-05 20:51:39 +0000581 return 0;
582}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000583
584static void
585subtype_dealloc(PyObject *self)
586{
Guido van Rossum14227b42001-12-06 02:35:58 +0000587 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000588 destructor basedealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000589
Guido van Rossum22b13872002-08-06 21:41:44 +0000590 /* Extract the type; we expect it to be a heap type */
591 type = self->ob_type;
592 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000593
Guido van Rossum22b13872002-08-06 21:41:44 +0000594 /* Test whether the type has GC exactly once */
595
596 if (!PyType_IS_GC(type)) {
597 /* It's really rare to find a dynamic type that doesn't have
598 GC; it can only happen when deriving from 'object' and not
599 adding any slots or instance variables. This allows
600 certain simplifications: there's no need to call
601 clear_slots(), or DECREF the dict, or clear weakrefs. */
602
603 /* Maybe call finalizer; exit early if resurrected */
Guido van Rossumfebd61d2002-08-08 20:55:20 +0000604 if (type->tp_del) {
605 type->tp_del(self);
606 if (self->ob_refcnt > 0)
607 return;
608 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000609
610 /* Find the nearest base with a different tp_dealloc */
611 base = type;
612 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
613 assert(base->ob_size == 0);
614 base = base->tp_base;
615 assert(base);
616 }
617
618 /* Call the base tp_dealloc() */
619 assert(basedealloc);
620 basedealloc(self);
621
622 /* Can't reference self beyond this point */
623 Py_DECREF(type);
624
625 /* Done */
626 return;
627 }
628
629 /* We get here only if the type has GC */
630
631 /* UnTrack and re-Track around the trashcan macro, alas */
Andrew M. Kuchlingc9172d32003-02-06 15:22:49 +0000632 /* See explanation at end of function for full disclosure */
Guido van Rossum0906e072002-08-07 20:42:09 +0000633 PyObject_GC_UnTrack(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000634 ++_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000635 Py_TRASHCAN_SAFE_BEGIN(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000636 --_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000637 _PyObject_GC_TRACK(self); /* We'll untrack for real later */
638
639 /* Maybe call finalizer; exit early if resurrected */
Guido van Rossumfebd61d2002-08-08 20:55:20 +0000640 if (type->tp_del) {
641 type->tp_del(self);
642 if (self->ob_refcnt > 0)
643 goto endlabel;
644 }
Guido van Rossum7ad2d1e2001-10-29 22:11:00 +0000645
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000646 /* Find the nearest base with a different tp_dealloc
647 and clear slots while we're at it */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000648 base = type;
649 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
650 if (base->ob_size)
651 clear_slots(base, self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000652 base = base->tp_base;
653 assert(base);
Guido van Rossum14227b42001-12-06 02:35:58 +0000654 }
655
Tim Peters6d6c1a32001-08-02 04:15:00 +0000656 /* If we added a dict, DECREF it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000657 if (type->tp_dictoffset && !base->tp_dictoffset) {
658 PyObject **dictptr = _PyObject_GetDictPtr(self);
659 if (dictptr != NULL) {
660 PyObject *dict = *dictptr;
661 if (dict != NULL) {
662 Py_DECREF(dict);
663 *dictptr = NULL;
664 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000665 }
666 }
667
Guido van Rossum9676b222001-08-17 20:32:36 +0000668 /* If we added weaklist, we clear it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000669 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
Guido van Rossum9676b222001-08-17 20:32:36 +0000670 PyObject_ClearWeakRefs(self);
671
Tim Peters6d6c1a32001-08-02 04:15:00 +0000672 /* Finalize GC if the base doesn't do GC and we do */
Guido van Rossum22b13872002-08-06 21:41:44 +0000673 if (!PyType_IS_GC(base))
Guido van Rossum048eb752001-10-02 21:24:57 +0000674 _PyObject_GC_UNTRACK(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000675
676 /* Call the base tp_dealloc() */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000677 assert(basedealloc);
678 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000679
680 /* Can't reference self beyond this point */
Guido van Rossum22b13872002-08-06 21:41:44 +0000681 Py_DECREF(type);
682
Guido van Rossum0906e072002-08-07 20:42:09 +0000683 endlabel:
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000684 ++_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000685 Py_TRASHCAN_SAFE_END(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000686 --_PyTrash_delete_nesting;
687
688 /* Explanation of the weirdness around the trashcan macros:
689
690 Q. What do the trashcan macros do?
691
692 A. Read the comment titled "Trashcan mechanism" in object.h.
693 For one, this explains why there must be a call to GC-untrack
694 before the trashcan begin macro. Without understanding the
695 trashcan code, the answers to the following questions don't make
696 sense.
697
698 Q. Why do we GC-untrack before the trashcan and then immediately
699 GC-track again afterward?
700
701 A. In the case that the base class is GC-aware, the base class
702 probably GC-untracks the object. If it does that using the
703 UNTRACK macro, this will crash when the object is already
704 untracked. Because we don't know what the base class does, the
705 only safe thing is to make sure the object is tracked when we
706 call the base class dealloc. But... The trashcan begin macro
707 requires that the object is *untracked* before it is called. So
708 the dance becomes:
709
710 GC untrack
711 trashcan begin
712 GC track
713
714 Q. Why the bizarre (net-zero) manipulation of
715 _PyTrash_delete_nesting around the trashcan macros?
716
717 A. Some base classes (e.g. list) also use the trashcan mechanism.
718 The following scenario used to be possible:
719
720 - suppose the trashcan level is one below the trashcan limit
721
722 - subtype_dealloc() is called
723
724 - the trashcan limit is not yet reached, so the trashcan level
725 is incremented and the code between trashcan begin and end is
726 executed
727
728 - this destroys much of the object's contents, including its
729 slots and __dict__
730
731 - basedealloc() is called; this is really list_dealloc(), or
732 some other type which also uses the trashcan macros
733
734 - the trashcan limit is now reached, so the object is put on the
735 trashcan's to-be-deleted-later list
736
737 - basedealloc() returns
738
739 - subtype_dealloc() decrefs the object's type
740
741 - subtype_dealloc() returns
742
743 - later, the trashcan code starts deleting the objects from its
744 to-be-deleted-later list
745
746 - subtype_dealloc() is called *AGAIN* for the same object
747
748 - at the very least (if the destroyed slots and __dict__ don't
749 cause problems) the object's type gets decref'ed a second
750 time, which is *BAD*!!!
751
752 The remedy is to make sure that if the code between trashcan
753 begin and end in subtype_dealloc() is called, the code between
754 trashcan begin and end in basedealloc() will also be called.
755 This is done by decrementing the level after passing into the
756 trashcan block, and incrementing it just before leaving the
757 block.
758
759 But now it's possible that a chain of objects consisting solely
760 of objects whose deallocator is subtype_dealloc() will defeat
761 the trashcan mechanism completely: the decremented level means
762 that the effective level never reaches the limit. Therefore, we
763 *increment* the level *before* entering the trashcan block, and
764 matchingly decrement it after leaving. This means the trashcan
765 code will trigger a little early, but that's no big deal.
766
767 Q. Are there any live examples of code in need of all this
768 complexity?
769
770 A. Yes. See SF bug 668433 for code that crashed (when Python was
771 compiled in debug mode) before the trashcan level manipulations
772 were added. For more discussion, see SF patches 581742, 575073
773 and bug 574207.
774 */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000775}
776
Jeremy Hylton938ace62002-07-17 16:30:39 +0000777static PyTypeObject *solid_base(PyTypeObject *type);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000778
Tim Peters6d6c1a32001-08-02 04:15:00 +0000779/* type test with subclassing support */
780
781int
782PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
783{
784 PyObject *mro;
785
Guido van Rossum9478d072001-09-07 18:52:13 +0000786 if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
787 return b == a || b == &PyBaseObject_Type;
788
Tim Peters6d6c1a32001-08-02 04:15:00 +0000789 mro = a->tp_mro;
790 if (mro != NULL) {
791 /* Deal with multiple inheritance without recursion
792 by walking the MRO tuple */
793 int i, n;
794 assert(PyTuple_Check(mro));
795 n = PyTuple_GET_SIZE(mro);
796 for (i = 0; i < n; i++) {
797 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
798 return 1;
799 }
800 return 0;
801 }
802 else {
803 /* a is not completely initilized yet; follow tp_base */
804 do {
805 if (a == b)
806 return 1;
807 a = a->tp_base;
808 } while (a != NULL);
809 return b == &PyBaseObject_Type;
810 }
811}
812
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000813/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +0000814 without looking in the instance dictionary
815 (so we can't use PyObject_GetAttr) but still binding
816 it to the instance. The arguments are the object,
817 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000818 static variable used to cache the interned Python string.
819
820 Two variants:
821
822 - lookup_maybe() returns NULL without raising an exception
823 when the _PyType_Lookup() call fails;
824
825 - lookup_method() always raises an exception upon errors.
826*/
Guido van Rossum60718732001-08-28 17:47:51 +0000827
828static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000829lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +0000830{
831 PyObject *res;
832
833 if (*attrobj == NULL) {
834 *attrobj = PyString_InternFromString(attrstr);
835 if (*attrobj == NULL)
836 return NULL;
837 }
838 res = _PyType_Lookup(self->ob_type, *attrobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000839 if (res != NULL) {
Guido van Rossum60718732001-08-28 17:47:51 +0000840 descrgetfunc f;
841 if ((f = res->ob_type->tp_descr_get) == NULL)
842 Py_INCREF(res);
843 else
844 res = f(res, self, (PyObject *)(self->ob_type));
845 }
846 return res;
847}
848
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000849static PyObject *
850lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
851{
852 PyObject *res = lookup_maybe(self, attrstr, attrobj);
853 if (res == NULL && !PyErr_Occurred())
854 PyErr_SetObject(PyExc_AttributeError, *attrobj);
855 return res;
856}
857
Guido van Rossum2730b132001-08-28 18:22:14 +0000858/* A variation of PyObject_CallMethod that uses lookup_method()
859 instead of PyObject_GetAttrString(). This uses the same convention
860 as lookup_method to cache the interned name string object. */
861
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000862static PyObject *
Guido van Rossum2730b132001-08-28 18:22:14 +0000863call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
864{
865 va_list va;
866 PyObject *args, *func = 0, *retval;
Guido van Rossum2730b132001-08-28 18:22:14 +0000867 va_start(va, format);
868
Guido van Rossumda21c012001-10-03 00:50:18 +0000869 func = lookup_maybe(o, name, nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000870 if (func == NULL) {
871 va_end(va);
872 if (!PyErr_Occurred())
Guido van Rossumda21c012001-10-03 00:50:18 +0000873 PyErr_SetObject(PyExc_AttributeError, *nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000874 return NULL;
875 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000876
877 if (format && *format)
878 args = Py_VaBuildValue(format, va);
879 else
880 args = PyTuple_New(0);
881
882 va_end(va);
883
884 if (args == NULL)
885 return NULL;
886
887 assert(PyTuple_Check(args));
888 retval = PyObject_Call(func, args, NULL);
889
890 Py_DECREF(args);
891 Py_DECREF(func);
892
893 return retval;
894}
895
896/* Clone of call_method() that returns NotImplemented when the lookup fails. */
897
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000898static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000899call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
900{
901 va_list va;
902 PyObject *args, *func = 0, *retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000903 va_start(va, format);
904
Guido van Rossumda21c012001-10-03 00:50:18 +0000905 func = lookup_maybe(o, name, nameobj);
Guido van Rossum2730b132001-08-28 18:22:14 +0000906 if (func == NULL) {
907 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000908 if (!PyErr_Occurred()) {
909 Py_INCREF(Py_NotImplemented);
910 return Py_NotImplemented;
911 }
Guido van Rossum717ce002001-09-14 16:58:08 +0000912 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +0000913 }
914
915 if (format && *format)
916 args = Py_VaBuildValue(format, va);
917 else
918 args = PyTuple_New(0);
919
920 va_end(va);
921
Guido van Rossum717ce002001-09-14 16:58:08 +0000922 if (args == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +0000923 return NULL;
924
Guido van Rossum717ce002001-09-14 16:58:08 +0000925 assert(PyTuple_Check(args));
926 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +0000927
928 Py_DECREF(args);
929 Py_DECREF(func);
930
931 return retval;
932}
933
Tim Petersa91e9642001-11-14 23:32:33 +0000934static int
935fill_classic_mro(PyObject *mro, PyObject *cls)
936{
937 PyObject *bases, *base;
938 int i, n;
939
940 assert(PyList_Check(mro));
941 assert(PyClass_Check(cls));
942 i = PySequence_Contains(mro, cls);
943 if (i < 0)
944 return -1;
945 if (!i) {
946 if (PyList_Append(mro, cls) < 0)
947 return -1;
948 }
949 bases = ((PyClassObject *)cls)->cl_bases;
950 assert(bases && PyTuple_Check(bases));
951 n = PyTuple_GET_SIZE(bases);
952 for (i = 0; i < n; i++) {
953 base = PyTuple_GET_ITEM(bases, i);
954 if (fill_classic_mro(mro, base) < 0)
955 return -1;
956 }
957 return 0;
958}
959
960static PyObject *
961classic_mro(PyObject *cls)
962{
963 PyObject *mro;
964
965 assert(PyClass_Check(cls));
966 mro = PyList_New(0);
967 if (mro != NULL) {
968 if (fill_classic_mro(mro, cls) == 0)
969 return mro;
970 Py_DECREF(mro);
971 }
972 return NULL;
973}
974
Tim Petersea7f75d2002-12-07 21:39:16 +0000975/*
Guido van Rossum1f121312002-11-14 19:49:16 +0000976 Method resolution order algorithm C3 described in
977 "A Monotonic Superclass Linearization for Dylan",
978 by Kim Barrett, Bob Cassel, Paul Haahr,
Tim Petersea7f75d2002-12-07 21:39:16 +0000979 David A. Moon, Keith Playford, and P. Tucker Withington.
Guido van Rossum1f121312002-11-14 19:49:16 +0000980 (OOPSLA 1996)
981
Guido van Rossum98f33732002-11-25 21:36:54 +0000982 Some notes about the rules implied by C3:
983
Tim Petersea7f75d2002-12-07 21:39:16 +0000984 No duplicate bases.
Guido van Rossum98f33732002-11-25 21:36:54 +0000985 It isn't legal to repeat a class in a list of base classes.
986
987 The next three properties are the 3 constraints in "C3".
988
Tim Petersea7f75d2002-12-07 21:39:16 +0000989 Local precendece order.
Guido van Rossum98f33732002-11-25 21:36:54 +0000990 If A precedes B in C's MRO, then A will precede B in the MRO of all
991 subclasses of C.
992
993 Monotonicity.
994 The MRO of a class must be an extension without reordering of the
995 MRO of each of its superclasses.
996
997 Extended Precedence Graph (EPG).
998 Linearization is consistent if there is a path in the EPG from
999 each class to all its successors in the linearization. See
1000 the paper for definition of EPG.
Guido van Rossum1f121312002-11-14 19:49:16 +00001001 */
1002
Tim Petersea7f75d2002-12-07 21:39:16 +00001003static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001004tail_contains(PyObject *list, int whence, PyObject *o) {
1005 int j, size;
1006 size = PyList_GET_SIZE(list);
1007
1008 for (j = whence+1; j < size; j++) {
1009 if (PyList_GET_ITEM(list, j) == o)
1010 return 1;
1011 }
1012 return 0;
1013}
1014
Guido van Rossum98f33732002-11-25 21:36:54 +00001015static PyObject *
1016class_name(PyObject *cls)
1017{
1018 PyObject *name = PyObject_GetAttrString(cls, "__name__");
1019 if (name == NULL) {
1020 PyErr_Clear();
1021 Py_XDECREF(name);
1022 name = PyObject_Repr(cls);
1023 }
1024 if (name == NULL)
1025 return NULL;
1026 if (!PyString_Check(name)) {
1027 Py_DECREF(name);
1028 return NULL;
1029 }
1030 return name;
1031}
1032
1033static int
1034check_duplicates(PyObject *list)
1035{
1036 int i, j, n;
1037 /* Let's use a quadratic time algorithm,
1038 assuming that the bases lists is short.
1039 */
1040 n = PyList_GET_SIZE(list);
1041 for (i = 0; i < n; i++) {
1042 PyObject *o = PyList_GET_ITEM(list, i);
1043 for (j = i + 1; j < n; j++) {
1044 if (PyList_GET_ITEM(list, j) == o) {
1045 o = class_name(o);
1046 PyErr_Format(PyExc_TypeError,
1047 "duplicate base class %s",
1048 o ? PyString_AS_STRING(o) : "?");
1049 Py_XDECREF(o);
1050 return -1;
1051 }
1052 }
1053 }
1054 return 0;
1055}
1056
1057/* Raise a TypeError for an MRO order disagreement.
1058
1059 It's hard to produce a good error message. In the absence of better
1060 insight into error reporting, report the classes that were candidates
1061 to be put next into the MRO. There is some conflict between the
1062 order in which they should be put in the MRO, but it's hard to
1063 diagnose what constraint can't be satisfied.
1064*/
1065
1066static void
1067set_mro_error(PyObject *to_merge, int *remain)
1068{
1069 int i, n, off, to_merge_size;
1070 char buf[1000];
1071 PyObject *k, *v;
1072 PyObject *set = PyDict_New();
1073
1074 to_merge_size = PyList_GET_SIZE(to_merge);
1075 for (i = 0; i < to_merge_size; i++) {
1076 PyObject *L = PyList_GET_ITEM(to_merge, i);
1077 if (remain[i] < PyList_GET_SIZE(L)) {
1078 PyObject *c = PyList_GET_ITEM(L, remain[i]);
1079 if (PyDict_SetItem(set, c, Py_None) < 0)
1080 return;
1081 }
1082 }
1083 n = PyDict_Size(set);
1084
Raymond Hettingerf394df42003-04-06 19:13:41 +00001085 off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \
1086consistent method resolution\norder (MRO) for bases");
Guido van Rossum98f33732002-11-25 21:36:54 +00001087 i = 0;
1088 while (PyDict_Next(set, &i, &k, &v) && off < sizeof(buf)) {
1089 PyObject *name = class_name(k);
1090 off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s",
1091 name ? PyString_AS_STRING(name) : "?");
1092 Py_XDECREF(name);
1093 if (--n && off+1 < sizeof(buf)) {
1094 buf[off++] = ',';
1095 buf[off] = '\0';
1096 }
1097 }
1098 PyErr_SetString(PyExc_TypeError, buf);
1099 Py_DECREF(set);
1100}
1101
Tim Petersea7f75d2002-12-07 21:39:16 +00001102static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001103pmerge(PyObject *acc, PyObject* to_merge) {
1104 int i, j, to_merge_size;
1105 int *remain;
1106 int ok, empty_cnt;
Tim Petersea7f75d2002-12-07 21:39:16 +00001107
Guido van Rossum1f121312002-11-14 19:49:16 +00001108 to_merge_size = PyList_GET_SIZE(to_merge);
1109
Guido van Rossum98f33732002-11-25 21:36:54 +00001110 /* remain stores an index into each sublist of to_merge.
1111 remain[i] is the index of the next base in to_merge[i]
1112 that is not included in acc.
1113 */
Guido van Rossum1f121312002-11-14 19:49:16 +00001114 remain = PyMem_MALLOC(SIZEOF_INT*to_merge_size);
1115 if (remain == NULL)
1116 return -1;
1117 for (i = 0; i < to_merge_size; i++)
1118 remain[i] = 0;
1119
1120 again:
1121 empty_cnt = 0;
1122 for (i = 0; i < to_merge_size; i++) {
1123 PyObject *candidate;
Tim Petersea7f75d2002-12-07 21:39:16 +00001124
Guido van Rossum1f121312002-11-14 19:49:16 +00001125 PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
1126
1127 if (remain[i] >= PyList_GET_SIZE(cur_list)) {
1128 empty_cnt++;
1129 continue;
1130 }
1131
Guido van Rossum98f33732002-11-25 21:36:54 +00001132 /* Choose next candidate for MRO.
1133
1134 The input sequences alone can determine the choice.
1135 If not, choose the class which appears in the MRO
1136 of the earliest direct superclass of the new class.
1137 */
1138
Guido van Rossum1f121312002-11-14 19:49:16 +00001139 candidate = PyList_GET_ITEM(cur_list, remain[i]);
1140 for (j = 0; j < to_merge_size; j++) {
1141 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum98f33732002-11-25 21:36:54 +00001142 if (tail_contains(j_lst, remain[j], candidate)) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001143 goto skip; /* continue outer loop */
Guido van Rossum98f33732002-11-25 21:36:54 +00001144 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001145 }
1146 ok = PyList_Append(acc, candidate);
1147 if (ok < 0) {
1148 PyMem_Free(remain);
1149 return -1;
1150 }
1151 for (j = 0; j < to_merge_size; j++) {
1152 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum768158c2002-12-31 16:33:01 +00001153 if (remain[j] < PyList_GET_SIZE(j_lst) &&
1154 PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001155 remain[j]++;
1156 }
1157 }
1158 goto again;
Tim Peters9a6b8d82002-11-14 23:22:33 +00001159 skip: ;
Guido van Rossum1f121312002-11-14 19:49:16 +00001160 }
1161
Guido van Rossum98f33732002-11-25 21:36:54 +00001162 if (empty_cnt == to_merge_size) {
1163 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001164 return 0;
Guido van Rossum98f33732002-11-25 21:36:54 +00001165 }
1166 set_mro_error(to_merge, remain);
1167 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001168 return -1;
1169}
1170
Tim Peters6d6c1a32001-08-02 04:15:00 +00001171static PyObject *
1172mro_implementation(PyTypeObject *type)
1173{
1174 int i, n, ok;
1175 PyObject *bases, *result;
Guido van Rossum1f121312002-11-14 19:49:16 +00001176 PyObject *to_merge, *bases_aslist;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001177
Guido van Rossum63517572002-06-18 16:44:57 +00001178 if(type->tp_dict == NULL) {
1179 if(PyType_Ready(type) < 0)
1180 return NULL;
1181 }
1182
Guido van Rossum98f33732002-11-25 21:36:54 +00001183 /* Find a superclass linearization that honors the constraints
1184 of the explicit lists of bases and the constraints implied by
Tim Petersea7f75d2002-12-07 21:39:16 +00001185 each base class.
Guido van Rossum98f33732002-11-25 21:36:54 +00001186
1187 to_merge is a list of lists, where each list is a superclass
1188 linearization implied by a base class. The last element of
1189 to_merge is the declared list of bases.
1190 */
1191
Tim Peters6d6c1a32001-08-02 04:15:00 +00001192 bases = type->tp_bases;
1193 n = PyTuple_GET_SIZE(bases);
Guido van Rossum1f121312002-11-14 19:49:16 +00001194
1195 to_merge = PyList_New(n+1);
1196 if (to_merge == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001197 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001198
Tim Peters6d6c1a32001-08-02 04:15:00 +00001199 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001200 PyObject *base = PyTuple_GET_ITEM(bases, i);
1201 PyObject *parentMRO;
1202 if (PyType_Check(base))
1203 parentMRO = PySequence_List(
1204 ((PyTypeObject*)base)->tp_mro);
1205 else
1206 parentMRO = classic_mro(base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001207 if (parentMRO == NULL) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001208 Py_DECREF(to_merge);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001209 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001210 }
1211
1212 PyList_SET_ITEM(to_merge, i, parentMRO);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001213 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001214
1215 bases_aslist = PySequence_List(bases);
1216 if (bases_aslist == NULL) {
1217 Py_DECREF(to_merge);
1218 return NULL;
1219 }
Guido van Rossum98f33732002-11-25 21:36:54 +00001220 /* This is just a basic sanity check. */
1221 if (check_duplicates(bases_aslist) < 0) {
1222 Py_DECREF(to_merge);
1223 Py_DECREF(bases_aslist);
1224 return NULL;
1225 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001226 PyList_SET_ITEM(to_merge, n, bases_aslist);
1227
1228 result = Py_BuildValue("[O]", (PyObject *)type);
1229 if (result == NULL) {
1230 Py_DECREF(to_merge);
1231 return NULL;
1232 }
1233
1234 ok = pmerge(result, to_merge);
1235 Py_DECREF(to_merge);
1236 if (ok < 0) {
1237 Py_DECREF(result);
1238 return NULL;
1239 }
1240
Tim Peters6d6c1a32001-08-02 04:15:00 +00001241 return result;
1242}
1243
1244static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001245mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001246{
1247 PyTypeObject *type = (PyTypeObject *)self;
1248
Tim Peters6d6c1a32001-08-02 04:15:00 +00001249 return mro_implementation(type);
1250}
1251
1252static int
1253mro_internal(PyTypeObject *type)
1254{
1255 PyObject *mro, *result, *tuple;
1256
1257 if (type->ob_type == &PyType_Type) {
1258 result = mro_implementation(type);
1259 }
1260 else {
Guido van Rossum60718732001-08-28 17:47:51 +00001261 static PyObject *mro_str;
1262 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001263 if (mro == NULL)
1264 return -1;
1265 result = PyObject_CallObject(mro, NULL);
1266 Py_DECREF(mro);
1267 }
1268 if (result == NULL)
1269 return -1;
1270 tuple = PySequence_Tuple(result);
1271 Py_DECREF(result);
1272 type->tp_mro = tuple;
1273 return 0;
1274}
1275
1276
1277/* Calculate the best base amongst multiple base classes.
1278 This is the first one that's on the path to the "solid base". */
1279
1280static PyTypeObject *
1281best_base(PyObject *bases)
1282{
1283 int i, n;
1284 PyTypeObject *base, *winner, *candidate, *base_i;
Tim Petersa91e9642001-11-14 23:32:33 +00001285 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001286
1287 assert(PyTuple_Check(bases));
1288 n = PyTuple_GET_SIZE(bases);
1289 assert(n > 0);
Tim Petersa91e9642001-11-14 23:32:33 +00001290 base = NULL;
1291 winner = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001292 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001293 base_proto = PyTuple_GET_ITEM(bases, i);
1294 if (PyClass_Check(base_proto))
1295 continue;
1296 if (!PyType_Check(base_proto)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001297 PyErr_SetString(
1298 PyExc_TypeError,
1299 "bases must be types");
1300 return NULL;
1301 }
Tim Petersa91e9642001-11-14 23:32:33 +00001302 base_i = (PyTypeObject *)base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001303 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001304 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001305 return NULL;
1306 }
1307 candidate = solid_base(base_i);
Tim Petersa91e9642001-11-14 23:32:33 +00001308 if (winner == NULL) {
1309 winner = candidate;
1310 base = base_i;
1311 }
1312 else if (PyType_IsSubtype(winner, candidate))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001313 ;
1314 else if (PyType_IsSubtype(candidate, winner)) {
1315 winner = candidate;
1316 base = base_i;
1317 }
1318 else {
1319 PyErr_SetString(
1320 PyExc_TypeError,
1321 "multiple bases have "
1322 "instance lay-out conflict");
1323 return NULL;
1324 }
1325 }
Guido van Rossume54616c2001-12-14 04:19:56 +00001326 if (base == NULL)
1327 PyErr_SetString(PyExc_TypeError,
1328 "a new-style class can't have only classic bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001329 return base;
1330}
1331
1332static int
1333extra_ivars(PyTypeObject *type, PyTypeObject *base)
1334{
Neil Schemenauerc806c882001-08-29 23:54:54 +00001335 size_t t_size = type->tp_basicsize;
1336 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001337
Guido van Rossum9676b222001-08-17 20:32:36 +00001338 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001339 if (type->tp_itemsize || base->tp_itemsize) {
1340 /* If itemsize is involved, stricter rules */
1341 return t_size != b_size ||
1342 type->tp_itemsize != base->tp_itemsize;
1343 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001344 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
1345 type->tp_weaklistoffset + sizeof(PyObject *) == t_size)
1346 t_size -= sizeof(PyObject *);
1347 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
1348 type->tp_dictoffset + sizeof(PyObject *) == t_size)
1349 t_size -= sizeof(PyObject *);
1350
1351 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001352}
1353
1354static PyTypeObject *
1355solid_base(PyTypeObject *type)
1356{
1357 PyTypeObject *base;
1358
1359 if (type->tp_base)
1360 base = solid_base(type->tp_base);
1361 else
1362 base = &PyBaseObject_Type;
1363 if (extra_ivars(type, base))
1364 return type;
1365 else
1366 return base;
1367}
1368
Jeremy Hylton938ace62002-07-17 16:30:39 +00001369static void object_dealloc(PyObject *);
1370static int object_init(PyObject *, PyObject *, PyObject *);
1371static int update_slot(PyTypeObject *, PyObject *);
1372static void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001373
1374static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001375subtype_dict(PyObject *obj, void *context)
1376{
1377 PyObject **dictptr = _PyObject_GetDictPtr(obj);
1378 PyObject *dict;
1379
1380 if (dictptr == NULL) {
1381 PyErr_SetString(PyExc_AttributeError,
1382 "This object has no __dict__");
1383 return NULL;
1384 }
1385 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +00001386 if (dict == NULL)
1387 *dictptr = dict = PyDict_New();
1388 Py_XINCREF(dict);
1389 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001390}
1391
Guido van Rossum6661be32001-10-26 04:26:12 +00001392static int
1393subtype_setdict(PyObject *obj, PyObject *value, void *context)
1394{
1395 PyObject **dictptr = _PyObject_GetDictPtr(obj);
1396 PyObject *dict;
1397
1398 if (dictptr == NULL) {
1399 PyErr_SetString(PyExc_AttributeError,
1400 "This object has no __dict__");
1401 return -1;
1402 }
Guido van Rossumd331cb52001-12-05 19:46:42 +00001403 if (value != NULL && !PyDict_Check(value)) {
Guido van Rossum6661be32001-10-26 04:26:12 +00001404 PyErr_SetString(PyExc_TypeError,
1405 "__dict__ must be set to a dictionary");
1406 return -1;
1407 }
1408 dict = *dictptr;
Guido van Rossumd331cb52001-12-05 19:46:42 +00001409 Py_XINCREF(value);
Guido van Rossum6661be32001-10-26 04:26:12 +00001410 *dictptr = value;
1411 Py_XDECREF(dict);
1412 return 0;
1413}
1414
Guido van Rossumad47da02002-08-12 19:05:44 +00001415static PyObject *
1416subtype_getweakref(PyObject *obj, void *context)
1417{
1418 PyObject **weaklistptr;
1419 PyObject *result;
1420
1421 if (obj->ob_type->tp_weaklistoffset == 0) {
1422 PyErr_SetString(PyExc_AttributeError,
1423 "This object has no __weaklist__");
1424 return NULL;
1425 }
1426 assert(obj->ob_type->tp_weaklistoffset > 0);
1427 assert(obj->ob_type->tp_weaklistoffset + sizeof(PyObject *) <=
Guido van Rossum3747a0f2002-08-12 19:25:08 +00001428 (size_t)(obj->ob_type->tp_basicsize));
Guido van Rossumad47da02002-08-12 19:05:44 +00001429 weaklistptr = (PyObject **)
Guido van Rossum3747a0f2002-08-12 19:25:08 +00001430 ((char *)obj + obj->ob_type->tp_weaklistoffset);
Guido van Rossumad47da02002-08-12 19:05:44 +00001431 if (*weaklistptr == NULL)
1432 result = Py_None;
1433 else
1434 result = *weaklistptr;
1435 Py_INCREF(result);
1436 return result;
1437}
1438
Guido van Rossum373c7412003-01-07 13:41:37 +00001439/* Three variants on the subtype_getsets list. */
1440
1441static PyGetSetDef subtype_getsets_full[] = {
Guido van Rossumad47da02002-08-12 19:05:44 +00001442 {"__dict__", subtype_dict, subtype_setdict,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001443 PyDoc_STR("dictionary for instance variables (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001444 {"__weakref__", subtype_getweakref, NULL,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001445 PyDoc_STR("list of weak references to the object (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001446 {0}
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001447};
1448
Guido van Rossum373c7412003-01-07 13:41:37 +00001449static PyGetSetDef subtype_getsets_dict_only[] = {
1450 {"__dict__", subtype_dict, subtype_setdict,
1451 PyDoc_STR("dictionary for instance variables (if defined)")},
1452 {0}
1453};
1454
1455static PyGetSetDef subtype_getsets_weakref_only[] = {
1456 {"__weakref__", subtype_getweakref, NULL,
1457 PyDoc_STR("list of weak references to the object (if defined)")},
1458 {0}
1459};
1460
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001461static int
1462valid_identifier(PyObject *s)
1463{
Guido van Rossum03013a02002-07-16 14:30:28 +00001464 unsigned char *p;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001465 int i, n;
1466
1467 if (!PyString_Check(s)) {
1468 PyErr_SetString(PyExc_TypeError,
1469 "__slots__ must be strings");
1470 return 0;
1471 }
Guido van Rossum03013a02002-07-16 14:30:28 +00001472 p = (unsigned char *) PyString_AS_STRING(s);
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001473 n = PyString_GET_SIZE(s);
1474 /* We must reject an empty name. As a hack, we bump the
1475 length to 1 so that the loop will balk on the trailing \0. */
1476 if (n == 0)
1477 n = 1;
1478 for (i = 0; i < n; i++, p++) {
1479 if (!(i == 0 ? isalpha(*p) : isalnum(*p)) && *p != '_') {
1480 PyErr_SetString(PyExc_TypeError,
1481 "__slots__ must be identifiers");
1482 return 0;
1483 }
1484 }
1485 return 1;
1486}
1487
Martin v. Löwisd919a592002-10-14 21:07:28 +00001488#ifdef Py_USING_UNICODE
1489/* Replace Unicode objects in slots. */
1490
1491static PyObject *
1492_unicode_to_string(PyObject *slots, int nslots)
1493{
1494 PyObject *tmp = slots;
1495 PyObject *o, *o1;
1496 int i;
1497 intintargfunc copy = slots->ob_type->tp_as_sequence->sq_slice;
1498 for (i = 0; i < nslots; i++) {
1499 if (PyUnicode_Check(o = PyTuple_GET_ITEM(tmp, i))) {
1500 if (tmp == slots) {
1501 tmp = copy(slots, 0, PyTuple_GET_SIZE(slots));
1502 if (tmp == NULL)
1503 return NULL;
1504 }
1505 o1 = _PyUnicode_AsDefaultEncodedString
1506 (o, NULL);
1507 if (o1 == NULL) {
1508 Py_DECREF(tmp);
1509 return 0;
1510 }
1511 Py_INCREF(o1);
1512 Py_DECREF(o);
1513 PyTuple_SET_ITEM(tmp, i, o1);
1514 }
1515 }
1516 return tmp;
1517}
1518#endif
1519
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001520static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001521type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
1522{
1523 PyObject *name, *bases, *dict;
1524 static char *kwlist[] = {"name", "bases", "dict", 0};
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001525 PyObject *slots, *tmp, *newslots;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001526 PyTypeObject *type, *base, *tmptype, *winner;
Guido van Rossume5c691a2003-03-07 15:13:17 +00001527 PyHeapTypeObject *et;
Guido van Rossum6f799372001-09-20 20:46:19 +00001528 PyMemberDef *mp;
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001529 int i, nbases, nslots, slotoffset, add_dict, add_weak;
Guido van Rossumad47da02002-08-12 19:05:44 +00001530 int j, may_add_dict, may_add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001531
Tim Peters3abca122001-10-27 19:37:48 +00001532 assert(args != NULL && PyTuple_Check(args));
1533 assert(kwds == NULL || PyDict_Check(kwds));
1534
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001535 /* Special case: type(x) should return x->ob_type */
Tim Peters3abca122001-10-27 19:37:48 +00001536 {
1537 const int nargs = PyTuple_GET_SIZE(args);
1538 const int nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
1539
1540 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
1541 PyObject *x = PyTuple_GET_ITEM(args, 0);
1542 Py_INCREF(x->ob_type);
1543 return (PyObject *) x->ob_type;
1544 }
1545
1546 /* SF bug 475327 -- if that didn't trigger, we need 3
1547 arguments. but PyArg_ParseTupleAndKeywords below may give
1548 a msg saying type() needs exactly 3. */
1549 if (nargs + nkwds != 3) {
1550 PyErr_SetString(PyExc_TypeError,
1551 "type() takes 1 or 3 arguments");
1552 return NULL;
1553 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001554 }
1555
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001556 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001557 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
1558 &name,
1559 &PyTuple_Type, &bases,
1560 &PyDict_Type, &dict))
1561 return NULL;
1562
1563 /* Determine the proper metatype to deal with this,
1564 and check for metatype conflicts while we're at it.
1565 Note that if some other metatype wins to contract,
1566 it's possible that its instances are not types. */
1567 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001568 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001569 for (i = 0; i < nbases; i++) {
1570 tmp = PyTuple_GET_ITEM(bases, i);
1571 tmptype = tmp->ob_type;
Tim Petersa91e9642001-11-14 23:32:33 +00001572 if (tmptype == &PyClass_Type)
1573 continue; /* Special case classic classes */
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001574 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001575 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001576 if (PyType_IsSubtype(tmptype, winner)) {
1577 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001578 continue;
1579 }
1580 PyErr_SetString(PyExc_TypeError,
1581 "metatype conflict among bases");
1582 return NULL;
1583 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001584 if (winner != metatype) {
1585 if (winner->tp_new != type_new) /* Pass it to the winner */
1586 return winner->tp_new(winner, args, kwds);
1587 metatype = winner;
1588 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001589
1590 /* Adjust for empty tuple bases */
1591 if (nbases == 0) {
1592 bases = Py_BuildValue("(O)", &PyBaseObject_Type);
1593 if (bases == NULL)
1594 return NULL;
1595 nbases = 1;
1596 }
1597 else
1598 Py_INCREF(bases);
1599
1600 /* XXX From here until type is allocated, "return NULL" leaks bases! */
1601
1602 /* Calculate best base, and check that all bases are type objects */
1603 base = best_base(bases);
1604 if (base == NULL)
1605 return NULL;
1606 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
1607 PyErr_Format(PyExc_TypeError,
1608 "type '%.100s' is not an acceptable base type",
1609 base->tp_name);
1610 return NULL;
1611 }
1612
Tim Peters6d6c1a32001-08-02 04:15:00 +00001613 /* Check for a __slots__ sequence variable in dict, and count it */
1614 slots = PyDict_GetItemString(dict, "__slots__");
1615 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +00001616 add_dict = 0;
1617 add_weak = 0;
Guido van Rossumad47da02002-08-12 19:05:44 +00001618 may_add_dict = base->tp_dictoffset == 0;
1619 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
1620 if (slots == NULL) {
1621 if (may_add_dict) {
1622 add_dict++;
1623 }
1624 if (may_add_weak) {
1625 add_weak++;
1626 }
1627 }
1628 else {
1629 /* Have slots */
1630
Tim Peters6d6c1a32001-08-02 04:15:00 +00001631 /* Make it into a tuple */
1632 if (PyString_Check(slots))
1633 slots = Py_BuildValue("(O)", slots);
1634 else
1635 slots = PySequence_Tuple(slots);
1636 if (slots == NULL)
1637 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00001638 assert(PyTuple_Check(slots));
1639
1640 /* Are slots allowed? */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001641 nslots = PyTuple_GET_SIZE(slots);
Guido van Rossume5c691a2003-03-07 15:13:17 +00001642 if (nslots > 0 && base->tp_itemsize != 0 && !PyType_Check(base)) {
1643 /* for the special case of meta types, allow slots */
Guido van Rossumc4141872001-08-30 04:43:35 +00001644 PyErr_Format(PyExc_TypeError,
1645 "nonempty __slots__ "
1646 "not supported for subtype of '%s'",
1647 base->tp_name);
Guido van Rossumad47da02002-08-12 19:05:44 +00001648 bad_slots:
1649 Py_DECREF(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +00001650 return NULL;
1651 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001652
Martin v. Löwisd919a592002-10-14 21:07:28 +00001653#ifdef Py_USING_UNICODE
1654 tmp = _unicode_to_string(slots, nslots);
Martin v. Löwis13b1a5c2002-10-14 21:11:34 +00001655 if (tmp != slots) {
1656 Py_DECREF(slots);
1657 slots = tmp;
1658 }
Martin v. Löwisd919a592002-10-14 21:07:28 +00001659 if (!tmp)
1660 return NULL;
1661#endif
Guido van Rossumad47da02002-08-12 19:05:44 +00001662 /* Check for valid slot names and two special cases */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001663 for (i = 0; i < nslots; i++) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001664 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
1665 char *s;
1666 if (!valid_identifier(tmp))
1667 goto bad_slots;
1668 assert(PyString_Check(tmp));
1669 s = PyString_AS_STRING(tmp);
1670 if (strcmp(s, "__dict__") == 0) {
1671 if (!may_add_dict || add_dict) {
1672 PyErr_SetString(PyExc_TypeError,
1673 "__dict__ slot disallowed: "
1674 "we already got one");
1675 goto bad_slots;
1676 }
1677 add_dict++;
1678 }
1679 if (strcmp(s, "__weakref__") == 0) {
1680 if (!may_add_weak || add_weak) {
1681 PyErr_SetString(PyExc_TypeError,
1682 "__weakref__ slot disallowed: "
1683 "either we already got one, "
1684 "or __itemsize__ != 0");
1685 goto bad_slots;
1686 }
1687 add_weak++;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001688 }
1689 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001690
Guido van Rossumad47da02002-08-12 19:05:44 +00001691 /* Copy slots into yet another tuple, demangling names */
1692 newslots = PyTuple_New(nslots - add_dict - add_weak);
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001693 if (newslots == NULL)
Guido van Rossumad47da02002-08-12 19:05:44 +00001694 goto bad_slots;
1695 for (i = j = 0; i < nslots; i++) {
1696 char *s;
Guido van Rossum8e829202002-08-16 03:47:49 +00001697 char buffer[256];
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001698 tmp = PyTuple_GET_ITEM(slots, i);
Guido van Rossumad47da02002-08-12 19:05:44 +00001699 s = PyString_AS_STRING(tmp);
1700 if ((add_dict && strcmp(s, "__dict__") == 0) ||
1701 (add_weak && strcmp(s, "__weakref__") == 0))
1702 continue;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001703 if (_Py_Mangle(PyString_AS_STRING(name),
Guido van Rossumad47da02002-08-12 19:05:44 +00001704 PyString_AS_STRING(tmp),
1705 buffer, sizeof(buffer)))
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001706 {
1707 tmp = PyString_FromString(buffer);
1708 } else {
1709 Py_INCREF(tmp);
1710 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001711 PyTuple_SET_ITEM(newslots, j, tmp);
1712 j++;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001713 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001714 assert(j == nslots - add_dict - add_weak);
1715 nslots = j;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001716 Py_DECREF(slots);
1717 slots = newslots;
1718
Guido van Rossumad47da02002-08-12 19:05:44 +00001719 /* Secondary bases may provide weakrefs or dict */
1720 if (nbases > 1 &&
1721 ((may_add_dict && !add_dict) ||
1722 (may_add_weak && !add_weak))) {
1723 for (i = 0; i < nbases; i++) {
1724 tmp = PyTuple_GET_ITEM(bases, i);
1725 if (tmp == (PyObject *)base)
1726 continue; /* Skip primary base */
1727 if (PyClass_Check(tmp)) {
1728 /* Classic base class provides both */
1729 if (may_add_dict && !add_dict)
1730 add_dict++;
1731 if (may_add_weak && !add_weak)
1732 add_weak++;
1733 break;
1734 }
1735 assert(PyType_Check(tmp));
1736 tmptype = (PyTypeObject *)tmp;
1737 if (may_add_dict && !add_dict &&
1738 tmptype->tp_dictoffset != 0)
1739 add_dict++;
1740 if (may_add_weak && !add_weak &&
1741 tmptype->tp_weaklistoffset != 0)
1742 add_weak++;
1743 if (may_add_dict && !add_dict)
1744 continue;
1745 if (may_add_weak && !add_weak)
1746 continue;
1747 /* Nothing more to check */
1748 break;
1749 }
1750 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001751 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001752
1753 /* XXX From here until type is safely allocated,
1754 "return NULL" may leak slots! */
1755
1756 /* Allocate the type object */
1757 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
Guido van Rossumad47da02002-08-12 19:05:44 +00001758 if (type == NULL) {
1759 Py_XDECREF(slots);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001760 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00001761 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001762
1763 /* Keep name and slots alive in the extended type object */
Guido van Rossume5c691a2003-03-07 15:13:17 +00001764 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001765 Py_INCREF(name);
1766 et->name = name;
1767 et->slots = slots;
1768
Guido van Rossumdc91b992001-08-08 22:26:22 +00001769 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001770 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
1771 Py_TPFLAGS_BASETYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00001772 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
1773 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00001774
1775 /* It's a new-style number unless it specifically inherits any
1776 old-style numeric behavior */
1777 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
1778 (base->tp_as_number == NULL))
1779 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
1780
1781 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001782 type->tp_as_number = &et->as_number;
1783 type->tp_as_sequence = &et->as_sequence;
1784 type->tp_as_mapping = &et->as_mapping;
1785 type->tp_as_buffer = &et->as_buffer;
1786 type->tp_name = PyString_AS_STRING(name);
1787
1788 /* Set tp_base and tp_bases */
1789 type->tp_bases = bases;
1790 Py_INCREF(base);
1791 type->tp_base = base;
1792
Guido van Rossum687ae002001-10-15 22:03:32 +00001793 /* Initialize tp_dict from passed-in dict */
1794 type->tp_dict = dict = PyDict_Copy(dict);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001795 if (dict == NULL) {
1796 Py_DECREF(type);
1797 return NULL;
1798 }
1799
Guido van Rossumc3542212001-08-16 09:18:56 +00001800 /* Set __module__ in the dict */
1801 if (PyDict_GetItemString(dict, "__module__") == NULL) {
1802 tmp = PyEval_GetGlobals();
1803 if (tmp != NULL) {
1804 tmp = PyDict_GetItemString(tmp, "__name__");
1805 if (tmp != NULL) {
1806 if (PyDict_SetItemString(dict, "__module__",
1807 tmp) < 0)
1808 return NULL;
1809 }
1810 }
1811 }
1812
Tim Peters2f93e282001-10-04 05:27:00 +00001813 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
Tim Peters24008312002-03-17 18:56:20 +00001814 and is a string. The __doc__ accessor will first look for tp_doc;
1815 if that fails, it will still look into __dict__.
Tim Peters2f93e282001-10-04 05:27:00 +00001816 */
1817 {
1818 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
1819 if (doc != NULL && PyString_Check(doc)) {
1820 const size_t n = (size_t)PyString_GET_SIZE(doc);
Tim Peters59f809d2001-10-04 05:43:02 +00001821 type->tp_doc = (char *)PyObject_MALLOC(n+1);
Tim Peters2f93e282001-10-04 05:27:00 +00001822 if (type->tp_doc == NULL) {
1823 Py_DECREF(type);
1824 return NULL;
1825 }
1826 memcpy(type->tp_doc, PyString_AS_STRING(doc), n+1);
1827 }
1828 }
1829
Tim Peters6d6c1a32001-08-02 04:15:00 +00001830 /* Special-case __new__: if it's a plain function,
1831 make it a static function */
1832 tmp = PyDict_GetItemString(dict, "__new__");
1833 if (tmp != NULL && PyFunction_Check(tmp)) {
1834 tmp = PyStaticMethod_New(tmp);
1835 if (tmp == NULL) {
1836 Py_DECREF(type);
1837 return NULL;
1838 }
1839 PyDict_SetItemString(dict, "__new__", tmp);
1840 Py_DECREF(tmp);
1841 }
1842
1843 /* Add descriptors for custom slots from __slots__, or for __dict__ */
Guido van Rossume5c691a2003-03-07 15:13:17 +00001844 mp = PyHeapType_GET_MEMBERS(et);
Neil Schemenauerc806c882001-08-29 23:54:54 +00001845 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001846 if (slots != NULL) {
1847 for (i = 0; i < nslots; i++, mp++) {
1848 mp->name = PyString_AS_STRING(
1849 PyTuple_GET_ITEM(slots, i));
Guido van Rossum64b206c2001-12-04 17:13:22 +00001850 mp->type = T_OBJECT_EX;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001851 mp->offset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +00001852 if (base->tp_weaklistoffset == 0 &&
Guido van Rossum64b206c2001-12-04 17:13:22 +00001853 strcmp(mp->name, "__weakref__") == 0) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001854 add_weak++;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001855 mp->type = T_OBJECT;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001856 mp->flags = READONLY;
Guido van Rossum9676b222001-08-17 20:32:36 +00001857 type->tp_weaklistoffset = slotoffset;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001858 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001859 slotoffset += sizeof(PyObject *);
1860 }
1861 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001862 if (add_dict) {
1863 if (base->tp_itemsize)
1864 type->tp_dictoffset = -(long)sizeof(PyObject *);
1865 else
1866 type->tp_dictoffset = slotoffset;
1867 slotoffset += sizeof(PyObject *);
1868 }
1869 if (add_weak) {
1870 assert(!base->tp_itemsize);
1871 type->tp_weaklistoffset = slotoffset;
1872 slotoffset += sizeof(PyObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001873 }
1874 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001875 type->tp_itemsize = base->tp_itemsize;
Guido van Rossume5c691a2003-03-07 15:13:17 +00001876 type->tp_members = PyHeapType_GET_MEMBERS(et);
Guido van Rossum373c7412003-01-07 13:41:37 +00001877
1878 if (type->tp_weaklistoffset && type->tp_dictoffset)
1879 type->tp_getset = subtype_getsets_full;
1880 else if (type->tp_weaklistoffset && !type->tp_dictoffset)
1881 type->tp_getset = subtype_getsets_weakref_only;
1882 else if (!type->tp_weaklistoffset && type->tp_dictoffset)
1883 type->tp_getset = subtype_getsets_dict_only;
1884 else
1885 type->tp_getset = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001886
1887 /* Special case some slots */
1888 if (type->tp_dictoffset != 0 || nslots > 0) {
1889 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
1890 type->tp_getattro = PyObject_GenericGetAttr;
1891 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
1892 type->tp_setattro = PyObject_GenericSetAttr;
1893 }
1894 type->tp_dealloc = subtype_dealloc;
1895
Guido van Rossum9475a232001-10-05 20:51:39 +00001896 /* Enable GC unless there are really no instance variables possible */
1897 if (!(type->tp_basicsize == sizeof(PyObject) &&
1898 type->tp_itemsize == 0))
1899 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
1900
Tim Peters6d6c1a32001-08-02 04:15:00 +00001901 /* Always override allocation strategy to use regular heap */
1902 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00001903 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001904 type->tp_free = PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00001905 type->tp_traverse = subtype_traverse;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001906 type->tp_clear = subtype_clear;
Guido van Rossum048eb752001-10-02 21:24:57 +00001907 }
1908 else
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001909 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001910
1911 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001912 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001913 Py_DECREF(type);
1914 return NULL;
1915 }
1916
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001917 /* Put the proper slots in place */
1918 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00001919
Tim Peters6d6c1a32001-08-02 04:15:00 +00001920 return (PyObject *)type;
1921}
1922
1923/* Internal API to look for a name through the MRO.
1924 This returns a borrowed reference, and doesn't set an exception! */
1925PyObject *
1926_PyType_Lookup(PyTypeObject *type, PyObject *name)
1927{
1928 int i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00001929 PyObject *mro, *res, *base, *dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001930
Guido van Rossum687ae002001-10-15 22:03:32 +00001931 /* Look in tp_dict of types in MRO */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001932 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00001933
1934 /* If mro is NULL, the type is either not yet initialized
1935 by PyType_Ready(), or already cleared by type_clear().
1936 Either way the safest thing to do is to return NULL. */
1937 if (mro == NULL)
1938 return NULL;
1939
Tim Peters6d6c1a32001-08-02 04:15:00 +00001940 assert(PyTuple_Check(mro));
1941 n = PyTuple_GET_SIZE(mro);
1942 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001943 base = PyTuple_GET_ITEM(mro, i);
1944 if (PyClass_Check(base))
1945 dict = ((PyClassObject *)base)->cl_dict;
1946 else {
1947 assert(PyType_Check(base));
1948 dict = ((PyTypeObject *)base)->tp_dict;
1949 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001950 assert(dict && PyDict_Check(dict));
1951 res = PyDict_GetItem(dict, name);
1952 if (res != NULL)
1953 return res;
1954 }
1955 return NULL;
1956}
1957
1958/* This is similar to PyObject_GenericGetAttr(),
1959 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
1960static PyObject *
1961type_getattro(PyTypeObject *type, PyObject *name)
1962{
1963 PyTypeObject *metatype = type->ob_type;
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001964 PyObject *meta_attribute, *attribute;
1965 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001966
1967 /* Initialize this type (we'll assume the metatype is initialized) */
1968 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001969 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001970 return NULL;
1971 }
1972
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001973 /* No readable descriptor found yet */
1974 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00001975
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001976 /* Look for the attribute in the metatype */
1977 meta_attribute = _PyType_Lookup(metatype, name);
1978
1979 if (meta_attribute != NULL) {
1980 meta_get = meta_attribute->ob_type->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00001981
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001982 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
1983 /* Data descriptors implement tp_descr_set to intercept
1984 * writes. Assume the attribute is not overridden in
1985 * type's tp_dict (and bases): call the descriptor now.
1986 */
1987 return meta_get(meta_attribute, (PyObject *)type,
1988 (PyObject *)metatype);
1989 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001990 }
1991
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001992 /* No data descriptor found on metatype. Look in tp_dict of this
1993 * type and its bases */
1994 attribute = _PyType_Lookup(type, name);
1995 if (attribute != NULL) {
1996 /* Implement descriptor functionality, if any */
1997 descrgetfunc local_get = attribute->ob_type->tp_descr_get;
1998 if (local_get != NULL) {
1999 /* NULL 2nd argument indicates the descriptor was
2000 * found on the target object itself (or a base) */
2001 return local_get(attribute, (PyObject *)NULL,
2002 (PyObject *)type);
2003 }
Tim Peters34592512002-07-11 06:23:50 +00002004
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002005 Py_INCREF(attribute);
2006 return attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002007 }
2008
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002009 /* No attribute found in local __dict__ (or bases): use the
2010 * descriptor from the metatype, if any */
2011 if (meta_get != NULL)
2012 return meta_get(meta_attribute, (PyObject *)type,
2013 (PyObject *)metatype);
2014
2015 /* If an ordinary attribute was found on the metatype, return it now */
2016 if (meta_attribute != NULL) {
2017 Py_INCREF(meta_attribute);
2018 return meta_attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002019 }
2020
2021 /* Give up */
2022 PyErr_Format(PyExc_AttributeError,
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002023 "type object '%.50s' has no attribute '%.400s'",
2024 type->tp_name, PyString_AS_STRING(name));
Tim Peters6d6c1a32001-08-02 04:15:00 +00002025 return NULL;
2026}
2027
2028static int
2029type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
2030{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002031 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2032 PyErr_Format(
2033 PyExc_TypeError,
2034 "can't set attributes of built-in/extension type '%s'",
2035 type->tp_name);
2036 return -1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002037 }
Guido van Rossum8d24ee92003-03-24 23:49:49 +00002038 /* XXX Example of how I expect this to be used...
2039 if (update_subclasses(type, name, invalidate_cache, NULL) < 0)
2040 return -1;
2041 */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002042 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
2043 return -1;
2044 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002045}
2046
2047static void
2048type_dealloc(PyTypeObject *type)
2049{
Guido van Rossume5c691a2003-03-07 15:13:17 +00002050 PyHeapTypeObject *et;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002051
2052 /* Assert this is a heap-allocated type object */
2053 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002054 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00002055 PyObject_ClearWeakRefs((PyObject *)type);
Guido van Rossume5c691a2003-03-07 15:13:17 +00002056 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002057 Py_XDECREF(type->tp_base);
2058 Py_XDECREF(type->tp_dict);
2059 Py_XDECREF(type->tp_bases);
2060 Py_XDECREF(type->tp_mro);
Guido van Rossum687ae002001-10-15 22:03:32 +00002061 Py_XDECREF(type->tp_cache);
Guido van Rossum1c450732001-10-08 15:18:27 +00002062 Py_XDECREF(type->tp_subclasses);
Neal Norwitzcee5ca02002-07-30 00:42:06 +00002063 PyObject_Free(type->tp_doc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002064 Py_XDECREF(et->name);
2065 Py_XDECREF(et->slots);
2066 type->ob_type->tp_free((PyObject *)type);
2067}
2068
Guido van Rossum1c450732001-10-08 15:18:27 +00002069static PyObject *
2070type_subclasses(PyTypeObject *type, PyObject *args_ignored)
2071{
2072 PyObject *list, *raw, *ref;
2073 int i, n;
2074
2075 list = PyList_New(0);
2076 if (list == NULL)
2077 return NULL;
2078 raw = type->tp_subclasses;
2079 if (raw == NULL)
2080 return list;
2081 assert(PyList_Check(raw));
2082 n = PyList_GET_SIZE(raw);
2083 for (i = 0; i < n; i++) {
2084 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00002085 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00002086 ref = PyWeakref_GET_OBJECT(ref);
2087 if (ref != Py_None) {
2088 if (PyList_Append(list, ref) < 0) {
2089 Py_DECREF(list);
2090 return NULL;
2091 }
2092 }
2093 }
2094 return list;
2095}
2096
Tim Peters6d6c1a32001-08-02 04:15:00 +00002097static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002098 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002099 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
Guido van Rossum1c450732001-10-08 15:18:27 +00002100 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002101 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002102 {0}
2103};
2104
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002105PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002106"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002107"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002108
Guido van Rossum048eb752001-10-02 21:24:57 +00002109static int
2110type_traverse(PyTypeObject *type, visitproc visit, void *arg)
2111{
Guido van Rossum048eb752001-10-02 21:24:57 +00002112 int err;
2113
Guido van Rossuma3862092002-06-10 15:24:42 +00002114 /* Because of type_is_gc(), the collector only calls this
2115 for heaptypes. */
2116 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002117
2118#define VISIT(SLOT) \
2119 if (SLOT) { \
2120 err = visit((PyObject *)(SLOT), arg); \
2121 if (err) \
2122 return err; \
2123 }
2124
2125 VISIT(type->tp_dict);
Guido van Rossum687ae002001-10-15 22:03:32 +00002126 VISIT(type->tp_cache);
Guido van Rossum048eb752001-10-02 21:24:57 +00002127 VISIT(type->tp_mro);
2128 VISIT(type->tp_bases);
2129 VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00002130
2131 /* There's no need to visit type->tp_subclasses or
Guido van Rossume5c691a2003-03-07 15:13:17 +00002132 ((PyHeapTypeObject *)type)->slots, because they can't be involved
Guido van Rossuma3862092002-06-10 15:24:42 +00002133 in cycles; tp_subclasses is a list of weak references,
2134 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00002135
2136#undef VISIT
2137
2138 return 0;
2139}
2140
2141static int
2142type_clear(PyTypeObject *type)
2143{
Guido van Rossum048eb752001-10-02 21:24:57 +00002144 PyObject *tmp;
2145
Guido van Rossuma3862092002-06-10 15:24:42 +00002146 /* Because of type_is_gc(), the collector only calls this
2147 for heaptypes. */
2148 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002149
2150#define CLEAR(SLOT) \
2151 if (SLOT) { \
2152 tmp = (PyObject *)(SLOT); \
2153 SLOT = NULL; \
2154 Py_DECREF(tmp); \
2155 }
2156
Guido van Rossuma3862092002-06-10 15:24:42 +00002157 /* The only field we need to clear is tp_mro, which is part of a
2158 hard cycle (its first element is the class itself) that won't
2159 be broken otherwise (it's a tuple and tuples don't have a
2160 tp_clear handler). None of the other fields need to be
2161 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00002162
Guido van Rossuma3862092002-06-10 15:24:42 +00002163 tp_dict:
2164 It is a dict, so the collector will call its tp_clear.
2165
2166 tp_cache:
2167 Not used; if it were, it would be a dict.
2168
2169 tp_bases, tp_base:
2170 If these are involved in a cycle, there must be at least
2171 one other, mutable object in the cycle, e.g. a base
2172 class's dict; the cycle will be broken that way.
2173
2174 tp_subclasses:
2175 A list of weak references can't be part of a cycle; and
2176 lists have their own tp_clear.
2177
Guido van Rossume5c691a2003-03-07 15:13:17 +00002178 slots (in PyHeapTypeObject):
Guido van Rossuma3862092002-06-10 15:24:42 +00002179 A tuple of strings can't be part of a cycle.
2180 */
2181
2182 CLEAR(type->tp_mro);
Tim Peters2f93e282001-10-04 05:27:00 +00002183
Guido van Rossum048eb752001-10-02 21:24:57 +00002184#undef CLEAR
2185
2186 return 0;
2187}
2188
2189static int
2190type_is_gc(PyTypeObject *type)
2191{
2192 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
2193}
2194
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002195PyTypeObject PyType_Type = {
2196 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002197 0, /* ob_size */
2198 "type", /* tp_name */
Guido van Rossume5c691a2003-03-07 15:13:17 +00002199 sizeof(PyHeapTypeObject), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00002200 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002201 (destructor)type_dealloc, /* tp_dealloc */
2202 0, /* tp_print */
2203 0, /* tp_getattr */
2204 0, /* tp_setattr */
2205 type_compare, /* tp_compare */
2206 (reprfunc)type_repr, /* tp_repr */
2207 0, /* tp_as_number */
2208 0, /* tp_as_sequence */
2209 0, /* tp_as_mapping */
2210 (hashfunc)_Py_HashPointer, /* tp_hash */
2211 (ternaryfunc)type_call, /* tp_call */
2212 0, /* tp_str */
2213 (getattrofunc)type_getattro, /* tp_getattro */
2214 (setattrofunc)type_setattro, /* tp_setattro */
2215 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00002216 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2217 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002218 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00002219 (traverseproc)type_traverse, /* tp_traverse */
2220 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002221 0, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00002222 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002223 0, /* tp_iter */
2224 0, /* tp_iternext */
2225 type_methods, /* tp_methods */
2226 type_members, /* tp_members */
2227 type_getsets, /* tp_getset */
2228 0, /* tp_base */
2229 0, /* tp_dict */
2230 0, /* tp_descr_get */
2231 0, /* tp_descr_set */
2232 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
2233 0, /* tp_init */
2234 0, /* tp_alloc */
2235 type_new, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002236 PyObject_GC_Del, /* tp_free */
Guido van Rossum048eb752001-10-02 21:24:57 +00002237 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002238};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002239
2240
2241/* The base type of all types (eventually)... except itself. */
2242
2243static int
2244object_init(PyObject *self, PyObject *args, PyObject *kwds)
2245{
2246 return 0;
2247}
2248
Guido van Rossum298e4212003-02-13 16:30:16 +00002249/* If we don't have a tp_new for a new-style class, new will use this one.
2250 Therefore this should take no arguments/keywords. However, this new may
2251 also be inherited by objects that define a tp_init but no tp_new. These
2252 objects WILL pass argumets to tp_new, because it gets the same args as
2253 tp_init. So only allow arguments if we aren't using the default init, in
2254 which case we expect init to handle argument parsing. */
2255static PyObject *
2256object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2257{
2258 if (type->tp_init == object_init && (PyTuple_GET_SIZE(args) ||
2259 (kwds && PyDict_Check(kwds) && PyDict_Size(kwds)))) {
2260 PyErr_SetString(PyExc_TypeError,
2261 "default __new__ takes no parameters");
2262 return NULL;
2263 }
2264 return type->tp_alloc(type, 0);
2265}
2266
Tim Peters6d6c1a32001-08-02 04:15:00 +00002267static void
2268object_dealloc(PyObject *self)
2269{
2270 self->ob_type->tp_free(self);
2271}
2272
Guido van Rossum8e248182001-08-12 05:17:56 +00002273static PyObject *
2274object_repr(PyObject *self)
2275{
Guido van Rossum76e69632001-08-16 18:52:43 +00002276 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00002277 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002278
Guido van Rossum76e69632001-08-16 18:52:43 +00002279 type = self->ob_type;
2280 mod = type_module(type, NULL);
2281 if (mod == NULL)
2282 PyErr_Clear();
2283 else if (!PyString_Check(mod)) {
2284 Py_DECREF(mod);
2285 mod = NULL;
2286 }
2287 name = type_name(type, NULL);
2288 if (name == NULL)
2289 return NULL;
2290 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002291 rtn = PyString_FromFormat("<%s.%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002292 PyString_AS_STRING(mod),
2293 PyString_AS_STRING(name),
2294 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002295 else
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002296 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002297 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002298 Py_XDECREF(mod);
2299 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00002300 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002301}
2302
Guido van Rossumb8f63662001-08-15 23:57:02 +00002303static PyObject *
2304object_str(PyObject *self)
2305{
2306 unaryfunc f;
2307
2308 f = self->ob_type->tp_repr;
2309 if (f == NULL)
2310 f = object_repr;
2311 return f(self);
2312}
2313
Guido van Rossum8e248182001-08-12 05:17:56 +00002314static long
2315object_hash(PyObject *self)
2316{
2317 return _Py_HashPointer(self);
2318}
Guido van Rossum8e248182001-08-12 05:17:56 +00002319
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002320static PyObject *
2321object_get_class(PyObject *self, void *closure)
2322{
2323 Py_INCREF(self->ob_type);
2324 return (PyObject *)(self->ob_type);
2325}
2326
2327static int
2328equiv_structs(PyTypeObject *a, PyTypeObject *b)
2329{
2330 return a == b ||
2331 (a != NULL &&
2332 b != NULL &&
2333 a->tp_basicsize == b->tp_basicsize &&
2334 a->tp_itemsize == b->tp_itemsize &&
2335 a->tp_dictoffset == b->tp_dictoffset &&
2336 a->tp_weaklistoffset == b->tp_weaklistoffset &&
2337 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
2338 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
2339}
2340
2341static int
2342same_slots_added(PyTypeObject *a, PyTypeObject *b)
2343{
2344 PyTypeObject *base = a->tp_base;
2345 int size;
2346
2347 if (base != b->tp_base)
2348 return 0;
2349 if (equiv_structs(a, base) && equiv_structs(b, base))
2350 return 1;
2351 size = base->tp_basicsize;
2352 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
2353 size += sizeof(PyObject *);
2354 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
2355 size += sizeof(PyObject *);
2356 return size == a->tp_basicsize && size == b->tp_basicsize;
2357}
2358
2359static int
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002360compatible_for_assignment(PyTypeObject* old, PyTypeObject* new, char* attr)
2361{
2362 PyTypeObject *newbase, *oldbase;
2363
2364 if (new->tp_dealloc != old->tp_dealloc ||
2365 new->tp_free != old->tp_free)
2366 {
2367 PyErr_Format(PyExc_TypeError,
2368 "%s assignment: "
2369 "'%s' deallocator differs from '%s'",
2370 attr,
2371 new->tp_name,
2372 old->tp_name);
2373 return 0;
2374 }
2375 newbase = new;
2376 oldbase = old;
2377 while (equiv_structs(newbase, newbase->tp_base))
2378 newbase = newbase->tp_base;
2379 while (equiv_structs(oldbase, oldbase->tp_base))
2380 oldbase = oldbase->tp_base;
2381 if (newbase != oldbase &&
2382 (newbase->tp_base != oldbase->tp_base ||
2383 !same_slots_added(newbase, oldbase))) {
2384 PyErr_Format(PyExc_TypeError,
2385 "%s assignment: "
2386 "'%s' object layout differs from '%s'",
2387 attr,
2388 new->tp_name,
2389 old->tp_name);
2390 return 0;
2391 }
Tim Petersea7f75d2002-12-07 21:39:16 +00002392
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002393 return 1;
2394}
2395
2396static int
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002397object_set_class(PyObject *self, PyObject *value, void *closure)
2398{
2399 PyTypeObject *old = self->ob_type;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002400 PyTypeObject *new;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002401
Guido van Rossumb6b89422002-04-15 01:03:30 +00002402 if (value == NULL) {
2403 PyErr_SetString(PyExc_TypeError,
2404 "can't delete __class__ attribute");
2405 return -1;
2406 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002407 if (!PyType_Check(value)) {
2408 PyErr_Format(PyExc_TypeError,
2409 "__class__ must be set to new-style class, not '%s' object",
2410 value->ob_type->tp_name);
2411 return -1;
2412 }
2413 new = (PyTypeObject *)value;
Guido van Rossum40af8892002-08-10 05:42:07 +00002414 if (!(new->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
2415 !(old->tp_flags & Py_TPFLAGS_HEAPTYPE))
2416 {
2417 PyErr_Format(PyExc_TypeError,
2418 "__class__ assignment: only for heap types");
2419 return -1;
2420 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002421 if (compatible_for_assignment(new, old, "__class__")) {
2422 Py_INCREF(new);
2423 self->ob_type = new;
2424 Py_DECREF(old);
2425 return 0;
2426 }
2427 else {
Guido van Rossum9ee4b942002-05-24 18:47:47 +00002428 return -1;
2429 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002430}
2431
2432static PyGetSetDef object_getsets[] = {
2433 {"__class__", object_get_class, object_set_class,
Neal Norwitz858e34f2002-08-13 17:18:45 +00002434 PyDoc_STR("the object's class")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002435 {0}
2436};
2437
Guido van Rossumc53f0092003-02-18 22:05:12 +00002438
Guido van Rossum036f9992003-02-21 22:02:54 +00002439/* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
2440 We fall back to helpers in copy_reg for:
2441 - pickle protocols < 2
2442 - calculating the list of slot names (done only once per class)
2443 - the __newobj__ function (which is used as a token but never called)
2444*/
2445
2446static PyObject *
2447import_copy_reg(void)
2448{
2449 static PyObject *copy_reg_str;
Guido van Rossum3926a632001-09-25 16:25:58 +00002450
2451 if (!copy_reg_str) {
2452 copy_reg_str = PyString_InternFromString("copy_reg");
2453 if (copy_reg_str == NULL)
2454 return NULL;
2455 }
Guido van Rossum036f9992003-02-21 22:02:54 +00002456
2457 return PyImport_Import(copy_reg_str);
2458}
2459
2460static PyObject *
2461slotnames(PyObject *cls)
2462{
2463 PyObject *clsdict;
2464 PyObject *copy_reg;
2465 PyObject *slotnames;
2466
2467 if (!PyType_Check(cls)) {
2468 Py_INCREF(Py_None);
2469 return Py_None;
2470 }
2471
2472 clsdict = ((PyTypeObject *)cls)->tp_dict;
2473 slotnames = PyDict_GetItemString(clsdict, "__slotnames__");
2474 if (slotnames != NULL) {
2475 Py_INCREF(slotnames);
2476 return slotnames;
2477 }
2478
2479 copy_reg = import_copy_reg();
2480 if (copy_reg == NULL)
2481 return NULL;
2482
2483 slotnames = PyObject_CallMethod(copy_reg, "_slotnames", "O", cls);
2484 Py_DECREF(copy_reg);
2485 if (slotnames != NULL &&
2486 slotnames != Py_None &&
2487 !PyList_Check(slotnames))
2488 {
2489 PyErr_SetString(PyExc_TypeError,
2490 "copy_reg._slotnames didn't return a list or None");
2491 Py_DECREF(slotnames);
2492 slotnames = NULL;
2493 }
2494
2495 return slotnames;
2496}
2497
2498static PyObject *
2499reduce_2(PyObject *obj)
2500{
2501 PyObject *cls, *getnewargs;
2502 PyObject *args = NULL, *args2 = NULL;
2503 PyObject *getstate = NULL, *state = NULL, *names = NULL;
2504 PyObject *slots = NULL, *listitems = NULL, *dictitems = NULL;
2505 PyObject *copy_reg = NULL, *newobj = NULL, *res = NULL;
2506 int i, n;
2507
2508 cls = PyObject_GetAttrString(obj, "__class__");
2509 if (cls == NULL)
2510 return NULL;
2511
2512 getnewargs = PyObject_GetAttrString(obj, "__getnewargs__");
2513 if (getnewargs != NULL) {
2514 args = PyObject_CallObject(getnewargs, NULL);
2515 Py_DECREF(getnewargs);
2516 if (args != NULL && !PyTuple_Check(args)) {
2517 PyErr_SetString(PyExc_TypeError,
2518 "__getnewargs__ should return a tuple");
2519 goto end;
2520 }
2521 }
2522 else {
2523 PyErr_Clear();
2524 args = PyTuple_New(0);
2525 }
2526 if (args == NULL)
2527 goto end;
2528
2529 getstate = PyObject_GetAttrString(obj, "__getstate__");
2530 if (getstate != NULL) {
2531 state = PyObject_CallObject(getstate, NULL);
2532 Py_DECREF(getstate);
2533 }
2534 else {
2535 state = PyObject_GetAttrString(obj, "__dict__");
2536 if (state == NULL) {
2537 PyErr_Clear();
2538 state = Py_None;
2539 Py_INCREF(state);
2540 }
2541 names = slotnames(cls);
2542 if (names == NULL)
2543 goto end;
2544 if (names != Py_None) {
2545 assert(PyList_Check(names));
2546 slots = PyDict_New();
2547 if (slots == NULL)
2548 goto end;
2549 n = 0;
2550 /* Can't pre-compute the list size; the list
2551 is stored on the class so accessible to other
2552 threads, which may be run by DECREF */
2553 for (i = 0; i < PyList_GET_SIZE(names); i++) {
2554 PyObject *name, *value;
2555 name = PyList_GET_ITEM(names, i);
2556 value = PyObject_GetAttr(obj, name);
2557 if (value == NULL)
2558 PyErr_Clear();
2559 else {
2560 int err = PyDict_SetItem(slots, name,
2561 value);
2562 Py_DECREF(value);
2563 if (err)
2564 goto end;
2565 n++;
2566 }
2567 }
2568 if (n) {
2569 state = Py_BuildValue("(NO)", state, slots);
2570 if (state == NULL)
2571 goto end;
2572 }
2573 }
2574 }
2575
2576 if (!PyList_Check(obj)) {
2577 listitems = Py_None;
2578 Py_INCREF(listitems);
2579 }
2580 else {
2581 listitems = PyObject_GetIter(obj);
2582 if (listitems == NULL)
2583 goto end;
2584 }
2585
2586 if (!PyDict_Check(obj)) {
2587 dictitems = Py_None;
2588 Py_INCREF(dictitems);
2589 }
2590 else {
2591 dictitems = PyObject_CallMethod(obj, "iteritems", "");
2592 if (dictitems == NULL)
2593 goto end;
2594 }
2595
2596 copy_reg = import_copy_reg();
2597 if (copy_reg == NULL)
2598 goto end;
2599 newobj = PyObject_GetAttrString(copy_reg, "__newobj__");
2600 if (newobj == NULL)
2601 goto end;
2602
2603 n = PyTuple_GET_SIZE(args);
2604 args2 = PyTuple_New(n+1);
2605 if (args2 == NULL)
2606 goto end;
2607 PyTuple_SET_ITEM(args2, 0, cls);
2608 cls = NULL;
2609 for (i = 0; i < n; i++) {
2610 PyObject *v = PyTuple_GET_ITEM(args, i);
2611 Py_INCREF(v);
2612 PyTuple_SET_ITEM(args2, i+1, v);
2613 }
2614
2615 res = Py_BuildValue("(OOOOO)",
2616 newobj, args2, state, listitems, dictitems);
2617
2618 end:
2619 Py_XDECREF(cls);
2620 Py_XDECREF(args);
2621 Py_XDECREF(args2);
Jeremy Hyltond06483c2003-04-09 21:01:42 +00002622 Py_XDECREF(slots);
Guido van Rossum036f9992003-02-21 22:02:54 +00002623 Py_XDECREF(state);
2624 Py_XDECREF(names);
2625 Py_XDECREF(listitems);
2626 Py_XDECREF(dictitems);
2627 Py_XDECREF(copy_reg);
2628 Py_XDECREF(newobj);
2629 return res;
2630}
2631
2632static PyObject *
2633object_reduce_ex(PyObject *self, PyObject *args)
2634{
2635 /* Call copy_reg._reduce_ex(self, proto) */
2636 PyObject *reduce, *copy_reg, *res;
2637 int proto = 0;
2638
2639 if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
2640 return NULL;
2641
2642 reduce = PyObject_GetAttrString(self, "__reduce__");
2643 if (reduce == NULL)
2644 PyErr_Clear();
2645 else {
2646 PyObject *cls, *clsreduce, *objreduce;
2647 int override;
2648 cls = PyObject_GetAttrString(self, "__class__");
2649 if (cls == NULL) {
2650 Py_DECREF(reduce);
2651 return NULL;
2652 }
2653 clsreduce = PyObject_GetAttrString(cls, "__reduce__");
2654 Py_DECREF(cls);
2655 if (clsreduce == NULL) {
2656 Py_DECREF(reduce);
2657 return NULL;
2658 }
2659 objreduce = PyDict_GetItemString(PyBaseObject_Type.tp_dict,
2660 "__reduce__");
2661 override = (clsreduce != objreduce);
2662 Py_DECREF(clsreduce);
2663 if (override) {
2664 res = PyObject_CallObject(reduce, NULL);
2665 Py_DECREF(reduce);
2666 return res;
2667 }
2668 else
2669 Py_DECREF(reduce);
2670 }
2671
2672 if (proto >= 2)
2673 return reduce_2(self);
2674
2675 copy_reg = import_copy_reg();
Guido van Rossum3926a632001-09-25 16:25:58 +00002676 if (!copy_reg)
2677 return NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00002678
Guido van Rossumc53f0092003-02-18 22:05:12 +00002679 res = PyEval_CallMethod(copy_reg, "_reduce_ex", "(Oi)", self, proto);
Guido van Rossum3926a632001-09-25 16:25:58 +00002680 Py_DECREF(copy_reg);
Guido van Rossum036f9992003-02-21 22:02:54 +00002681
Guido van Rossum3926a632001-09-25 16:25:58 +00002682 return res;
2683}
2684
2685static PyMethodDef object_methods[] = {
Guido van Rossumc53f0092003-02-18 22:05:12 +00002686 {"__reduce_ex__", object_reduce_ex, METH_VARARGS,
2687 PyDoc_STR("helper for pickle")},
2688 {"__reduce__", object_reduce_ex, METH_VARARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002689 PyDoc_STR("helper for pickle")},
Guido van Rossum3926a632001-09-25 16:25:58 +00002690 {0}
2691};
2692
Guido van Rossum036f9992003-02-21 22:02:54 +00002693
Tim Peters6d6c1a32001-08-02 04:15:00 +00002694PyTypeObject PyBaseObject_Type = {
2695 PyObject_HEAD_INIT(&PyType_Type)
2696 0, /* ob_size */
2697 "object", /* tp_name */
2698 sizeof(PyObject), /* tp_basicsize */
2699 0, /* tp_itemsize */
2700 (destructor)object_dealloc, /* tp_dealloc */
2701 0, /* tp_print */
2702 0, /* tp_getattr */
2703 0, /* tp_setattr */
2704 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002705 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002706 0, /* tp_as_number */
2707 0, /* tp_as_sequence */
2708 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002709 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002710 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002711 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002712 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002713 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002714 0, /* tp_as_buffer */
2715 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002716 PyDoc_STR("The most base type"), /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002717 0, /* tp_traverse */
2718 0, /* tp_clear */
2719 0, /* tp_richcompare */
2720 0, /* tp_weaklistoffset */
2721 0, /* tp_iter */
2722 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00002723 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002724 0, /* tp_members */
2725 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002726 0, /* tp_base */
2727 0, /* tp_dict */
2728 0, /* tp_descr_get */
2729 0, /* tp_descr_set */
2730 0, /* tp_dictoffset */
2731 object_init, /* tp_init */
2732 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossum298e4212003-02-13 16:30:16 +00002733 object_new, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002734 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002735};
2736
2737
2738/* Initialize the __dict__ in a type object */
2739
2740static int
2741add_methods(PyTypeObject *type, PyMethodDef *meth)
2742{
Guido van Rossum687ae002001-10-15 22:03:32 +00002743 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002744
2745 for (; meth->ml_name != NULL; meth++) {
2746 PyObject *descr;
2747 if (PyDict_GetItemString(dict, meth->ml_name))
2748 continue;
Fred Drake7bf97152002-03-28 05:33:33 +00002749 if (meth->ml_flags & METH_CLASS) {
2750 if (meth->ml_flags & METH_STATIC) {
2751 PyErr_SetString(PyExc_ValueError,
2752 "method cannot be both class and static");
2753 return -1;
2754 }
Tim Petersbca1cbc2002-12-09 22:56:13 +00002755 descr = PyDescr_NewClassMethod(type, meth);
Fred Drake7bf97152002-03-28 05:33:33 +00002756 }
2757 else if (meth->ml_flags & METH_STATIC) {
Guido van Rossum9af48ff2003-02-11 17:12:46 +00002758 PyObject *cfunc = PyCFunction_New(meth, NULL);
2759 if (cfunc == NULL)
2760 return -1;
2761 descr = PyStaticMethod_New(cfunc);
2762 Py_DECREF(cfunc);
Fred Drake7bf97152002-03-28 05:33:33 +00002763 }
2764 else {
2765 descr = PyDescr_NewMethod(type, meth);
2766 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002767 if (descr == NULL)
2768 return -1;
Fred Drake7bf97152002-03-28 05:33:33 +00002769 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002770 return -1;
2771 Py_DECREF(descr);
2772 }
2773 return 0;
2774}
2775
2776static int
Guido van Rossum6f799372001-09-20 20:46:19 +00002777add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002778{
Guido van Rossum687ae002001-10-15 22:03:32 +00002779 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002780
2781 for (; memb->name != NULL; memb++) {
2782 PyObject *descr;
2783 if (PyDict_GetItemString(dict, memb->name))
2784 continue;
2785 descr = PyDescr_NewMember(type, memb);
2786 if (descr == NULL)
2787 return -1;
2788 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
2789 return -1;
2790 Py_DECREF(descr);
2791 }
2792 return 0;
2793}
2794
2795static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00002796add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002797{
Guido van Rossum687ae002001-10-15 22:03:32 +00002798 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002799
2800 for (; gsp->name != NULL; gsp++) {
2801 PyObject *descr;
2802 if (PyDict_GetItemString(dict, gsp->name))
2803 continue;
2804 descr = PyDescr_NewGetSet(type, gsp);
2805
2806 if (descr == NULL)
2807 return -1;
2808 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
2809 return -1;
2810 Py_DECREF(descr);
2811 }
2812 return 0;
2813}
2814
Guido van Rossum13d52f02001-08-10 21:24:08 +00002815static void
2816inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002817{
2818 int oldsize, newsize;
2819
Guido van Rossum13d52f02001-08-10 21:24:08 +00002820 /* Special flag magic */
2821 if (!type->tp_as_buffer && base->tp_as_buffer) {
2822 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
2823 type->tp_flags |=
2824 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
2825 }
2826 if (!type->tp_as_sequence && base->tp_as_sequence) {
2827 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
2828 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
2829 }
2830 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
2831 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
2832 if ((!type->tp_as_number && base->tp_as_number) ||
2833 (!type->tp_as_sequence && base->tp_as_sequence)) {
2834 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
2835 if (!type->tp_as_number && !type->tp_as_sequence) {
2836 type->tp_flags |= base->tp_flags &
2837 Py_TPFLAGS_HAVE_INPLACEOPS;
2838 }
2839 }
2840 /* Wow */
2841 }
2842 if (!type->tp_as_number && base->tp_as_number) {
2843 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
2844 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
2845 }
2846
2847 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00002848 oldsize = base->tp_basicsize;
2849 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
2850 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
2851 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00002852 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
2853 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00002854 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00002855 if (type->tp_traverse == NULL)
2856 type->tp_traverse = base->tp_traverse;
2857 if (type->tp_clear == NULL)
2858 type->tp_clear = base->tp_clear;
2859 }
2860 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
Guido van Rossumf884b742001-12-17 17:14:22 +00002861 /* The condition below could use some explanation.
2862 It appears that tp_new is not inherited for static types
2863 whose base class is 'object'; this seems to be a precaution
2864 so that old extension types don't suddenly become
2865 callable (object.__new__ wouldn't insure the invariants
2866 that the extension type's own factory function ensures).
2867 Heap types, of course, are under our control, so they do
2868 inherit tp_new; static extension types that specify some
2869 other built-in type as the default are considered
2870 new-style-aware so they also inherit object.__new__. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002871 if (base != &PyBaseObject_Type ||
2872 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2873 if (type->tp_new == NULL)
2874 type->tp_new = base->tp_new;
2875 }
2876 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00002877 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00002878
2879 /* Copy other non-function slots */
2880
2881#undef COPYVAL
2882#define COPYVAL(SLOT) \
2883 if (type->SLOT == 0) type->SLOT = base->SLOT
2884
2885 COPYVAL(tp_itemsize);
2886 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
2887 COPYVAL(tp_weaklistoffset);
2888 }
2889 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2890 COPYVAL(tp_dictoffset);
2891 }
Guido van Rossum13d52f02001-08-10 21:24:08 +00002892}
2893
2894static void
2895inherit_slots(PyTypeObject *type, PyTypeObject *base)
2896{
2897 PyTypeObject *basebase;
2898
2899#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00002900#undef COPYSLOT
2901#undef COPYNUM
2902#undef COPYSEQ
2903#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00002904#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00002905
2906#define SLOTDEFINED(SLOT) \
2907 (base->SLOT != 0 && \
2908 (basebase == NULL || base->SLOT != basebase->SLOT))
2909
Tim Peters6d6c1a32001-08-02 04:15:00 +00002910#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00002911 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00002912
2913#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
2914#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
2915#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00002916#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002917
Guido van Rossum13d52f02001-08-10 21:24:08 +00002918 /* This won't inherit indirect slots (from tp_as_number etc.)
2919 if type doesn't provide the space. */
2920
2921 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
2922 basebase = base->tp_base;
2923 if (basebase->tp_as_number == NULL)
2924 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002925 COPYNUM(nb_add);
2926 COPYNUM(nb_subtract);
2927 COPYNUM(nb_multiply);
2928 COPYNUM(nb_divide);
2929 COPYNUM(nb_remainder);
2930 COPYNUM(nb_divmod);
2931 COPYNUM(nb_power);
2932 COPYNUM(nb_negative);
2933 COPYNUM(nb_positive);
2934 COPYNUM(nb_absolute);
2935 COPYNUM(nb_nonzero);
2936 COPYNUM(nb_invert);
2937 COPYNUM(nb_lshift);
2938 COPYNUM(nb_rshift);
2939 COPYNUM(nb_and);
2940 COPYNUM(nb_xor);
2941 COPYNUM(nb_or);
2942 COPYNUM(nb_coerce);
2943 COPYNUM(nb_int);
2944 COPYNUM(nb_long);
2945 COPYNUM(nb_float);
2946 COPYNUM(nb_oct);
2947 COPYNUM(nb_hex);
2948 COPYNUM(nb_inplace_add);
2949 COPYNUM(nb_inplace_subtract);
2950 COPYNUM(nb_inplace_multiply);
2951 COPYNUM(nb_inplace_divide);
2952 COPYNUM(nb_inplace_remainder);
2953 COPYNUM(nb_inplace_power);
2954 COPYNUM(nb_inplace_lshift);
2955 COPYNUM(nb_inplace_rshift);
2956 COPYNUM(nb_inplace_and);
2957 COPYNUM(nb_inplace_xor);
2958 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00002959 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
2960 COPYNUM(nb_true_divide);
2961 COPYNUM(nb_floor_divide);
2962 COPYNUM(nb_inplace_true_divide);
2963 COPYNUM(nb_inplace_floor_divide);
2964 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002965 }
2966
Guido van Rossum13d52f02001-08-10 21:24:08 +00002967 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
2968 basebase = base->tp_base;
2969 if (basebase->tp_as_sequence == NULL)
2970 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002971 COPYSEQ(sq_length);
2972 COPYSEQ(sq_concat);
2973 COPYSEQ(sq_repeat);
2974 COPYSEQ(sq_item);
2975 COPYSEQ(sq_slice);
2976 COPYSEQ(sq_ass_item);
2977 COPYSEQ(sq_ass_slice);
2978 COPYSEQ(sq_contains);
2979 COPYSEQ(sq_inplace_concat);
2980 COPYSEQ(sq_inplace_repeat);
2981 }
2982
Guido van Rossum13d52f02001-08-10 21:24:08 +00002983 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
2984 basebase = base->tp_base;
2985 if (basebase->tp_as_mapping == NULL)
2986 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002987 COPYMAP(mp_length);
2988 COPYMAP(mp_subscript);
2989 COPYMAP(mp_ass_subscript);
2990 }
2991
Tim Petersfc57ccb2001-10-12 02:38:24 +00002992 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
2993 basebase = base->tp_base;
2994 if (basebase->tp_as_buffer == NULL)
2995 basebase = NULL;
2996 COPYBUF(bf_getreadbuffer);
2997 COPYBUF(bf_getwritebuffer);
2998 COPYBUF(bf_getsegcount);
2999 COPYBUF(bf_getcharbuffer);
3000 }
3001
Guido van Rossum13d52f02001-08-10 21:24:08 +00003002 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003003
Tim Peters6d6c1a32001-08-02 04:15:00 +00003004 COPYSLOT(tp_dealloc);
3005 COPYSLOT(tp_print);
3006 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
3007 type->tp_getattr = base->tp_getattr;
3008 type->tp_getattro = base->tp_getattro;
3009 }
3010 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
3011 type->tp_setattr = base->tp_setattr;
3012 type->tp_setattro = base->tp_setattro;
3013 }
3014 /* tp_compare see tp_richcompare */
3015 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003016 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003017 COPYSLOT(tp_call);
3018 COPYSLOT(tp_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003019 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003020 if (type->tp_compare == NULL &&
3021 type->tp_richcompare == NULL &&
3022 type->tp_hash == NULL)
3023 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003024 type->tp_compare = base->tp_compare;
3025 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003026 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003027 }
3028 }
3029 else {
3030 COPYSLOT(tp_compare);
3031 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003032 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
3033 COPYSLOT(tp_iter);
3034 COPYSLOT(tp_iternext);
3035 }
3036 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
3037 COPYSLOT(tp_descr_get);
3038 COPYSLOT(tp_descr_set);
3039 COPYSLOT(tp_dictoffset);
3040 COPYSLOT(tp_init);
3041 COPYSLOT(tp_alloc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003042 COPYSLOT(tp_free);
Guido van Rossumcc8fe042002-04-05 17:10:16 +00003043 COPYSLOT(tp_is_gc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003044 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003045}
3046
Jeremy Hylton938ace62002-07-17 16:30:39 +00003047static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00003048
Tim Peters6d6c1a32001-08-02 04:15:00 +00003049int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00003050PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003051{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003052 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003053 PyTypeObject *base;
3054 int i, n;
3055
Guido van Rossumcab05802002-06-10 15:29:03 +00003056 if (type->tp_flags & Py_TPFLAGS_READY) {
3057 assert(type->tp_dict != NULL);
Guido van Rossumd614f972001-08-10 17:39:49 +00003058 return 0;
Guido van Rossumcab05802002-06-10 15:29:03 +00003059 }
Guido van Rossumd614f972001-08-10 17:39:49 +00003060 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00003061
3062 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003063
Tim Peters36eb4df2003-03-23 03:33:13 +00003064#ifdef Py_TRACE_REFS
3065 /* PyType_Ready is the closest thing we have to a choke point
3066 * for type objects, so is the best place I can think of to try
3067 * to get type objects into the doubly-linked list of all objects.
3068 * Still, not all type objects go thru PyType_Ready.
3069 */
Tim Peters7571a0f2003-03-23 17:52:28 +00003070 _Py_AddToAllObjects((PyObject *)type, 0);
Tim Peters36eb4df2003-03-23 03:33:13 +00003071#endif
3072
Tim Peters6d6c1a32001-08-02 04:15:00 +00003073 /* Initialize tp_base (defaults to BaseObject unless that's us) */
3074 base = type->tp_base;
3075 if (base == NULL && type != &PyBaseObject_Type)
3076 base = type->tp_base = &PyBaseObject_Type;
3077
Guido van Rossum323a9cf2002-08-14 17:26:30 +00003078 /* Initialize the base class */
3079 if (base && base->tp_dict == NULL) {
3080 if (PyType_Ready(base) < 0)
3081 goto error;
3082 }
3083
Guido van Rossum0986d822002-04-08 01:38:42 +00003084 /* Initialize ob_type if NULL. This means extensions that want to be
3085 compilable separately on Windows can call PyType_Ready() instead of
3086 initializing the ob_type field of their type objects. */
3087 if (type->ob_type == NULL)
3088 type->ob_type = base->ob_type;
3089
Tim Peters6d6c1a32001-08-02 04:15:00 +00003090 /* Initialize tp_bases */
3091 bases = type->tp_bases;
3092 if (bases == NULL) {
3093 if (base == NULL)
3094 bases = PyTuple_New(0);
3095 else
3096 bases = Py_BuildValue("(O)", base);
3097 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003098 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003099 type->tp_bases = bases;
3100 }
3101
Guido van Rossum687ae002001-10-15 22:03:32 +00003102 /* Initialize tp_dict */
3103 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003104 if (dict == NULL) {
3105 dict = PyDict_New();
3106 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003107 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00003108 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003109 }
3110
Guido van Rossum687ae002001-10-15 22:03:32 +00003111 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003112 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003113 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003114 if (type->tp_methods != NULL) {
3115 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003116 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003117 }
3118 if (type->tp_members != NULL) {
3119 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003120 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003121 }
3122 if (type->tp_getset != NULL) {
3123 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003124 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003125 }
3126
Tim Peters6d6c1a32001-08-02 04:15:00 +00003127 /* Calculate method resolution order */
3128 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00003129 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003130 }
3131
Guido van Rossum13d52f02001-08-10 21:24:08 +00003132 /* Inherit special flags from dominant base */
3133 if (type->tp_base != NULL)
3134 inherit_special(type, type->tp_base);
3135
Tim Peters6d6c1a32001-08-02 04:15:00 +00003136 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003137 bases = type->tp_mro;
3138 assert(bases != NULL);
3139 assert(PyTuple_Check(bases));
3140 n = PyTuple_GET_SIZE(bases);
3141 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003142 PyObject *b = PyTuple_GET_ITEM(bases, i);
3143 if (PyType_Check(b))
3144 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003145 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003146
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003147 /* if the type dictionary doesn't contain a __doc__, set it from
3148 the tp_doc slot.
3149 */
3150 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
3151 if (type->tp_doc != NULL) {
3152 PyObject *doc = PyString_FromString(type->tp_doc);
3153 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
3154 Py_DECREF(doc);
3155 } else {
Guido van Rossumd4641072002-04-03 02:13:37 +00003156 PyDict_SetItemString(type->tp_dict,
3157 "__doc__", Py_None);
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003158 }
3159 }
3160
Guido van Rossum13d52f02001-08-10 21:24:08 +00003161 /* Some more special stuff */
3162 base = type->tp_base;
3163 if (base != NULL) {
3164 if (type->tp_as_number == NULL)
3165 type->tp_as_number = base->tp_as_number;
3166 if (type->tp_as_sequence == NULL)
3167 type->tp_as_sequence = base->tp_as_sequence;
3168 if (type->tp_as_mapping == NULL)
3169 type->tp_as_mapping = base->tp_as_mapping;
Guido van Rossumeea47182003-02-11 20:39:59 +00003170 if (type->tp_as_buffer == NULL)
3171 type->tp_as_buffer = base->tp_as_buffer;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003172 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003173
Guido van Rossum1c450732001-10-08 15:18:27 +00003174 /* Link into each base class's list of subclasses */
3175 bases = type->tp_bases;
3176 n = PyTuple_GET_SIZE(bases);
3177 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003178 PyObject *b = PyTuple_GET_ITEM(bases, i);
3179 if (PyType_Check(b) &&
3180 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00003181 goto error;
3182 }
3183
Guido van Rossum13d52f02001-08-10 21:24:08 +00003184 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00003185 assert(type->tp_dict != NULL);
3186 type->tp_flags =
3187 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003188 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00003189
3190 error:
3191 type->tp_flags &= ~Py_TPFLAGS_READYING;
3192 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003193}
3194
Guido van Rossum1c450732001-10-08 15:18:27 +00003195static int
3196add_subclass(PyTypeObject *base, PyTypeObject *type)
3197{
3198 int i;
3199 PyObject *list, *ref, *new;
3200
3201 list = base->tp_subclasses;
3202 if (list == NULL) {
3203 base->tp_subclasses = list = PyList_New(0);
3204 if (list == NULL)
3205 return -1;
3206 }
3207 assert(PyList_Check(list));
3208 new = PyWeakref_NewRef((PyObject *)type, NULL);
3209 i = PyList_GET_SIZE(list);
3210 while (--i >= 0) {
3211 ref = PyList_GET_ITEM(list, i);
3212 assert(PyWeakref_CheckRef(ref));
Guido van Rossum3930bc32002-10-18 13:51:49 +00003213 if (PyWeakref_GET_OBJECT(ref) == Py_None)
3214 return PyList_SetItem(list, i, new);
Guido van Rossum1c450732001-10-08 15:18:27 +00003215 }
3216 i = PyList_Append(list, new);
3217 Py_DECREF(new);
3218 return i;
3219}
3220
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003221static void
3222remove_subclass(PyTypeObject *base, PyTypeObject *type)
3223{
3224 int i;
3225 PyObject *list, *ref;
3226
3227 list = base->tp_subclasses;
3228 if (list == NULL) {
3229 return;
3230 }
3231 assert(PyList_Check(list));
3232 i = PyList_GET_SIZE(list);
3233 while (--i >= 0) {
3234 ref = PyList_GET_ITEM(list, i);
3235 assert(PyWeakref_CheckRef(ref));
3236 if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
3237 /* this can't fail, right? */
3238 PySequence_DelItem(list, i);
3239 return;
3240 }
3241 }
3242}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003243
3244/* Generic wrappers for overloadable 'operators' such as __getitem__ */
3245
3246/* There's a wrapper *function* for each distinct function typedef used
3247 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
3248 wrapper *table* for each distinct operation (e.g. __len__, __add__).
3249 Most tables have only one entry; the tables for binary operators have two
3250 entries, one regular and one with reversed arguments. */
3251
3252static PyObject *
3253wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
3254{
3255 inquiry func = (inquiry)wrapped;
3256 int res;
3257
3258 if (!PyArg_ParseTuple(args, ""))
3259 return NULL;
3260 res = (*func)(self);
3261 if (res == -1 && PyErr_Occurred())
3262 return NULL;
3263 return PyInt_FromLong((long)res);
3264}
3265
Tim Peters6d6c1a32001-08-02 04:15:00 +00003266static PyObject *
3267wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
3268{
3269 binaryfunc func = (binaryfunc)wrapped;
3270 PyObject *other;
3271
3272 if (!PyArg_ParseTuple(args, "O", &other))
3273 return NULL;
3274 return (*func)(self, other);
3275}
3276
3277static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003278wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
3279{
3280 binaryfunc func = (binaryfunc)wrapped;
3281 PyObject *other;
3282
3283 if (!PyArg_ParseTuple(args, "O", &other))
3284 return NULL;
3285 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003286 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003287 Py_INCREF(Py_NotImplemented);
3288 return Py_NotImplemented;
3289 }
3290 return (*func)(self, other);
3291}
3292
3293static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003294wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3295{
3296 binaryfunc func = (binaryfunc)wrapped;
3297 PyObject *other;
3298
3299 if (!PyArg_ParseTuple(args, "O", &other))
3300 return NULL;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003301 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003302 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003303 Py_INCREF(Py_NotImplemented);
3304 return Py_NotImplemented;
3305 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003306 return (*func)(other, self);
3307}
3308
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003309static PyObject *
3310wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
3311{
3312 coercion func = (coercion)wrapped;
3313 PyObject *other, *res;
3314 int ok;
3315
3316 if (!PyArg_ParseTuple(args, "O", &other))
3317 return NULL;
3318 ok = func(&self, &other);
3319 if (ok < 0)
3320 return NULL;
3321 if (ok > 0) {
3322 Py_INCREF(Py_NotImplemented);
3323 return Py_NotImplemented;
3324 }
3325 res = PyTuple_New(2);
3326 if (res == NULL) {
3327 Py_DECREF(self);
3328 Py_DECREF(other);
3329 return NULL;
3330 }
3331 PyTuple_SET_ITEM(res, 0, self);
3332 PyTuple_SET_ITEM(res, 1, other);
3333 return res;
3334}
3335
Tim Peters6d6c1a32001-08-02 04:15:00 +00003336static PyObject *
3337wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
3338{
3339 ternaryfunc func = (ternaryfunc)wrapped;
3340 PyObject *other;
3341 PyObject *third = Py_None;
3342
3343 /* Note: This wrapper only works for __pow__() */
3344
3345 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
3346 return NULL;
3347 return (*func)(self, other, third);
3348}
3349
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00003350static PyObject *
3351wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3352{
3353 ternaryfunc func = (ternaryfunc)wrapped;
3354 PyObject *other;
3355 PyObject *third = Py_None;
3356
3357 /* Note: This wrapper only works for __pow__() */
3358
3359 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
3360 return NULL;
3361 return (*func)(other, self, third);
3362}
3363
Tim Peters6d6c1a32001-08-02 04:15:00 +00003364static PyObject *
3365wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
3366{
3367 unaryfunc func = (unaryfunc)wrapped;
3368
3369 if (!PyArg_ParseTuple(args, ""))
3370 return NULL;
3371 return (*func)(self);
3372}
3373
Tim Peters6d6c1a32001-08-02 04:15:00 +00003374static PyObject *
3375wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
3376{
3377 intargfunc func = (intargfunc)wrapped;
3378 int i;
3379
3380 if (!PyArg_ParseTuple(args, "i", &i))
3381 return NULL;
3382 return (*func)(self, i);
3383}
3384
Guido van Rossum5d815f32001-08-17 21:57:47 +00003385static int
3386getindex(PyObject *self, PyObject *arg)
3387{
3388 int i;
3389
3390 i = PyInt_AsLong(arg);
3391 if (i == -1 && PyErr_Occurred())
3392 return -1;
3393 if (i < 0) {
3394 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
3395 if (sq && sq->sq_length) {
3396 int n = (*sq->sq_length)(self);
3397 if (n < 0)
3398 return -1;
3399 i += n;
3400 }
3401 }
3402 return i;
3403}
3404
3405static PyObject *
3406wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
3407{
3408 intargfunc func = (intargfunc)wrapped;
3409 PyObject *arg;
3410 int i;
3411
Guido van Rossumf4593e02001-10-03 12:09:30 +00003412 if (PyTuple_GET_SIZE(args) == 1) {
3413 arg = PyTuple_GET_ITEM(args, 0);
3414 i = getindex(self, arg);
3415 if (i == -1 && PyErr_Occurred())
3416 return NULL;
3417 return (*func)(self, i);
3418 }
3419 PyArg_ParseTuple(args, "O", &arg);
3420 assert(PyErr_Occurred());
3421 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003422}
3423
Tim Peters6d6c1a32001-08-02 04:15:00 +00003424static PyObject *
3425wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
3426{
3427 intintargfunc func = (intintargfunc)wrapped;
3428 int i, j;
3429
3430 if (!PyArg_ParseTuple(args, "ii", &i, &j))
3431 return NULL;
3432 return (*func)(self, i, j);
3433}
3434
Tim Peters6d6c1a32001-08-02 04:15:00 +00003435static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003436wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003437{
3438 intobjargproc func = (intobjargproc)wrapped;
3439 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003440 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003441
Guido van Rossum5d815f32001-08-17 21:57:47 +00003442 if (!PyArg_ParseTuple(args, "OO", &arg, &value))
3443 return NULL;
3444 i = getindex(self, arg);
3445 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00003446 return NULL;
3447 res = (*func)(self, i, value);
3448 if (res == -1 && PyErr_Occurred())
3449 return NULL;
3450 Py_INCREF(Py_None);
3451 return Py_None;
3452}
3453
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003454static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003455wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003456{
3457 intobjargproc func = (intobjargproc)wrapped;
3458 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003459 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003460
Guido van Rossum5d815f32001-08-17 21:57:47 +00003461 if (!PyArg_ParseTuple(args, "O", &arg))
3462 return NULL;
3463 i = getindex(self, arg);
3464 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003465 return NULL;
3466 res = (*func)(self, i, NULL);
3467 if (res == -1 && PyErr_Occurred())
3468 return NULL;
3469 Py_INCREF(Py_None);
3470 return Py_None;
3471}
3472
Tim Peters6d6c1a32001-08-02 04:15:00 +00003473static PyObject *
3474wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
3475{
3476 intintobjargproc func = (intintobjargproc)wrapped;
3477 int i, j, res;
3478 PyObject *value;
3479
3480 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
3481 return NULL;
3482 res = (*func)(self, i, j, value);
3483 if (res == -1 && PyErr_Occurred())
3484 return NULL;
3485 Py_INCREF(Py_None);
3486 return Py_None;
3487}
3488
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003489static PyObject *
3490wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
3491{
3492 intintobjargproc func = (intintobjargproc)wrapped;
3493 int i, j, res;
3494
3495 if (!PyArg_ParseTuple(args, "ii", &i, &j))
3496 return NULL;
3497 res = (*func)(self, i, j, NULL);
3498 if (res == -1 && PyErr_Occurred())
3499 return NULL;
3500 Py_INCREF(Py_None);
3501 return Py_None;
3502}
3503
Tim Peters6d6c1a32001-08-02 04:15:00 +00003504/* XXX objobjproc is a misnomer; should be objargpred */
3505static PyObject *
3506wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
3507{
3508 objobjproc func = (objobjproc)wrapped;
3509 int res;
3510 PyObject *value;
3511
3512 if (!PyArg_ParseTuple(args, "O", &value))
3513 return NULL;
3514 res = (*func)(self, value);
3515 if (res == -1 && PyErr_Occurred())
3516 return NULL;
3517 return PyInt_FromLong((long)res);
3518}
3519
Tim Peters6d6c1a32001-08-02 04:15:00 +00003520static PyObject *
3521wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
3522{
3523 objobjargproc func = (objobjargproc)wrapped;
3524 int res;
3525 PyObject *key, *value;
3526
3527 if (!PyArg_ParseTuple(args, "OO", &key, &value))
3528 return NULL;
3529 res = (*func)(self, key, value);
3530 if (res == -1 && PyErr_Occurred())
3531 return NULL;
3532 Py_INCREF(Py_None);
3533 return Py_None;
3534}
3535
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003536static PyObject *
3537wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
3538{
3539 objobjargproc func = (objobjargproc)wrapped;
3540 int res;
3541 PyObject *key;
3542
3543 if (!PyArg_ParseTuple(args, "O", &key))
3544 return NULL;
3545 res = (*func)(self, key, NULL);
3546 if (res == -1 && PyErr_Occurred())
3547 return NULL;
3548 Py_INCREF(Py_None);
3549 return Py_None;
3550}
3551
Tim Peters6d6c1a32001-08-02 04:15:00 +00003552static PyObject *
3553wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
3554{
3555 cmpfunc func = (cmpfunc)wrapped;
3556 int res;
3557 PyObject *other;
3558
3559 if (!PyArg_ParseTuple(args, "O", &other))
3560 return NULL;
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00003561 if (other->ob_type->tp_compare != func &&
3562 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00003563 PyErr_Format(
3564 PyExc_TypeError,
3565 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
3566 self->ob_type->tp_name,
3567 self->ob_type->tp_name,
3568 other->ob_type->tp_name);
3569 return NULL;
3570 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003571 res = (*func)(self, other);
3572 if (PyErr_Occurred())
3573 return NULL;
3574 return PyInt_FromLong((long)res);
3575}
3576
Tim Peters6d6c1a32001-08-02 04:15:00 +00003577static PyObject *
3578wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
3579{
3580 setattrofunc func = (setattrofunc)wrapped;
3581 int res;
3582 PyObject *name, *value;
3583
3584 if (!PyArg_ParseTuple(args, "OO", &name, &value))
3585 return NULL;
3586 res = (*func)(self, name, value);
3587 if (res < 0)
3588 return NULL;
3589 Py_INCREF(Py_None);
3590 return Py_None;
3591}
3592
3593static PyObject *
3594wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
3595{
3596 setattrofunc func = (setattrofunc)wrapped;
3597 int res;
3598 PyObject *name;
3599
3600 if (!PyArg_ParseTuple(args, "O", &name))
3601 return NULL;
3602 res = (*func)(self, name, NULL);
3603 if (res < 0)
3604 return NULL;
3605 Py_INCREF(Py_None);
3606 return Py_None;
3607}
3608
Tim Peters6d6c1a32001-08-02 04:15:00 +00003609static PyObject *
3610wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
3611{
3612 hashfunc func = (hashfunc)wrapped;
3613 long res;
3614
3615 if (!PyArg_ParseTuple(args, ""))
3616 return NULL;
3617 res = (*func)(self);
3618 if (res == -1 && PyErr_Occurred())
3619 return NULL;
3620 return PyInt_FromLong(res);
3621}
3622
Tim Peters6d6c1a32001-08-02 04:15:00 +00003623static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00003624wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003625{
3626 ternaryfunc func = (ternaryfunc)wrapped;
3627
Guido van Rossumc8e56452001-10-22 00:43:43 +00003628 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003629}
3630
Tim Peters6d6c1a32001-08-02 04:15:00 +00003631static PyObject *
3632wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
3633{
3634 richcmpfunc func = (richcmpfunc)wrapped;
3635 PyObject *other;
3636
3637 if (!PyArg_ParseTuple(args, "O", &other))
3638 return NULL;
3639 return (*func)(self, other, op);
3640}
3641
3642#undef RICHCMP_WRAPPER
3643#define RICHCMP_WRAPPER(NAME, OP) \
3644static PyObject * \
3645richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
3646{ \
3647 return wrap_richcmpfunc(self, args, wrapped, OP); \
3648}
3649
Jack Jansen8e938b42001-08-08 15:29:49 +00003650RICHCMP_WRAPPER(lt, Py_LT)
3651RICHCMP_WRAPPER(le, Py_LE)
3652RICHCMP_WRAPPER(eq, Py_EQ)
3653RICHCMP_WRAPPER(ne, Py_NE)
3654RICHCMP_WRAPPER(gt, Py_GT)
3655RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003656
Tim Peters6d6c1a32001-08-02 04:15:00 +00003657static PyObject *
3658wrap_next(PyObject *self, PyObject *args, void *wrapped)
3659{
3660 unaryfunc func = (unaryfunc)wrapped;
3661 PyObject *res;
3662
3663 if (!PyArg_ParseTuple(args, ""))
3664 return NULL;
3665 res = (*func)(self);
3666 if (res == NULL && !PyErr_Occurred())
3667 PyErr_SetNone(PyExc_StopIteration);
3668 return res;
3669}
3670
Tim Peters6d6c1a32001-08-02 04:15:00 +00003671static PyObject *
3672wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
3673{
3674 descrgetfunc func = (descrgetfunc)wrapped;
3675 PyObject *obj;
3676 PyObject *type = NULL;
3677
3678 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
3679 return NULL;
Guido van Rossum82ed25c2003-02-11 16:25:43 +00003680 if (obj == Py_None)
3681 obj = NULL;
3682 if (type == Py_None)
3683 type = NULL;
3684 if (type == NULL &&obj == NULL) {
3685 PyErr_SetString(PyExc_TypeError,
3686 "__get__(None, None) is invalid");
3687 return NULL;
3688 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003689 return (*func)(self, obj, type);
3690}
3691
Tim Peters6d6c1a32001-08-02 04:15:00 +00003692static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003693wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003694{
3695 descrsetfunc func = (descrsetfunc)wrapped;
3696 PyObject *obj, *value;
3697 int ret;
3698
3699 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
3700 return NULL;
3701 ret = (*func)(self, obj, value);
3702 if (ret < 0)
3703 return NULL;
3704 Py_INCREF(Py_None);
3705 return Py_None;
3706}
Guido van Rossum22b13872002-08-06 21:41:44 +00003707
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00003708static PyObject *
3709wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
3710{
3711 descrsetfunc func = (descrsetfunc)wrapped;
3712 PyObject *obj;
3713 int ret;
3714
3715 if (!PyArg_ParseTuple(args, "O", &obj))
3716 return NULL;
3717 ret = (*func)(self, obj, NULL);
3718 if (ret < 0)
3719 return NULL;
3720 Py_INCREF(Py_None);
3721 return Py_None;
3722}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003723
Tim Peters6d6c1a32001-08-02 04:15:00 +00003724static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00003725wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003726{
3727 initproc func = (initproc)wrapped;
3728
Guido van Rossumc8e56452001-10-22 00:43:43 +00003729 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003730 return NULL;
3731 Py_INCREF(Py_None);
3732 return Py_None;
3733}
3734
Tim Peters6d6c1a32001-08-02 04:15:00 +00003735static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003736tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003737{
Barry Warsaw60f01882001-08-22 19:24:42 +00003738 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003739 PyObject *arg0, *res;
3740
3741 if (self == NULL || !PyType_Check(self))
3742 Py_FatalError("__new__() called with non-type 'self'");
3743 type = (PyTypeObject *)self;
3744 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003745 PyErr_Format(PyExc_TypeError,
3746 "%s.__new__(): not enough arguments",
3747 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003748 return NULL;
3749 }
3750 arg0 = PyTuple_GET_ITEM(args, 0);
3751 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003752 PyErr_Format(PyExc_TypeError,
3753 "%s.__new__(X): X is not a type object (%s)",
3754 type->tp_name,
3755 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003756 return NULL;
3757 }
3758 subtype = (PyTypeObject *)arg0;
3759 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003760 PyErr_Format(PyExc_TypeError,
3761 "%s.__new__(%s): %s is not a subtype of %s",
3762 type->tp_name,
3763 subtype->tp_name,
3764 subtype->tp_name,
3765 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003766 return NULL;
3767 }
Barry Warsaw60f01882001-08-22 19:24:42 +00003768
3769 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00003770 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00003771 most derived base that's not a heap type is this type. */
3772 staticbase = subtype;
3773 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
3774 staticbase = staticbase->tp_base;
Guido van Rossuma8c60f42001-09-14 19:43:36 +00003775 if (staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003776 PyErr_Format(PyExc_TypeError,
3777 "%s.__new__(%s) is not safe, use %s.__new__()",
3778 type->tp_name,
3779 subtype->tp_name,
3780 staticbase == NULL ? "?" : staticbase->tp_name);
3781 return NULL;
3782 }
3783
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003784 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
3785 if (args == NULL)
3786 return NULL;
3787 res = type->tp_new(subtype, args, kwds);
3788 Py_DECREF(args);
3789 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003790}
3791
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003792static struct PyMethodDef tp_new_methoddef[] = {
3793 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00003794 PyDoc_STR("T.__new__(S, ...) -> "
3795 "a new object with type S, a subtype of T")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00003796 {0}
3797};
3798
3799static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003800add_tp_new_wrapper(PyTypeObject *type)
3801{
Guido van Rossumf040ede2001-08-07 16:40:56 +00003802 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003803
Guido van Rossum687ae002001-10-15 22:03:32 +00003804 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00003805 return 0;
3806 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003807 if (func == NULL)
3808 return -1;
Guido van Rossum687ae002001-10-15 22:03:32 +00003809 return PyDict_SetItemString(type->tp_dict, "__new__", func);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003810}
3811
Guido van Rossumf040ede2001-08-07 16:40:56 +00003812/* Slot wrappers that call the corresponding __foo__ slot. See comments
3813 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003814
Guido van Rossumdc91b992001-08-08 22:26:22 +00003815#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003816static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003817FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003818{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00003819 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003820 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003821}
3822
Guido van Rossumdc91b992001-08-08 22:26:22 +00003823#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003824static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003825FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003826{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003827 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003828 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003829}
3830
Guido van Rossumcd118802003-01-06 22:57:47 +00003831/* Boolean helper for SLOT1BINFULL().
3832 right.__class__ is a nontrivial subclass of left.__class__. */
3833static int
3834method_is_overloaded(PyObject *left, PyObject *right, char *name)
3835{
3836 PyObject *a, *b;
3837 int ok;
3838
3839 b = PyObject_GetAttrString((PyObject *)(right->ob_type), name);
3840 if (b == NULL) {
3841 PyErr_Clear();
3842 /* If right doesn't have it, it's not overloaded */
3843 return 0;
3844 }
3845
3846 a = PyObject_GetAttrString((PyObject *)(left->ob_type), name);
3847 if (a == NULL) {
3848 PyErr_Clear();
3849 Py_DECREF(b);
3850 /* If right has it but left doesn't, it's overloaded */
3851 return 1;
3852 }
3853
3854 ok = PyObject_RichCompareBool(a, b, Py_NE);
3855 Py_DECREF(a);
3856 Py_DECREF(b);
3857 if (ok < 0) {
3858 PyErr_Clear();
3859 return 0;
3860 }
3861
3862 return ok;
3863}
3864
Guido van Rossumdc91b992001-08-08 22:26:22 +00003865
3866#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003867static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003868FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003869{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003870 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00003871 int do_other = self->ob_type != other->ob_type && \
3872 other->ob_type->tp_as_number != NULL && \
3873 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003874 if (self->ob_type->tp_as_number != NULL && \
3875 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
3876 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00003877 if (do_other && \
Guido van Rossumcd118802003-01-06 22:57:47 +00003878 PyType_IsSubtype(other->ob_type, self->ob_type) && \
3879 method_is_overloaded(self, other, ROPSTR)) { \
Guido van Rossum55f20992001-10-01 17:18:22 +00003880 r = call_maybe( \
3881 other, ROPSTR, &rcache_str, "(O)", self); \
3882 if (r != Py_NotImplemented) \
3883 return r; \
3884 Py_DECREF(r); \
3885 do_other = 0; \
3886 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00003887 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00003888 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003889 if (r != Py_NotImplemented || \
3890 other->ob_type == self->ob_type) \
3891 return r; \
3892 Py_DECREF(r); \
3893 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00003894 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00003895 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00003896 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003897 } \
3898 Py_INCREF(Py_NotImplemented); \
3899 return Py_NotImplemented; \
3900}
3901
3902#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
3903 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
3904
3905#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
3906static PyObject * \
3907FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
3908{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003909 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003910 return call_method(self, OPSTR, &cache_str, \
3911 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003912}
3913
3914static int
3915slot_sq_length(PyObject *self)
3916{
Guido van Rossum2730b132001-08-28 18:22:14 +00003917 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00003918 PyObject *res = call_method(self, "__len__", &len_str, "()");
Guido van Rossum26111622001-10-01 16:42:49 +00003919 int len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003920
3921 if (res == NULL)
3922 return -1;
Guido van Rossum26111622001-10-01 16:42:49 +00003923 len = (int)PyInt_AsLong(res);
3924 Py_DECREF(res);
Jeremy Hylton73a088e2002-07-25 16:43:29 +00003925 if (len == -1 && PyErr_Occurred())
3926 return -1;
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00003927 if (len < 0) {
Guido van Rossum22b13872002-08-06 21:41:44 +00003928 PyErr_SetString(PyExc_ValueError,
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00003929 "__len__() should return >= 0");
3930 return -1;
3931 }
Guido van Rossum26111622001-10-01 16:42:49 +00003932 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003933}
3934
Guido van Rossumdc91b992001-08-08 22:26:22 +00003935SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
3936SLOT1(slot_sq_repeat, "__mul__", int, "i")
Guido van Rossumf4593e02001-10-03 12:09:30 +00003937
3938/* Super-optimized version of slot_sq_item.
3939 Other slots could do the same... */
3940static PyObject *
3941slot_sq_item(PyObject *self, int i)
3942{
3943 static PyObject *getitem_str;
3944 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
3945 descrgetfunc f;
3946
3947 if (getitem_str == NULL) {
3948 getitem_str = PyString_InternFromString("__getitem__");
3949 if (getitem_str == NULL)
3950 return NULL;
3951 }
3952 func = _PyType_Lookup(self->ob_type, getitem_str);
3953 if (func != NULL) {
Guido van Rossumf4593e02001-10-03 12:09:30 +00003954 if ((f = func->ob_type->tp_descr_get) == NULL)
3955 Py_INCREF(func);
Neal Norwitz673cd822002-10-18 16:33:13 +00003956 else {
Guido van Rossumf4593e02001-10-03 12:09:30 +00003957 func = f(func, self, (PyObject *)(self->ob_type));
Neal Norwitz673cd822002-10-18 16:33:13 +00003958 if (func == NULL) {
3959 return NULL;
3960 }
3961 }
Guido van Rossumf4593e02001-10-03 12:09:30 +00003962 ival = PyInt_FromLong(i);
3963 if (ival != NULL) {
3964 args = PyTuple_New(1);
3965 if (args != NULL) {
3966 PyTuple_SET_ITEM(args, 0, ival);
3967 retval = PyObject_Call(func, args, NULL);
3968 Py_XDECREF(args);
3969 Py_XDECREF(func);
3970 return retval;
3971 }
3972 }
3973 }
3974 else {
3975 PyErr_SetObject(PyExc_AttributeError, getitem_str);
3976 }
3977 Py_XDECREF(args);
3978 Py_XDECREF(ival);
3979 Py_XDECREF(func);
3980 return NULL;
3981}
3982
Guido van Rossumdc91b992001-08-08 22:26:22 +00003983SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003984
3985static int
3986slot_sq_ass_item(PyObject *self, int index, PyObject *value)
3987{
3988 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003989 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003990
3991 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003992 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003993 "(i)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003994 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003995 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003996 "(iO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003997 if (res == NULL)
3998 return -1;
3999 Py_DECREF(res);
4000 return 0;
4001}
4002
4003static int
4004slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
4005{
4006 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004007 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004008
4009 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004010 res = call_method(self, "__delslice__", &delslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004011 "(ii)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004012 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004013 res = call_method(self, "__setslice__", &setslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004014 "(iiO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004015 if (res == NULL)
4016 return -1;
4017 Py_DECREF(res);
4018 return 0;
4019}
4020
4021static int
4022slot_sq_contains(PyObject *self, PyObject *value)
4023{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004024 PyObject *func, *res, *args;
Tim Petersbf9b2442003-03-23 05:35:36 +00004025 int result = -1;
4026
Guido van Rossum60718732001-08-28 17:47:51 +00004027 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004028
Guido van Rossum55f20992001-10-01 17:18:22 +00004029 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004030 if (func != NULL) {
4031 args = Py_BuildValue("(O)", value);
4032 if (args == NULL)
4033 res = NULL;
4034 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004035 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004036 Py_DECREF(args);
4037 }
4038 Py_DECREF(func);
Tim Petersbf9b2442003-03-23 05:35:36 +00004039 if (res != NULL) {
4040 result = PyObject_IsTrue(res);
4041 Py_DECREF(res);
4042 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004043 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004044 else if (! PyErr_Occurred()) {
4045 result = _PySequence_IterSearch(self, value,
4046 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004047 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004048 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004049}
4050
Guido van Rossumdc91b992001-08-08 22:26:22 +00004051SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
4052SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004053
4054#define slot_mp_length slot_sq_length
4055
Guido van Rossumdc91b992001-08-08 22:26:22 +00004056SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004057
4058static int
4059slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
4060{
4061 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004062 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004063
4064 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004065 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004066 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004067 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004068 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004069 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004070 if (res == NULL)
4071 return -1;
4072 Py_DECREF(res);
4073 return 0;
4074}
4075
Guido van Rossumdc91b992001-08-08 22:26:22 +00004076SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
4077SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
4078SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
4079SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
4080SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
4081SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
4082
Jeremy Hylton938ace62002-07-17 16:30:39 +00004083static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00004084
4085SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
4086 nb_power, "__pow__", "__rpow__")
4087
4088static PyObject *
4089slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
4090{
Guido van Rossum2730b132001-08-28 18:22:14 +00004091 static PyObject *pow_str;
4092
Guido van Rossumdc91b992001-08-08 22:26:22 +00004093 if (modulus == Py_None)
4094 return slot_nb_power_binary(self, other);
Guido van Rossum23094982002-06-10 14:30:43 +00004095 /* Three-arg power doesn't use __rpow__. But ternary_op
4096 can call this when the second argument's type uses
4097 slot_nb_power, so check before calling self.__pow__. */
4098 if (self->ob_type->tp_as_number != NULL &&
4099 self->ob_type->tp_as_number->nb_power == slot_nb_power) {
4100 return call_method(self, "__pow__", &pow_str,
4101 "(OO)", other, modulus);
4102 }
4103 Py_INCREF(Py_NotImplemented);
4104 return Py_NotImplemented;
Guido van Rossumdc91b992001-08-08 22:26:22 +00004105}
4106
4107SLOT0(slot_nb_negative, "__neg__")
4108SLOT0(slot_nb_positive, "__pos__")
4109SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004110
4111static int
4112slot_nb_nonzero(PyObject *self)
4113{
Tim Petersea7f75d2002-12-07 21:39:16 +00004114 PyObject *func, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00004115 static PyObject *nonzero_str, *len_str;
Tim Petersea7f75d2002-12-07 21:39:16 +00004116 int result = -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004117
Guido van Rossum55f20992001-10-01 17:18:22 +00004118 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004119 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00004120 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00004121 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00004122 func = lookup_maybe(self, "__len__", &len_str);
Tim Petersea7f75d2002-12-07 21:39:16 +00004123 if (func == NULL)
4124 return PyErr_Occurred() ? -1 : 1;
4125 }
4126 args = PyTuple_New(0);
4127 if (args != NULL) {
4128 PyObject *temp = PyObject_Call(func, args, NULL);
4129 Py_DECREF(args);
4130 if (temp != NULL) {
4131 result = PyObject_IsTrue(temp);
4132 Py_DECREF(temp);
Guido van Rossum55f20992001-10-01 17:18:22 +00004133 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004134 }
Guido van Rossum55f20992001-10-01 17:18:22 +00004135 Py_DECREF(func);
Tim Petersea7f75d2002-12-07 21:39:16 +00004136 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004137}
4138
Guido van Rossumdc91b992001-08-08 22:26:22 +00004139SLOT0(slot_nb_invert, "__invert__")
4140SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
4141SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
4142SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
4143SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
4144SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004145
4146static int
4147slot_nb_coerce(PyObject **a, PyObject **b)
4148{
4149 static PyObject *coerce_str;
4150 PyObject *self = *a, *other = *b;
4151
4152 if (self->ob_type->tp_as_number != NULL &&
4153 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
4154 PyObject *r;
4155 r = call_maybe(
4156 self, "__coerce__", &coerce_str, "(O)", other);
4157 if (r == NULL)
4158 return -1;
4159 if (r == Py_NotImplemented) {
4160 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004161 }
Guido van Rossum55f20992001-10-01 17:18:22 +00004162 else {
4163 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
4164 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004165 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00004166 Py_DECREF(r);
4167 return -1;
4168 }
4169 *a = PyTuple_GET_ITEM(r, 0);
4170 Py_INCREF(*a);
4171 *b = PyTuple_GET_ITEM(r, 1);
4172 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004173 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00004174 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004175 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004176 }
4177 if (other->ob_type->tp_as_number != NULL &&
4178 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
4179 PyObject *r;
4180 r = call_maybe(
4181 other, "__coerce__", &coerce_str, "(O)", self);
4182 if (r == NULL)
4183 return -1;
4184 if (r == Py_NotImplemented) {
4185 Py_DECREF(r);
4186 return 1;
4187 }
4188 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
4189 PyErr_SetString(PyExc_TypeError,
4190 "__coerce__ didn't return a 2-tuple");
4191 Py_DECREF(r);
4192 return -1;
4193 }
4194 *a = PyTuple_GET_ITEM(r, 1);
4195 Py_INCREF(*a);
4196 *b = PyTuple_GET_ITEM(r, 0);
4197 Py_INCREF(*b);
4198 Py_DECREF(r);
4199 return 0;
4200 }
4201 return 1;
4202}
4203
Guido van Rossumdc91b992001-08-08 22:26:22 +00004204SLOT0(slot_nb_int, "__int__")
4205SLOT0(slot_nb_long, "__long__")
4206SLOT0(slot_nb_float, "__float__")
4207SLOT0(slot_nb_oct, "__oct__")
4208SLOT0(slot_nb_hex, "__hex__")
4209SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
4210SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
4211SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
4212SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
4213SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Guido van Rossum6e5680f2002-10-15 01:01:53 +00004214SLOT1(slot_nb_inplace_power, "__ipow__", PyObject *, "O")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004215SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
4216SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
4217SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
4218SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
4219SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
4220SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
4221 "__floordiv__", "__rfloordiv__")
4222SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
4223SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
4224SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004225
4226static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00004227half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004228{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004229 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004230 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004231 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004232
Guido van Rossum60718732001-08-28 17:47:51 +00004233 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004234 if (func == NULL) {
4235 PyErr_Clear();
4236 }
4237 else {
4238 args = Py_BuildValue("(O)", other);
4239 if (args == NULL)
4240 res = NULL;
4241 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004242 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004243 Py_DECREF(args);
4244 }
Raymond Hettingerab5dae32002-06-24 13:08:16 +00004245 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004246 if (res != Py_NotImplemented) {
4247 if (res == NULL)
4248 return -2;
4249 c = PyInt_AsLong(res);
4250 Py_DECREF(res);
4251 if (c == -1 && PyErr_Occurred())
4252 return -2;
4253 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
4254 }
4255 Py_DECREF(res);
4256 }
4257 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004258}
4259
Guido van Rossumab3b0342001-09-18 20:38:53 +00004260/* This slot is published for the benefit of try_3way_compare in object.c */
4261int
4262_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00004263{
4264 int c;
4265
Guido van Rossumab3b0342001-09-18 20:38:53 +00004266 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004267 c = half_compare(self, other);
4268 if (c <= 1)
4269 return c;
4270 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00004271 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004272 c = half_compare(other, self);
4273 if (c < -1)
4274 return -2;
4275 if (c <= 1)
4276 return -c;
4277 }
4278 return (void *)self < (void *)other ? -1 :
4279 (void *)self > (void *)other ? 1 : 0;
4280}
4281
4282static PyObject *
4283slot_tp_repr(PyObject *self)
4284{
4285 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004286 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004287
Guido van Rossum60718732001-08-28 17:47:51 +00004288 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004289 if (func != NULL) {
4290 res = PyEval_CallObject(func, NULL);
4291 Py_DECREF(func);
4292 return res;
4293 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00004294 PyErr_Clear();
4295 return PyString_FromFormat("<%s object at %p>",
4296 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004297}
4298
4299static PyObject *
4300slot_tp_str(PyObject *self)
4301{
4302 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004303 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004304
Guido van Rossum60718732001-08-28 17:47:51 +00004305 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004306 if (func != NULL) {
4307 res = PyEval_CallObject(func, NULL);
4308 Py_DECREF(func);
4309 return res;
4310 }
4311 else {
4312 PyErr_Clear();
4313 return slot_tp_repr(self);
4314 }
4315}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004316
4317static long
4318slot_tp_hash(PyObject *self)
4319{
Tim Peters61ce0a92002-12-06 23:38:02 +00004320 PyObject *func;
Guido van Rossum60718732001-08-28 17:47:51 +00004321 static PyObject *hash_str, *eq_str, *cmp_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004322 long h;
4323
Guido van Rossum60718732001-08-28 17:47:51 +00004324 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004325
4326 if (func != NULL) {
Tim Peters61ce0a92002-12-06 23:38:02 +00004327 PyObject *res = PyEval_CallObject(func, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004328 Py_DECREF(func);
4329 if (res == NULL)
4330 return -1;
4331 h = PyInt_AsLong(res);
Tim Peters61ce0a92002-12-06 23:38:02 +00004332 Py_DECREF(res);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004333 }
4334 else {
4335 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004336 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004337 if (func == NULL) {
4338 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004339 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004340 }
4341 if (func != NULL) {
4342 Py_DECREF(func);
4343 PyErr_SetString(PyExc_TypeError, "unhashable type");
4344 return -1;
4345 }
4346 PyErr_Clear();
4347 h = _Py_HashPointer((void *)self);
4348 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004349 if (h == -1 && !PyErr_Occurred())
4350 h = -2;
4351 return h;
4352}
4353
4354static PyObject *
4355slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
4356{
Guido van Rossum60718732001-08-28 17:47:51 +00004357 static PyObject *call_str;
4358 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004359 PyObject *res;
4360
4361 if (meth == NULL)
4362 return NULL;
4363 res = PyObject_Call(meth, args, kwds);
4364 Py_DECREF(meth);
4365 return res;
4366}
4367
Guido van Rossum14a6f832001-10-17 13:59:09 +00004368/* There are two slot dispatch functions for tp_getattro.
4369
4370 - slot_tp_getattro() is used when __getattribute__ is overridden
4371 but no __getattr__ hook is present;
4372
4373 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
4374
Guido van Rossumc334df52002-04-04 23:44:47 +00004375 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
4376 detects the absence of __getattr__ and then installs the simpler slot if
4377 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00004378
Tim Peters6d6c1a32001-08-02 04:15:00 +00004379static PyObject *
4380slot_tp_getattro(PyObject *self, PyObject *name)
4381{
Guido van Rossum14a6f832001-10-17 13:59:09 +00004382 static PyObject *getattribute_str = NULL;
4383 return call_method(self, "__getattribute__", &getattribute_str,
4384 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004385}
4386
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004387static PyObject *
4388slot_tp_getattr_hook(PyObject *self, PyObject *name)
4389{
4390 PyTypeObject *tp = self->ob_type;
4391 PyObject *getattr, *getattribute, *res;
4392 static PyObject *getattribute_str = NULL;
4393 static PyObject *getattr_str = NULL;
4394
4395 if (getattr_str == NULL) {
4396 getattr_str = PyString_InternFromString("__getattr__");
4397 if (getattr_str == NULL)
4398 return NULL;
4399 }
4400 if (getattribute_str == NULL) {
4401 getattribute_str =
4402 PyString_InternFromString("__getattribute__");
4403 if (getattribute_str == NULL)
4404 return NULL;
4405 }
4406 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004407 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004408 /* No __getattr__ hook: use a simpler dispatcher */
4409 tp->tp_getattro = slot_tp_getattro;
4410 return slot_tp_getattro(self, name);
4411 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004412 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004413 if (getattribute == NULL ||
4414 (getattribute->ob_type == &PyWrapperDescr_Type &&
4415 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
4416 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004417 res = PyObject_GenericGetAttr(self, name);
4418 else
4419 res = PyObject_CallFunction(getattribute, "OO", self, name);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004420 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004421 PyErr_Clear();
4422 res = PyObject_CallFunction(getattr, "OO", self, name);
4423 }
4424 return res;
4425}
4426
Tim Peters6d6c1a32001-08-02 04:15:00 +00004427static int
4428slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
4429{
4430 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004431 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004432
4433 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004434 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004435 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004436 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004437 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004438 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004439 if (res == NULL)
4440 return -1;
4441 Py_DECREF(res);
4442 return 0;
4443}
4444
4445/* Map rich comparison operators to their __xx__ namesakes */
4446static char *name_op[] = {
4447 "__lt__",
4448 "__le__",
4449 "__eq__",
4450 "__ne__",
4451 "__gt__",
4452 "__ge__",
4453};
4454
4455static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00004456half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004457{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004458 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004459 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00004460
Guido van Rossum60718732001-08-28 17:47:51 +00004461 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004462 if (func == NULL) {
4463 PyErr_Clear();
4464 Py_INCREF(Py_NotImplemented);
4465 return Py_NotImplemented;
4466 }
4467 args = Py_BuildValue("(O)", other);
4468 if (args == NULL)
4469 res = NULL;
4470 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004471 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004472 Py_DECREF(args);
4473 }
4474 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004475 return res;
4476}
4477
Guido van Rossumb8f63662001-08-15 23:57:02 +00004478/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
4479static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
4480
4481static PyObject *
4482slot_tp_richcompare(PyObject *self, PyObject *other, int op)
4483{
4484 PyObject *res;
4485
4486 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
4487 res = half_richcompare(self, other, op);
4488 if (res != Py_NotImplemented)
4489 return res;
4490 Py_DECREF(res);
4491 }
4492 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
4493 res = half_richcompare(other, self, swapped_op[op]);
4494 if (res != Py_NotImplemented) {
4495 return res;
4496 }
4497 Py_DECREF(res);
4498 }
4499 Py_INCREF(Py_NotImplemented);
4500 return Py_NotImplemented;
4501}
4502
4503static PyObject *
4504slot_tp_iter(PyObject *self)
4505{
4506 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004507 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004508
Guido van Rossum60718732001-08-28 17:47:51 +00004509 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004510 if (func != NULL) {
Guido van Rossum84b2bed2002-08-16 17:01:09 +00004511 PyObject *args;
4512 args = res = PyTuple_New(0);
4513 if (args != NULL) {
4514 res = PyObject_Call(func, args, NULL);
4515 Py_DECREF(args);
4516 }
4517 Py_DECREF(func);
4518 return res;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004519 }
4520 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004521 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004522 if (func == NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00004523 PyErr_SetString(PyExc_TypeError,
4524 "iteration over non-sequence");
Guido van Rossumb8f63662001-08-15 23:57:02 +00004525 return NULL;
4526 }
4527 Py_DECREF(func);
4528 return PySeqIter_New(self);
4529}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004530
4531static PyObject *
4532slot_tp_iternext(PyObject *self)
4533{
Guido van Rossum2730b132001-08-28 18:22:14 +00004534 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00004535 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004536}
4537
Guido van Rossum1a493502001-08-17 16:47:50 +00004538static PyObject *
4539slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4540{
4541 PyTypeObject *tp = self->ob_type;
4542 PyObject *get;
4543 static PyObject *get_str = NULL;
4544
4545 if (get_str == NULL) {
4546 get_str = PyString_InternFromString("__get__");
4547 if (get_str == NULL)
4548 return NULL;
4549 }
4550 get = _PyType_Lookup(tp, get_str);
4551 if (get == NULL) {
4552 /* Avoid further slowdowns */
4553 if (tp->tp_descr_get == slot_tp_descr_get)
4554 tp->tp_descr_get = NULL;
4555 Py_INCREF(self);
4556 return self;
4557 }
Guido van Rossum2c252392001-08-24 10:13:31 +00004558 if (obj == NULL)
4559 obj = Py_None;
4560 if (type == NULL)
4561 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00004562 return PyObject_CallFunction(get, "OOO", self, obj, type);
4563}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004564
4565static int
4566slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
4567{
Guido van Rossum2c252392001-08-24 10:13:31 +00004568 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004569 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00004570
4571 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00004572 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004573 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00004574 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004575 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004576 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004577 if (res == NULL)
4578 return -1;
4579 Py_DECREF(res);
4580 return 0;
4581}
4582
4583static int
4584slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
4585{
Guido van Rossum60718732001-08-28 17:47:51 +00004586 static PyObject *init_str;
4587 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004588 PyObject *res;
4589
4590 if (meth == NULL)
4591 return -1;
4592 res = PyObject_Call(meth, args, kwds);
4593 Py_DECREF(meth);
4594 if (res == NULL)
4595 return -1;
4596 Py_DECREF(res);
4597 return 0;
4598}
4599
4600static PyObject *
4601slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4602{
Guido van Rossum7bed2132002-08-08 21:57:53 +00004603 static PyObject *new_str;
4604 PyObject *func;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004605 PyObject *newargs, *x;
4606 int i, n;
4607
Guido van Rossum7bed2132002-08-08 21:57:53 +00004608 if (new_str == NULL) {
4609 new_str = PyString_InternFromString("__new__");
4610 if (new_str == NULL)
4611 return NULL;
4612 }
4613 func = PyObject_GetAttr((PyObject *)type, new_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004614 if (func == NULL)
4615 return NULL;
4616 assert(PyTuple_Check(args));
4617 n = PyTuple_GET_SIZE(args);
4618 newargs = PyTuple_New(n+1);
4619 if (newargs == NULL)
4620 return NULL;
4621 Py_INCREF(type);
4622 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
4623 for (i = 0; i < n; i++) {
4624 x = PyTuple_GET_ITEM(args, i);
4625 Py_INCREF(x);
4626 PyTuple_SET_ITEM(newargs, i+1, x);
4627 }
4628 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00004629 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004630 Py_DECREF(func);
4631 return x;
4632}
4633
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004634static void
4635slot_tp_del(PyObject *self)
4636{
4637 static PyObject *del_str = NULL;
4638 PyObject *del, *res;
4639 PyObject *error_type, *error_value, *error_traceback;
4640
4641 /* Temporarily resurrect the object. */
4642 assert(self->ob_refcnt == 0);
4643 self->ob_refcnt = 1;
4644
4645 /* Save the current exception, if any. */
4646 PyErr_Fetch(&error_type, &error_value, &error_traceback);
4647
4648 /* Execute __del__ method, if any. */
4649 del = lookup_maybe(self, "__del__", &del_str);
4650 if (del != NULL) {
4651 res = PyEval_CallObject(del, NULL);
4652 if (res == NULL)
4653 PyErr_WriteUnraisable(del);
4654 else
4655 Py_DECREF(res);
4656 Py_DECREF(del);
4657 }
4658
4659 /* Restore the saved exception. */
4660 PyErr_Restore(error_type, error_value, error_traceback);
4661
4662 /* Undo the temporary resurrection; can't use DECREF here, it would
4663 * cause a recursive call.
4664 */
4665 assert(self->ob_refcnt > 0);
4666 if (--self->ob_refcnt == 0)
4667 return; /* this is the normal path out */
4668
4669 /* __del__ resurrected it! Make it look like the original Py_DECREF
4670 * never happened.
4671 */
4672 {
4673 int refcnt = self->ob_refcnt;
4674 _Py_NewReference(self);
4675 self->ob_refcnt = refcnt;
4676 }
4677 assert(!PyType_IS_GC(self->ob_type) ||
4678 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
4679 /* If Py_REF_DEBUG, the original decref dropped _Py_RefTotal, but
4680 * _Py_NewReference bumped it again, so that's a wash.
4681 * If Py_TRACE_REFS, _Py_NewReference re-added self to the object
4682 * chain, so no more to do there either.
4683 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
4684 * _Py_NewReference bumped tp_allocs: both of those need to be
4685 * undone.
4686 */
4687#ifdef COUNT_ALLOCS
4688 --self->ob_type->tp_frees;
4689 --self->ob_type->tp_allocs;
4690#endif
4691}
4692
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004693
4694/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
Tim Petersbf9b2442003-03-23 05:35:36 +00004695 functions. The offsets here are relative to the 'PyHeapTypeObject'
Guido van Rossume5c691a2003-03-07 15:13:17 +00004696 structure, which incorporates the additional structures used for numbers,
4697 sequences and mappings.
4698 Note that multiple names may map to the same slot (e.g. __eq__,
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004699 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00004700 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
4701 terminated with an all-zero entry. (This table is further initialized and
4702 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004703
Guido van Rossum6d204072001-10-21 00:44:31 +00004704typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004705
4706#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00004707#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004708#undef ETSLOT
4709#undef SQSLOT
4710#undef MPSLOT
4711#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00004712#undef UNSLOT
4713#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004714#undef BINSLOT
4715#undef RBINSLOT
4716
Guido van Rossum6d204072001-10-21 00:44:31 +00004717#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004718 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
4719 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00004720#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
4721 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004722 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00004723#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Guido van Rossume5c691a2003-03-07 15:13:17 +00004724 {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004725 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00004726#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4727 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
4728#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4729 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
4730#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4731 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
4732#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4733 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
4734 "x." NAME "() <==> " DOC)
4735#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4736 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
4737 "x." NAME "(y) <==> x" DOC "y")
4738#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
4739 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
4740 "x." NAME "(y) <==> x" DOC "y")
4741#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
4742 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
4743 "x." NAME "(y) <==> y" DOC "x")
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004744
4745static slotdef slotdefs[] = {
Guido van Rossum6d204072001-10-21 00:44:31 +00004746 SQSLOT("__len__", sq_length, slot_sq_length, wrap_inquiry,
4747 "x.__len__() <==> len(x)"),
4748 SQSLOT("__add__", sq_concat, slot_sq_concat, wrap_binaryfunc,
4749 "x.__add__(y) <==> x+y"),
4750 SQSLOT("__mul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
4751 "x.__mul__(n) <==> x*n"),
4752 SQSLOT("__rmul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
4753 "x.__rmul__(n) <==> n*x"),
4754 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
4755 "x.__getitem__(y) <==> x[y]"),
4756 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_intintargfunc,
4757 "x.__getslice__(i, j) <==> x[i:j]"),
4758 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
4759 "x.__setitem__(i, y) <==> x[i]=y"),
4760 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
4761 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004762 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Guido van Rossum6d204072001-10-21 00:44:31 +00004763 wrap_intintobjargproc,
4764 "x.__setslice__(i, j, y) <==> x[i:j]=y"),
4765 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
4766 "x.__delslice__(i, j) <==> del x[i:j]"),
4767 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
4768 "x.__contains__(y) <==> y in x"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004769 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat,
Guido van Rossum6d204072001-10-21 00:44:31 +00004770 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004771 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat,
Guido van Rossum6d204072001-10-21 00:44:31 +00004772 wrap_intargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004773
Guido van Rossum6d204072001-10-21 00:44:31 +00004774 MPSLOT("__len__", mp_length, slot_mp_length, wrap_inquiry,
4775 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00004776 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004777 wrap_binaryfunc,
4778 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004779 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004780 wrap_objobjargproc,
4781 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004782 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004783 wrap_delitem,
4784 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004785
Guido van Rossum6d204072001-10-21 00:44:31 +00004786 BINSLOT("__add__", nb_add, slot_nb_add,
4787 "+"),
4788 RBINSLOT("__radd__", nb_add, slot_nb_add,
4789 "+"),
4790 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
4791 "-"),
4792 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
4793 "-"),
4794 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
4795 "*"),
4796 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
4797 "*"),
4798 BINSLOT("__div__", nb_divide, slot_nb_divide,
4799 "/"),
4800 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
4801 "/"),
4802 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
4803 "%"),
4804 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
4805 "%"),
4806 BINSLOT("__divmod__", nb_divmod, slot_nb_divmod,
4807 "divmod(x, y)"),
4808 RBINSLOT("__rdivmod__", nb_divmod, slot_nb_divmod,
4809 "divmod(y, x)"),
4810 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
4811 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
4812 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
4813 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
4814 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
4815 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
4816 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
4817 "abs(x)"),
Guido van Rossumdfce3bf2002-03-10 14:11:16 +00004818 UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquiry,
Guido van Rossum6d204072001-10-21 00:44:31 +00004819 "x != 0"),
4820 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
4821 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
4822 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
4823 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
4824 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
4825 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
4826 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
4827 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
4828 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
4829 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
4830 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
4831 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
4832 "x.__coerce__(y) <==> coerce(x, y)"),
4833 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
4834 "int(x)"),
4835 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
4836 "long(x)"),
4837 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
4838 "float(x)"),
4839 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
4840 "oct(x)"),
4841 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
4842 "hex(x)"),
4843 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
4844 wrap_binaryfunc, "+"),
4845 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
4846 wrap_binaryfunc, "-"),
4847 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
4848 wrap_binaryfunc, "*"),
4849 IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
4850 wrap_binaryfunc, "/"),
4851 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
4852 wrap_binaryfunc, "%"),
4853 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
Guido van Rossum6e5680f2002-10-15 01:01:53 +00004854 wrap_binaryfunc, "**"),
Guido van Rossum6d204072001-10-21 00:44:31 +00004855 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
4856 wrap_binaryfunc, "<<"),
4857 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
4858 wrap_binaryfunc, ">>"),
4859 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
4860 wrap_binaryfunc, "&"),
4861 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
4862 wrap_binaryfunc, "^"),
4863 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
4864 wrap_binaryfunc, "|"),
4865 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
4866 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
4867 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
4868 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
4869 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
4870 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
4871 IBSLOT("__itruediv__", nb_inplace_true_divide,
4872 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004873
Guido van Rossum6d204072001-10-21 00:44:31 +00004874 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
4875 "x.__str__() <==> str(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00004876 TPSLOT("__str__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00004877 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
4878 "x.__repr__() <==> repr(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00004879 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00004880 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
4881 "x.__cmp__(y) <==> cmp(x,y)"),
4882 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
4883 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00004884 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
4885 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004886 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00004887 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
4888 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
4889 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
4890 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
4891 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
4892 "x.__setattr__('name', value) <==> x.name = value"),
4893 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
4894 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
4895 "x.__delattr__('name') <==> del x.name"),
4896 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
4897 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
4898 "x.__lt__(y) <==> x<y"),
4899 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
4900 "x.__le__(y) <==> x<=y"),
4901 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
4902 "x.__eq__(y) <==> x==y"),
4903 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
4904 "x.__ne__(y) <==> x!=y"),
4905 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
4906 "x.__gt__(y) <==> x>y"),
4907 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
4908 "x.__ge__(y) <==> x>=y"),
4909 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
4910 "x.__iter__() <==> iter(x)"),
4911 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
4912 "x.next() -> the next value, or raise StopIteration"),
4913 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
4914 "descr.__get__(obj[, type]) -> value"),
4915 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
4916 "descr.__set__(obj, value)"),
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004917 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
4918 wrap_descr_delete, "descr.__delete__(obj)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00004919 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00004920 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00004921 "see x.__class__.__doc__ for signature",
4922 PyWrapperFlag_KEYWORDS),
4923 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004924 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004925 {NULL}
4926};
4927
Guido van Rossumc334df52002-04-04 23:44:47 +00004928/* Given a type pointer and an offset gotten from a slotdef entry, return a
4929 pointer to the actual slot. This is not quite the same as simply adding
4930 the offset to the type pointer, since it takes care to indirect through the
4931 proper indirection pointer (as_buffer, etc.); it returns NULL if the
4932 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004933static void **
4934slotptr(PyTypeObject *type, int offset)
4935{
4936 char *ptr;
4937
Guido van Rossume5c691a2003-03-07 15:13:17 +00004938 /* Note: this depends on the order of the members of PyHeapTypeObject! */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004939 assert(offset >= 0);
Guido van Rossume5c691a2003-03-07 15:13:17 +00004940 assert(offset < offsetof(PyHeapTypeObject, as_buffer));
4941 if (offset >= offsetof(PyHeapTypeObject, as_sequence)) {
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004942 ptr = (void *)type->tp_as_sequence;
Guido van Rossume5c691a2003-03-07 15:13:17 +00004943 offset -= offsetof(PyHeapTypeObject, as_sequence);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004944 }
Guido van Rossume5c691a2003-03-07 15:13:17 +00004945 else if (offset >= offsetof(PyHeapTypeObject, as_mapping)) {
Guido van Rossum09638c12002-06-13 19:17:46 +00004946 ptr = (void *)type->tp_as_mapping;
Guido van Rossume5c691a2003-03-07 15:13:17 +00004947 offset -= offsetof(PyHeapTypeObject, as_mapping);
Guido van Rossum09638c12002-06-13 19:17:46 +00004948 }
Guido van Rossume5c691a2003-03-07 15:13:17 +00004949 else if (offset >= offsetof(PyHeapTypeObject, as_number)) {
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004950 ptr = (void *)type->tp_as_number;
Guido van Rossume5c691a2003-03-07 15:13:17 +00004951 offset -= offsetof(PyHeapTypeObject, as_number);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004952 }
4953 else {
4954 ptr = (void *)type;
4955 }
4956 if (ptr != NULL)
4957 ptr += offset;
4958 return (void **)ptr;
4959}
Guido van Rossumf040ede2001-08-07 16:40:56 +00004960
Guido van Rossumc334df52002-04-04 23:44:47 +00004961/* Length of array of slotdef pointers used to store slots with the
4962 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
4963 the same __name__, for any __name__. Since that's a static property, it is
4964 appropriate to declare fixed-size arrays for this. */
4965#define MAX_EQUIV 10
4966
4967/* Return a slot pointer for a given name, but ONLY if the attribute has
4968 exactly one slot function. The name must be an interned string. */
4969static void **
4970resolve_slotdups(PyTypeObject *type, PyObject *name)
4971{
4972 /* XXX Maybe this could be optimized more -- but is it worth it? */
4973
4974 /* pname and ptrs act as a little cache */
4975 static PyObject *pname;
4976 static slotdef *ptrs[MAX_EQUIV];
4977 slotdef *p, **pp;
4978 void **res, **ptr;
4979
4980 if (pname != name) {
4981 /* Collect all slotdefs that match name into ptrs. */
4982 pname = name;
4983 pp = ptrs;
4984 for (p = slotdefs; p->name_strobj; p++) {
4985 if (p->name_strobj == name)
4986 *pp++ = p;
4987 }
4988 *pp = NULL;
4989 }
4990
4991 /* Look in all matching slots of the type; if exactly one of these has
4992 a filled-in slot, return its value. Otherwise return NULL. */
4993 res = NULL;
4994 for (pp = ptrs; *pp; pp++) {
4995 ptr = slotptr(type, (*pp)->offset);
4996 if (ptr == NULL || *ptr == NULL)
4997 continue;
4998 if (res != NULL)
4999 return NULL;
5000 res = ptr;
5001 }
5002 return res;
5003}
5004
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005005/* Common code for update_slots_callback() and fixup_slot_dispatchers(). This
Guido van Rossumc334df52002-04-04 23:44:47 +00005006 does some incredibly complex thinking and then sticks something into the
5007 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
5008 interests, and then stores a generic wrapper or a specific function into
5009 the slot.) Return a pointer to the next slotdef with a different offset,
5010 because that's convenient for fixup_slot_dispatchers(). */
5011static slotdef *
5012update_one_slot(PyTypeObject *type, slotdef *p)
5013{
5014 PyObject *descr;
5015 PyWrapperDescrObject *d;
5016 void *generic = NULL, *specific = NULL;
5017 int use_generic = 0;
5018 int offset = p->offset;
5019 void **ptr = slotptr(type, offset);
5020
5021 if (ptr == NULL) {
5022 do {
5023 ++p;
5024 } while (p->offset == offset);
5025 return p;
5026 }
5027 do {
5028 descr = _PyType_Lookup(type, p->name_strobj);
5029 if (descr == NULL)
5030 continue;
5031 if (descr->ob_type == &PyWrapperDescr_Type) {
5032 void **tptr = resolve_slotdups(type, p->name_strobj);
5033 if (tptr == NULL || tptr == ptr)
5034 generic = p->function;
5035 d = (PyWrapperDescrObject *)descr;
5036 if (d->d_base->wrapper == p->wrapper &&
5037 PyType_IsSubtype(type, d->d_type))
5038 {
5039 if (specific == NULL ||
5040 specific == d->d_wrapped)
5041 specific = d->d_wrapped;
5042 else
5043 use_generic = 1;
5044 }
5045 }
Guido van Rossum721f62e2002-08-09 02:14:34 +00005046 else if (descr->ob_type == &PyCFunction_Type &&
5047 PyCFunction_GET_FUNCTION(descr) ==
5048 (PyCFunction)tp_new_wrapper &&
5049 strcmp(p->name, "__new__") == 0)
5050 {
5051 /* The __new__ wrapper is not a wrapper descriptor,
5052 so must be special-cased differently.
5053 If we don't do this, creating an instance will
5054 always use slot_tp_new which will look up
5055 __new__ in the MRO which will call tp_new_wrapper
5056 which will look through the base classes looking
5057 for a static base and call its tp_new (usually
5058 PyType_GenericNew), after performing various
5059 sanity checks and constructing a new argument
5060 list. Cut all that nonsense short -- this speeds
5061 up instance creation tremendously. */
5062 specific = type->tp_new;
5063 /* XXX I'm not 100% sure that there isn't a hole
5064 in this reasoning that requires additional
5065 sanity checks. I'll buy the first person to
5066 point out a bug in this reasoning a beer. */
5067 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005068 else {
5069 use_generic = 1;
5070 generic = p->function;
5071 }
5072 } while ((++p)->offset == offset);
5073 if (specific && !use_generic)
5074 *ptr = specific;
5075 else
5076 *ptr = generic;
5077 return p;
5078}
5079
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005080/* In the type, update the slots whose slotdefs are gathered in the pp array.
5081 This is a callback for update_subclasses(). */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005082static int
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005083update_slots_callback(PyTypeObject *type, void *data)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005084{
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005085 slotdef **pp = (slotdef **)data;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005086
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005087 for (; *pp; pp++)
Guido van Rossumc334df52002-04-04 23:44:47 +00005088 update_one_slot(type, *pp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005089 return 0;
5090}
5091
Guido van Rossumc334df52002-04-04 23:44:47 +00005092/* Comparison function for qsort() to compare slotdefs by their offset, and
5093 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005094static int
5095slotdef_cmp(const void *aa, const void *bb)
5096{
5097 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
5098 int c = a->offset - b->offset;
5099 if (c != 0)
5100 return c;
5101 else
5102 return a - b;
5103}
5104
Guido van Rossumc334df52002-04-04 23:44:47 +00005105/* Initialize the slotdefs table by adding interned string objects for the
5106 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005107static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005108init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005109{
5110 slotdef *p;
5111 static int initialized = 0;
5112
5113 if (initialized)
5114 return;
5115 for (p = slotdefs; p->name; p++) {
5116 p->name_strobj = PyString_InternFromString(p->name);
5117 if (!p->name_strobj)
Guido van Rossumc334df52002-04-04 23:44:47 +00005118 Py_FatalError("Out of memory interning slotdef names");
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005119 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005120 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
5121 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005122 initialized = 1;
5123}
5124
Guido van Rossumc334df52002-04-04 23:44:47 +00005125/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005126static int
5127update_slot(PyTypeObject *type, PyObject *name)
5128{
Guido van Rossumc334df52002-04-04 23:44:47 +00005129 slotdef *ptrs[MAX_EQUIV];
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005130 slotdef *p;
5131 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005132 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005133
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005134 init_slotdefs();
5135 pp = ptrs;
5136 for (p = slotdefs; p->name; p++) {
5137 /* XXX assume name is interned! */
5138 if (p->name_strobj == name)
5139 *pp++ = p;
5140 }
5141 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005142 for (pp = ptrs; *pp; pp++) {
5143 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005144 offset = p->offset;
5145 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005146 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005147 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005148 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005149 if (ptrs[0] == NULL)
5150 return 0; /* Not an attribute that affects any slots */
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005151 return update_subclasses(type, name,
5152 update_slots_callback, (void *)ptrs);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005153}
5154
Guido van Rossumc334df52002-04-04 23:44:47 +00005155/* Store the proper functions in the slot dispatches at class (type)
5156 definition time, based upon which operations the class overrides in its
5157 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00005158static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005159fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005160{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005161 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005162
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005163 init_slotdefs();
Guido van Rossumc334df52002-04-04 23:44:47 +00005164 for (p = slotdefs; p->name; )
5165 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005166}
Guido van Rossum705f0f52001-08-24 16:47:00 +00005167
Michael W. Hudson98bbc492002-11-26 14:47:27 +00005168static void
5169update_all_slots(PyTypeObject* type)
5170{
5171 slotdef *p;
5172
5173 init_slotdefs();
5174 for (p = slotdefs; p->name; p++) {
5175 /* update_slot returns int but can't actually fail */
5176 update_slot(type, p->name_strobj);
5177 }
5178}
5179
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005180/* recurse_down_subclasses() and update_subclasses() are mutually
5181 recursive functions to call a callback for all subclasses,
5182 but refraining from recursing into subclasses that define 'name'. */
5183
5184static int
5185update_subclasses(PyTypeObject *type, PyObject *name,
5186 update_callback callback, void *data)
5187{
5188 if (callback(type, data) < 0)
5189 return -1;
5190 return recurse_down_subclasses(type, name, callback, data);
5191}
5192
5193static int
5194recurse_down_subclasses(PyTypeObject *type, PyObject *name,
5195 update_callback callback, void *data)
5196{
5197 PyTypeObject *subclass;
5198 PyObject *ref, *subclasses, *dict;
5199 int i, n;
5200
5201 subclasses = type->tp_subclasses;
5202 if (subclasses == NULL)
5203 return 0;
5204 assert(PyList_Check(subclasses));
5205 n = PyList_GET_SIZE(subclasses);
5206 for (i = 0; i < n; i++) {
5207 ref = PyList_GET_ITEM(subclasses, i);
5208 assert(PyWeakref_CheckRef(ref));
5209 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
5210 assert(subclass != NULL);
5211 if ((PyObject *)subclass == Py_None)
5212 continue;
5213 assert(PyType_Check(subclass));
5214 /* Avoid recursing down into unaffected classes */
5215 dict = subclass->tp_dict;
5216 if (dict != NULL && PyDict_Check(dict) &&
5217 PyDict_GetItem(dict, name) != NULL)
5218 continue;
5219 if (update_subclasses(subclass, name, callback, data) < 0)
5220 return -1;
5221 }
5222 return 0;
5223}
5224
Guido van Rossum6d204072001-10-21 00:44:31 +00005225/* This function is called by PyType_Ready() to populate the type's
5226 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00005227 function slot (like tp_repr) that's defined in the type, one or more
5228 corresponding descriptors are added in the type's tp_dict dictionary
5229 under the appropriate name (like __repr__). Some function slots
5230 cause more than one descriptor to be added (for example, the nb_add
5231 slot adds both __add__ and __radd__ descriptors) and some function
5232 slots compete for the same descriptor (for example both sq_item and
5233 mp_subscript generate a __getitem__ descriptor).
5234
5235 In the latter case, the first slotdef entry encoutered wins. Since
Tim Petersbf9b2442003-03-23 05:35:36 +00005236 slotdef entries are sorted by the offset of the slot in the
Guido van Rossume5c691a2003-03-07 15:13:17 +00005237 PyHeapTypeObject, this gives us some control over disambiguating
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005238 between competing slots: the members of PyHeapTypeObject are listed
5239 from most general to least general, so the most general slot is
5240 preferred. In particular, because as_mapping comes before as_sequence,
5241 for a type that defines both mp_subscript and sq_item, mp_subscript
5242 wins.
Guido van Rossum09638c12002-06-13 19:17:46 +00005243
5244 This only adds new descriptors and doesn't overwrite entries in
5245 tp_dict that were previously defined. The descriptors contain a
5246 reference to the C function they must call, so that it's safe if they
5247 are copied into a subtype's __dict__ and the subtype has a different
5248 C function in its slot -- calling the method defined by the
5249 descriptor will call the C function that was used to create it,
5250 rather than the C function present in the slot when it is called.
5251 (This is important because a subtype may have a C function in the
5252 slot that calls the method from the dictionary, and we want to avoid
5253 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00005254
5255static int
5256add_operators(PyTypeObject *type)
5257{
5258 PyObject *dict = type->tp_dict;
5259 slotdef *p;
5260 PyObject *descr;
5261 void **ptr;
5262
5263 init_slotdefs();
5264 for (p = slotdefs; p->name; p++) {
5265 if (p->wrapper == NULL)
5266 continue;
5267 ptr = slotptr(type, p->offset);
5268 if (!ptr || !*ptr)
5269 continue;
5270 if (PyDict_GetItem(dict, p->name_strobj))
5271 continue;
5272 descr = PyDescr_NewWrapper(type, p, *ptr);
5273 if (descr == NULL)
5274 return -1;
5275 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
5276 return -1;
5277 Py_DECREF(descr);
5278 }
5279 if (type->tp_new != NULL) {
5280 if (add_tp_new_wrapper(type) < 0)
5281 return -1;
5282 }
5283 return 0;
5284}
5285
Guido van Rossum705f0f52001-08-24 16:47:00 +00005286
5287/* Cooperative 'super' */
5288
5289typedef struct {
5290 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00005291 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005292 PyObject *obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005293 PyTypeObject *obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005294} superobject;
5295
Guido van Rossum6f799372001-09-20 20:46:19 +00005296static PyMemberDef super_members[] = {
5297 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
5298 "the class invoking super()"},
5299 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
5300 "the instance invoking super(); may be None"},
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005301 {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
5302 "the type of the the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005303 {0}
5304};
5305
Guido van Rossum705f0f52001-08-24 16:47:00 +00005306static void
5307super_dealloc(PyObject *self)
5308{
5309 superobject *su = (superobject *)self;
5310
Guido van Rossum048eb752001-10-02 21:24:57 +00005311 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005312 Py_XDECREF(su->obj);
5313 Py_XDECREF(su->type);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005314 Py_XDECREF(su->obj_type);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005315 self->ob_type->tp_free(self);
5316}
5317
5318static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005319super_repr(PyObject *self)
5320{
5321 superobject *su = (superobject *)self;
5322
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005323 if (su->obj_type)
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005324 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005325 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005326 su->type ? su->type->tp_name : "NULL",
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005327 su->obj_type->tp_name);
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005328 else
5329 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005330 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005331 su->type ? su->type->tp_name : "NULL");
5332}
5333
5334static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00005335super_getattro(PyObject *self, PyObject *name)
5336{
5337 superobject *su = (superobject *)self;
5338
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005339 if (su->obj_type != NULL) {
Tim Petersa91e9642001-11-14 23:32:33 +00005340 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005341 PyTypeObject *starttype;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005342 descrgetfunc f;
5343 int i, n;
5344
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005345 starttype = su->obj_type;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005346 mro = starttype->tp_mro;
5347
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005348 if (mro == NULL)
5349 n = 0;
5350 else {
5351 assert(PyTuple_Check(mro));
5352 n = PyTuple_GET_SIZE(mro);
5353 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005354 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00005355 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00005356 break;
5357 }
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005358#if 0
Guido van Rossume705ef12001-08-29 15:47:06 +00005359 if (i >= n && PyType_Check(su->obj)) {
Guido van Rossum155db9a2002-04-02 17:53:47 +00005360 starttype = (PyTypeObject *)(su->obj);
5361 mro = starttype->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005362 if (mro == NULL)
5363 n = 0;
5364 else {
5365 assert(PyTuple_Check(mro));
5366 n = PyTuple_GET_SIZE(mro);
5367 }
Guido van Rossume705ef12001-08-29 15:47:06 +00005368 for (i = 0; i < n; i++) {
5369 if ((PyObject *)(su->type) ==
5370 PyTuple_GET_ITEM(mro, i))
5371 break;
5372 }
Guido van Rossume705ef12001-08-29 15:47:06 +00005373 }
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005374#endif
Guido van Rossum705f0f52001-08-24 16:47:00 +00005375 i++;
5376 res = NULL;
5377 for (; i < n; i++) {
5378 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00005379 if (PyType_Check(tmp))
5380 dict = ((PyTypeObject *)tmp)->tp_dict;
5381 else if (PyClass_Check(tmp))
5382 dict = ((PyClassObject *)tmp)->cl_dict;
5383 else
5384 continue;
5385 res = PyDict_GetItem(dict, name);
Guido van Rossum5b443c62001-12-03 15:38:28 +00005386 if (res != NULL && !PyDescr_IsData(res)) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00005387 Py_INCREF(res);
5388 f = res->ob_type->tp_descr_get;
5389 if (f != NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00005390 tmp = f(res, su->obj,
5391 (PyObject *)starttype);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005392 Py_DECREF(res);
5393 res = tmp;
5394 }
5395 return res;
5396 }
5397 }
5398 }
5399 return PyObject_GenericGetAttr(self, name);
5400}
5401
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005402static PyTypeObject *
Guido van Rossum5b443c62001-12-03 15:38:28 +00005403supercheck(PyTypeObject *type, PyObject *obj)
5404{
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005405 /* Check that a super() call makes sense. Return a type object.
5406
5407 obj can be a new-style class, or an instance of one:
5408
5409 - If it is a class, it must be a subclass of 'type'. This case is
5410 used for class methods; the return value is obj.
5411
5412 - If it is an instance, it must be an instance of 'type'. This is
5413 the normal case; the return value is obj.__class__.
5414
5415 But... when obj is an instance, we want to allow for the case where
5416 obj->ob_type is not a subclass of type, but obj.__class__ is!
5417 This will allow using super() with a proxy for obj.
5418 */
5419
Guido van Rossum8e80a722003-02-18 19:22:22 +00005420 /* Check for first bullet above (special case) */
5421 if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
5422 Py_INCREF(obj);
5423 return (PyTypeObject *)obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005424 }
Guido van Rossum8e80a722003-02-18 19:22:22 +00005425
5426 /* Normal case */
5427 if (PyType_IsSubtype(obj->ob_type, type)) {
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005428 Py_INCREF(obj->ob_type);
5429 return obj->ob_type;
5430 }
5431 else {
5432 /* Try the slow way */
5433 static PyObject *class_str = NULL;
5434 PyObject *class_attr;
5435
5436 if (class_str == NULL) {
5437 class_str = PyString_FromString("__class__");
5438 if (class_str == NULL)
5439 return NULL;
5440 }
5441
5442 class_attr = PyObject_GetAttr(obj, class_str);
5443
5444 if (class_attr != NULL &&
5445 PyType_Check(class_attr) &&
5446 (PyTypeObject *)class_attr != obj->ob_type)
5447 {
5448 int ok = PyType_IsSubtype(
5449 (PyTypeObject *)class_attr, type);
5450 if (ok)
5451 return (PyTypeObject *)class_attr;
5452 }
5453
5454 if (class_attr == NULL)
5455 PyErr_Clear();
5456 else
5457 Py_DECREF(class_attr);
5458 }
5459
Tim Peters97e5ff52003-02-18 19:32:50 +00005460 PyErr_SetString(PyExc_TypeError,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005461 "super(type, obj): "
5462 "obj must be an instance or subtype of type");
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005463 return NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005464}
5465
Guido van Rossum705f0f52001-08-24 16:47:00 +00005466static PyObject *
5467super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5468{
5469 superobject *su = (superobject *)self;
5470 superobject *new;
5471
5472 if (obj == NULL || obj == Py_None || su->obj != NULL) {
5473 /* Not binding to an object, or already bound */
5474 Py_INCREF(self);
5475 return self;
5476 }
Guido van Rossum5b443c62001-12-03 15:38:28 +00005477 if (su->ob_type != &PySuper_Type)
5478 /* If su is an instance of a subclass of super,
5479 call its type */
5480 return PyObject_CallFunction((PyObject *)su->ob_type,
5481 "OO", su->type, obj);
5482 else {
5483 /* Inline the common case */
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005484 PyTypeObject *obj_type = supercheck(su->type, obj);
5485 if (obj_type == NULL)
Guido van Rossum5b443c62001-12-03 15:38:28 +00005486 return NULL;
5487 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
5488 NULL, NULL);
5489 if (new == NULL)
5490 return NULL;
5491 Py_INCREF(su->type);
5492 Py_INCREF(obj);
5493 new->type = su->type;
5494 new->obj = obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005495 new->obj_type = obj_type;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005496 return (PyObject *)new;
5497 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005498}
5499
5500static int
5501super_init(PyObject *self, PyObject *args, PyObject *kwds)
5502{
5503 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00005504 PyTypeObject *type;
5505 PyObject *obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005506 PyTypeObject *obj_type = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005507
5508 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
5509 return -1;
5510 if (obj == Py_None)
5511 obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005512 if (obj != NULL) {
5513 obj_type = supercheck(type, obj);
5514 if (obj_type == NULL)
5515 return -1;
5516 Py_INCREF(obj);
5517 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005518 Py_INCREF(type);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005519 su->type = type;
5520 su->obj = obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005521 su->obj_type = obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005522 return 0;
5523}
5524
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005525PyDoc_STRVAR(super_doc,
Guido van Rossum705f0f52001-08-24 16:47:00 +00005526"super(type) -> unbound super object\n"
5527"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00005528"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00005529"Typical use to call a cooperative superclass method:\n"
5530"class C(B):\n"
5531" def meth(self, arg):\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005532" super(C, self).meth(arg)");
Guido van Rossum705f0f52001-08-24 16:47:00 +00005533
Guido van Rossum048eb752001-10-02 21:24:57 +00005534static int
5535super_traverse(PyObject *self, visitproc visit, void *arg)
5536{
5537 superobject *su = (superobject *)self;
5538 int err;
5539
5540#define VISIT(SLOT) \
5541 if (SLOT) { \
5542 err = visit((PyObject *)(SLOT), arg); \
5543 if (err) \
5544 return err; \
5545 }
5546
5547 VISIT(su->obj);
5548 VISIT(su->type);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005549 VISIT(su->obj_type);
Guido van Rossum048eb752001-10-02 21:24:57 +00005550
5551#undef VISIT
5552
5553 return 0;
5554}
5555
Guido van Rossum705f0f52001-08-24 16:47:00 +00005556PyTypeObject PySuper_Type = {
5557 PyObject_HEAD_INIT(&PyType_Type)
5558 0, /* ob_size */
5559 "super", /* tp_name */
5560 sizeof(superobject), /* tp_basicsize */
5561 0, /* tp_itemsize */
5562 /* methods */
5563 super_dealloc, /* tp_dealloc */
5564 0, /* tp_print */
5565 0, /* tp_getattr */
5566 0, /* tp_setattr */
5567 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005568 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005569 0, /* tp_as_number */
5570 0, /* tp_as_sequence */
5571 0, /* tp_as_mapping */
5572 0, /* tp_hash */
5573 0, /* tp_call */
5574 0, /* tp_str */
5575 super_getattro, /* tp_getattro */
5576 0, /* tp_setattro */
5577 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00005578 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
5579 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005580 super_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00005581 super_traverse, /* tp_traverse */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005582 0, /* tp_clear */
5583 0, /* tp_richcompare */
5584 0, /* tp_weaklistoffset */
5585 0, /* tp_iter */
5586 0, /* tp_iternext */
5587 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005588 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005589 0, /* tp_getset */
5590 0, /* tp_base */
5591 0, /* tp_dict */
5592 super_descr_get, /* tp_descr_get */
5593 0, /* tp_descr_set */
5594 0, /* tp_dictoffset */
5595 super_init, /* tp_init */
5596 PyType_GenericAlloc, /* tp_alloc */
5597 PyType_GenericNew, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00005598 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005599};