blob: e61eae882c2b1d5848da0e55591f7e18e014af49 [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
8/* The *real* layout of a type object when allocated on the heap */
9/* XXX Should we publish this in a header file? */
10typedef struct {
Guido van Rossum09638c12002-06-13 19:17:46 +000011 /* Note: there's a dependency on the order of these members
12 in slotptr() below. */
Guido van Rossum9923ffe2002-06-04 19:52:53 +000013 PyTypeObject type;
14 PyNumberMethods as_number;
Guido van Rossum9923ffe2002-06-04 19:52:53 +000015 PyMappingMethods as_mapping;
Guido van Rossum09638c12002-06-13 19:17:46 +000016 PySequenceMethods as_sequence; /* as_sequence comes after as_mapping,
17 so that the mapping wins when both
18 the mapping and the sequence define
19 a given operator (e.g. __getitem__).
20 see add_operators() below. */
Guido van Rossum9923ffe2002-06-04 19:52:53 +000021 PyBufferProcs as_buffer;
22 PyObject *name, *slots;
23 PyMemberDef members[1];
24} etype;
25
Guido van Rossum6f799372001-09-20 20:46:19 +000026static PyMemberDef type_members[] = {
Tim Peters6d6c1a32001-08-02 04:15:00 +000027 {"__basicsize__", T_INT, offsetof(PyTypeObject,tp_basicsize),READONLY},
28 {"__itemsize__", T_INT, offsetof(PyTypeObject, tp_itemsize), READONLY},
29 {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY},
Guido van Rossum9676b222001-08-17 20:32:36 +000030 {"__weakrefoffset__", T_LONG,
Tim Peters6d6c1a32001-08-02 04:15:00 +000031 offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
32 {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY},
33 {"__dictoffset__", T_LONG,
34 offsetof(PyTypeObject, tp_dictoffset), READONLY},
Tim Peters6d6c1a32001-08-02 04:15:00 +000035 {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY},
36 {0}
37};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000038
Guido van Rossumc0b618a1997-05-02 03:12:38 +000039static PyObject *
Guido van Rossumc3542212001-08-16 09:18:56 +000040type_name(PyTypeObject *type, void *context)
41{
42 char *s;
43
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +000044 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
45 etype* et = (etype*)type;
Tim Petersea7f75d2002-12-07 21:39:16 +000046
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +000047 Py_INCREF(et->name);
48 return et->name;
49 }
50 else {
51 s = strrchr(type->tp_name, '.');
52 if (s == NULL)
53 s = type->tp_name;
54 else
55 s++;
56 return PyString_FromString(s);
57 }
Guido van Rossumc3542212001-08-16 09:18:56 +000058}
59
Michael W. Hudson98bbc492002-11-26 14:47:27 +000060static int
61type_set_name(PyTypeObject *type, PyObject *value, void *context)
62{
63 etype* et;
64
65 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
66 PyErr_Format(PyExc_TypeError,
67 "can't set %s.__name__", type->tp_name);
68 return -1;
69 }
70 if (!value) {
71 PyErr_Format(PyExc_TypeError,
72 "can't delete %s.__name__", type->tp_name);
73 return -1;
74 }
75 if (!PyString_Check(value)) {
76 PyErr_Format(PyExc_TypeError,
77 "can only assign string to %s.__name__, not '%s'",
78 type->tp_name, value->ob_type->tp_name);
79 return -1;
80 }
Tim Petersea7f75d2002-12-07 21:39:16 +000081 if (strlen(PyString_AS_STRING(value))
Michael W. Hudson98bbc492002-11-26 14:47:27 +000082 != (size_t)PyString_GET_SIZE(value)) {
83 PyErr_Format(PyExc_ValueError,
84 "__name__ must not contain null bytes");
85 return -1;
86 }
87
88 et = (etype*)type;
89
90 Py_INCREF(value);
91
92 Py_DECREF(et->name);
93 et->name = value;
94
95 type->tp_name = PyString_AS_STRING(value);
96
97 return 0;
98}
99
Guido van Rossumc3542212001-08-16 09:18:56 +0000100static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000101type_module(PyTypeObject *type, void *context)
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000102{
Guido van Rossumc3542212001-08-16 09:18:56 +0000103 PyObject *mod;
104 char *s;
105
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +0000106 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
107 mod = PyDict_GetItemString(type->tp_dict, "__module__");
108 Py_XINCREF(mod);
Guido van Rossumc3542212001-08-16 09:18:56 +0000109 return mod;
110 }
Michael W. Hudsonade8c8b2002-11-27 16:29:26 +0000111 else {
112 s = strrchr(type->tp_name, '.');
113 if (s != NULL)
114 return PyString_FromStringAndSize(
115 type->tp_name, (int)(s - type->tp_name));
116 return PyString_FromString("__builtin__");
117 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000118}
119
Guido van Rossum3926a632001-09-25 16:25:58 +0000120static int
121type_set_module(PyTypeObject *type, PyObject *value, void *context)
122{
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000123 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
Guido van Rossum3926a632001-09-25 16:25:58 +0000124 PyErr_Format(PyExc_TypeError,
125 "can't set %s.__module__", type->tp_name);
126 return -1;
127 }
128 if (!value) {
129 PyErr_Format(PyExc_TypeError,
130 "can't delete %s.__module__", type->tp_name);
131 return -1;
132 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000133
Guido van Rossum3926a632001-09-25 16:25:58 +0000134 return PyDict_SetItemString(type->tp_dict, "__module__", value);
135}
136
Tim Peters6d6c1a32001-08-02 04:15:00 +0000137static PyObject *
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000138type_get_bases(PyTypeObject *type, void *context)
139{
140 Py_INCREF(type->tp_bases);
141 return type->tp_bases;
142}
143
144static PyTypeObject *best_base(PyObject *);
145static int mro_internal(PyTypeObject *);
146static int compatible_for_assignment(PyTypeObject *, PyTypeObject *, char *);
147static int add_subclass(PyTypeObject*, PyTypeObject*);
148static void remove_subclass(PyTypeObject *, PyTypeObject *);
149static void update_all_slots(PyTypeObject *);
150
151static int
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000152mro_subclasses(PyTypeObject *type, PyObject* temp)
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000153{
154 PyTypeObject *subclass;
155 PyObject *ref, *subclasses, *old_mro;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000156 int i, n;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000157
158 subclasses = type->tp_subclasses;
159 if (subclasses == NULL)
160 return 0;
161 assert(PyList_Check(subclasses));
162 n = PyList_GET_SIZE(subclasses);
163 for (i = 0; i < n; i++) {
164 ref = PyList_GET_ITEM(subclasses, i);
165 assert(PyWeakref_CheckRef(ref));
166 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
167 assert(subclass != NULL);
168 if ((PyObject *)subclass == Py_None)
169 continue;
170 assert(PyType_Check(subclass));
171 old_mro = subclass->tp_mro;
172 if (mro_internal(subclass) < 0) {
173 subclass->tp_mro = old_mro;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000174 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000175 }
176 else {
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000177 PyObject* tuple;
178 tuple = Py_BuildValue("OO", subclass, old_mro);
179 if (!tuple)
180 return -1;
181 if (PyList_Append(temp, tuple) < 0)
182 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000183 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000184 if (mro_subclasses(subclass, temp) < 0)
185 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000186 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000187 return 0;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000188}
189
190static int
191type_set_bases(PyTypeObject *type, PyObject *value, void *context)
192{
193 int i, r = 0;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000194 PyObject *ob, *temp;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000195 PyTypeObject *new_base, *old_base;
196 PyObject *old_bases, *old_mro;
197
198 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
199 PyErr_Format(PyExc_TypeError,
200 "can't set %s.__bases__", type->tp_name);
201 return -1;
202 }
203 if (!value) {
204 PyErr_Format(PyExc_TypeError,
205 "can't delete %s.__bases__", type->tp_name);
206 return -1;
207 }
208 if (!PyTuple_Check(value)) {
209 PyErr_Format(PyExc_TypeError,
210 "can only assign tuple to %s.__bases__, not %s",
211 type->tp_name, value->ob_type->tp_name);
212 return -1;
213 }
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +0000214 if (PyTuple_GET_SIZE(value) == 0) {
215 PyErr_Format(PyExc_TypeError,
216 "can only assign non-empty tuple to %s.__bases__, not ()",
217 type->tp_name);
218 return -1;
219 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000220 for (i = 0; i < PyTuple_GET_SIZE(value); i++) {
221 ob = PyTuple_GET_ITEM(value, i);
222 if (!PyClass_Check(ob) && !PyType_Check(ob)) {
223 PyErr_Format(
224 PyExc_TypeError,
225 "%s.__bases__ must be tuple of old- or new-style classes, not '%s'",
226 type->tp_name, ob->ob_type->tp_name);
227 return -1;
228 }
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +0000229 if (PyType_Check(ob)) {
230 if (PyType_IsSubtype((PyTypeObject*)ob, type)) {
231 PyErr_SetString(PyExc_TypeError,
232 "a __bases__ item causes an inheritance cycle");
233 return -1;
234 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000235 }
236 }
237
238 new_base = best_base(value);
239
240 if (!new_base) {
241 return -1;
242 }
243
244 if (!compatible_for_assignment(type->tp_base, new_base, "__bases__"))
245 return -1;
246
247 Py_INCREF(new_base);
248 Py_INCREF(value);
249
250 old_bases = type->tp_bases;
251 old_base = type->tp_base;
252 old_mro = type->tp_mro;
253
254 type->tp_bases = value;
255 type->tp_base = new_base;
256
257 if (mro_internal(type) < 0) {
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000258 goto bail;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000259 }
260
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000261 temp = PyList_New(0);
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000262 if (!temp)
263 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000264
265 r = mro_subclasses(type, temp);
266
267 if (r < 0) {
268 for (i = 0; i < PyList_Size(temp); i++) {
269 PyTypeObject* cls;
270 PyObject* mro;
271 PyArg_ParseTuple(PyList_GetItem(temp, i),
272 "OO", &cls, &mro);
273 Py_DECREF(cls->tp_mro);
274 cls->tp_mro = mro;
275 Py_INCREF(cls->tp_mro);
276 }
277 Py_DECREF(temp);
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000278 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000279 }
280
281 Py_DECREF(temp);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000282
283 /* any base that was in __bases__ but now isn't, we
Raymond Hettingera8285862002-12-14 17:17:56 +0000284 need to remove |type| from its tp_subclasses.
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000285 conversely, any class now in __bases__ that wasn't
Raymond Hettingera8285862002-12-14 17:17:56 +0000286 needs to have |type| added to its subclasses. */
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000287
288 /* for now, sod that: just remove from all old_bases,
289 add to all new_bases */
290
291 for (i = PyTuple_GET_SIZE(old_bases) - 1; i >= 0; i--) {
292 ob = PyTuple_GET_ITEM(old_bases, i);
293 if (PyType_Check(ob)) {
294 remove_subclass(
295 (PyTypeObject*)ob, type);
296 }
297 }
298
299 for (i = PyTuple_GET_SIZE(value) - 1; i >= 0; i--) {
300 ob = PyTuple_GET_ITEM(value, i);
301 if (PyType_Check(ob)) {
302 if (add_subclass((PyTypeObject*)ob, type) < 0)
303 r = -1;
304 }
305 }
306
307 update_all_slots(type);
308
309 Py_DECREF(old_bases);
310 Py_DECREF(old_base);
311 Py_DECREF(old_mro);
312
313 return r;
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000314
315 bail:
316 type->tp_bases = old_bases;
317 type->tp_base = old_base;
318 type->tp_mro = old_mro;
Tim Petersea7f75d2002-12-07 21:39:16 +0000319
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000320 Py_DECREF(value);
321 Py_DECREF(new_base);
Tim Petersea7f75d2002-12-07 21:39:16 +0000322
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000323 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000324}
325
326static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000327type_dict(PyTypeObject *type, void *context)
328{
329 if (type->tp_dict == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000330 Py_INCREF(Py_None);
331 return Py_None;
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000332 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000333 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000334}
335
Tim Peters24008312002-03-17 18:56:20 +0000336static PyObject *
337type_get_doc(PyTypeObject *type, void *context)
338{
339 PyObject *result;
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000340 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL)
Tim Peters24008312002-03-17 18:56:20 +0000341 return PyString_FromString(type->tp_doc);
Tim Peters24008312002-03-17 18:56:20 +0000342 result = PyDict_GetItemString(type->tp_dict, "__doc__");
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000343 if (result == NULL) {
344 result = Py_None;
345 Py_INCREF(result);
346 }
347 else if (result->ob_type->tp_descr_get) {
Tim Peters2b858972002-04-18 04:12:28 +0000348 result = result->ob_type->tp_descr_get(result, NULL,
349 (PyObject *)type);
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000350 }
351 else {
352 Py_INCREF(result);
353 }
Tim Peters24008312002-03-17 18:56:20 +0000354 return result;
355}
356
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000357static PyGetSetDef type_getsets[] = {
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000358 {"__name__", (getter)type_name, (setter)type_set_name, NULL},
359 {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL},
Guido van Rossum3926a632001-09-25 16:25:58 +0000360 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000361 {"__dict__", (getter)type_dict, NULL, NULL},
Tim Peters24008312002-03-17 18:56:20 +0000362 {"__doc__", (getter)type_get_doc, NULL, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000363 {0}
364};
365
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000366static int
367type_compare(PyObject *v, PyObject *w)
368{
369 /* This is called with type objects only. So we
370 can just compare the addresses. */
371 Py_uintptr_t vv = (Py_uintptr_t)v;
372 Py_uintptr_t ww = (Py_uintptr_t)w;
373 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
374}
375
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000376static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000377type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000378{
Barry Warsaw7ce36942001-08-24 18:34:26 +0000379 PyObject *mod, *name, *rtn;
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000380 char *kind;
Guido van Rossumc3542212001-08-16 09:18:56 +0000381
382 mod = type_module(type, NULL);
383 if (mod == NULL)
384 PyErr_Clear();
385 else if (!PyString_Check(mod)) {
386 Py_DECREF(mod);
387 mod = NULL;
388 }
389 name = type_name(type, NULL);
390 if (name == NULL)
391 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000392
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000393 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
394 kind = "class";
395 else
396 kind = "type";
397
Barry Warsaw7ce36942001-08-24 18:34:26 +0000398 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__")) {
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000399 rtn = PyString_FromFormat("<%s '%s.%s'>",
400 kind,
Barry Warsaw7ce36942001-08-24 18:34:26 +0000401 PyString_AS_STRING(mod),
402 PyString_AS_STRING(name));
403 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000404 else
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000405 rtn = PyString_FromFormat("<%s '%s'>", kind, type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000406
Guido van Rossumc3542212001-08-16 09:18:56 +0000407 Py_XDECREF(mod);
408 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000409 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000410}
411
Tim Peters6d6c1a32001-08-02 04:15:00 +0000412static PyObject *
413type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
414{
415 PyObject *obj;
416
417 if (type->tp_new == NULL) {
418 PyErr_Format(PyExc_TypeError,
419 "cannot create '%.100s' instances",
420 type->tp_name);
421 return NULL;
422 }
423
Tim Peters3f996e72001-09-13 19:18:27 +0000424 obj = type->tp_new(type, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000425 if (obj != NULL) {
Guido van Rossumf76de622001-10-18 15:49:21 +0000426 /* Ugly exception: when the call was type(something),
427 don't call tp_init on the result. */
428 if (type == &PyType_Type &&
429 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
430 (kwds == NULL ||
431 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
432 return obj;
Guido van Rossum8ace1ab2002-04-06 01:05:01 +0000433 /* If the returned object is not an instance of type,
434 it won't be initialized. */
435 if (!PyType_IsSubtype(obj->ob_type, type))
436 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000437 type = obj->ob_type;
Jeremy Hylton719841e2002-07-16 19:39:38 +0000438 if (PyType_HasFeature(type, Py_TPFLAGS_HAVE_CLASS) &&
439 type->tp_init != NULL &&
Tim Peters6d6c1a32001-08-02 04:15:00 +0000440 type->tp_init(obj, args, kwds) < 0) {
441 Py_DECREF(obj);
442 obj = NULL;
443 }
444 }
445 return obj;
446}
447
448PyObject *
449PyType_GenericAlloc(PyTypeObject *type, int nitems)
450{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000451 PyObject *obj;
Tim Petersf2a67da2001-10-07 03:54:51 +0000452 const size_t size = _PyObject_VAR_SIZE(type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000453
454 if (PyType_IS_GC(type))
Neil Schemenauer09a2ae52002-04-12 03:06:53 +0000455 obj = _PyObject_GC_Malloc(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000456 else
Neil Schemenauerc806c882001-08-29 23:54:54 +0000457 obj = PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000458
Neil Schemenauerc806c882001-08-29 23:54:54 +0000459 if (obj == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000460 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000461
Neil Schemenauerc806c882001-08-29 23:54:54 +0000462 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000463
Tim Peters6d6c1a32001-08-02 04:15:00 +0000464 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
465 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000466
Tim Peters6d6c1a32001-08-02 04:15:00 +0000467 if (type->tp_itemsize == 0)
468 PyObject_INIT(obj, type);
469 else
470 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000471
Tim Peters6d6c1a32001-08-02 04:15:00 +0000472 if (PyType_IS_GC(type))
Neil Schemenauerc806c882001-08-29 23:54:54 +0000473 _PyObject_GC_TRACK(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000474 return obj;
475}
476
477PyObject *
478PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
479{
480 return type->tp_alloc(type, 0);
481}
482
Guido van Rossum9475a232001-10-05 20:51:39 +0000483/* Helpers for subtyping */
484
485static int
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000486traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
487{
488 int i, n;
489 PyMemberDef *mp;
490
491 n = type->ob_size;
492 mp = ((etype *)type)->members;
493 for (i = 0; i < n; i++, mp++) {
494 if (mp->type == T_OBJECT_EX) {
495 char *addr = (char *)self + mp->offset;
496 PyObject *obj = *(PyObject **)addr;
497 if (obj != NULL) {
498 int err = visit(obj, arg);
499 if (err)
500 return err;
501 }
502 }
503 }
504 return 0;
505}
506
507static int
Guido van Rossum9475a232001-10-05 20:51:39 +0000508subtype_traverse(PyObject *self, visitproc visit, void *arg)
509{
510 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000511 traverseproc basetraverse;
Guido van Rossum9475a232001-10-05 20:51:39 +0000512
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000513 /* Find the nearest base with a different tp_traverse,
514 and traverse slots while we're at it */
Guido van Rossum9475a232001-10-05 20:51:39 +0000515 type = self->ob_type;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000516 base = type;
517 while ((basetraverse = base->tp_traverse) == subtype_traverse) {
518 if (base->ob_size) {
519 int err = traverse_slots(base, self, visit, arg);
520 if (err)
521 return err;
522 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000523 base = base->tp_base;
524 assert(base);
525 }
526
527 if (type->tp_dictoffset != base->tp_dictoffset) {
528 PyObject **dictptr = _PyObject_GetDictPtr(self);
529 if (dictptr && *dictptr) {
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000530 int err = visit(*dictptr, arg);
Guido van Rossum9475a232001-10-05 20:51:39 +0000531 if (err)
532 return err;
533 }
534 }
535
Guido van Rossuma3862092002-06-10 15:24:42 +0000536 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
537 /* For a heaptype, the instances count as references
538 to the type. Traverse the type so the collector
539 can find cycles involving this link. */
540 int err = visit((PyObject *)type, arg);
541 if (err)
542 return err;
543 }
544
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000545 if (basetraverse)
546 return basetraverse(self, visit, arg);
547 return 0;
548}
549
550static void
551clear_slots(PyTypeObject *type, PyObject *self)
552{
553 int i, n;
554 PyMemberDef *mp;
555
556 n = type->ob_size;
557 mp = ((etype *)type)->members;
558 for (i = 0; i < n; i++, mp++) {
559 if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
560 char *addr = (char *)self + mp->offset;
561 PyObject *obj = *(PyObject **)addr;
562 if (obj != NULL) {
563 Py_DECREF(obj);
564 *(PyObject **)addr = NULL;
565 }
566 }
567 }
568}
569
570static int
571subtype_clear(PyObject *self)
572{
573 PyTypeObject *type, *base;
574 inquiry baseclear;
575
576 /* Find the nearest base with a different tp_clear
577 and clear slots while we're at it */
578 type = self->ob_type;
579 base = type;
580 while ((baseclear = base->tp_clear) == subtype_clear) {
581 if (base->ob_size)
582 clear_slots(base, self);
583 base = base->tp_base;
584 assert(base);
585 }
586
Guido van Rossuma3862092002-06-10 15:24:42 +0000587 /* There's no need to clear the instance dict (if any);
588 the collector will call its tp_clear handler. */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000589
590 if (baseclear)
591 return baseclear(self);
Guido van Rossum9475a232001-10-05 20:51:39 +0000592 return 0;
593}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000594
595static void
596subtype_dealloc(PyObject *self)
597{
Guido van Rossum14227b42001-12-06 02:35:58 +0000598 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000599 destructor basedealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000600
Guido van Rossum22b13872002-08-06 21:41:44 +0000601 /* Extract the type; we expect it to be a heap type */
602 type = self->ob_type;
603 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000604
Guido van Rossum22b13872002-08-06 21:41:44 +0000605 /* Test whether the type has GC exactly once */
606
607 if (!PyType_IS_GC(type)) {
608 /* It's really rare to find a dynamic type that doesn't have
609 GC; it can only happen when deriving from 'object' and not
610 adding any slots or instance variables. This allows
611 certain simplifications: there's no need to call
612 clear_slots(), or DECREF the dict, or clear weakrefs. */
613
614 /* Maybe call finalizer; exit early if resurrected */
Guido van Rossumfebd61d2002-08-08 20:55:20 +0000615 if (type->tp_del) {
616 type->tp_del(self);
617 if (self->ob_refcnt > 0)
618 return;
619 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000620
621 /* Find the nearest base with a different tp_dealloc */
622 base = type;
623 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
624 assert(base->ob_size == 0);
625 base = base->tp_base;
626 assert(base);
627 }
628
629 /* Call the base tp_dealloc() */
630 assert(basedealloc);
631 basedealloc(self);
632
633 /* Can't reference self beyond this point */
634 Py_DECREF(type);
635
636 /* Done */
637 return;
638 }
639
640 /* We get here only if the type has GC */
641
642 /* UnTrack and re-Track around the trashcan macro, alas */
Andrew M. Kuchlingc9172d32003-02-06 15:22:49 +0000643 /* See explanation at end of function for full disclosure */
Guido van Rossum0906e072002-08-07 20:42:09 +0000644 PyObject_GC_UnTrack(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000645 ++_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000646 Py_TRASHCAN_SAFE_BEGIN(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000647 --_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000648 _PyObject_GC_TRACK(self); /* We'll untrack for real later */
649
650 /* Maybe call finalizer; exit early if resurrected */
Guido van Rossumfebd61d2002-08-08 20:55:20 +0000651 if (type->tp_del) {
652 type->tp_del(self);
653 if (self->ob_refcnt > 0)
654 goto endlabel;
655 }
Guido van Rossum7ad2d1e2001-10-29 22:11:00 +0000656
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000657 /* Find the nearest base with a different tp_dealloc
658 and clear slots while we're at it */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000659 base = type;
660 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
661 if (base->ob_size)
662 clear_slots(base, self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000663 base = base->tp_base;
664 assert(base);
Guido van Rossum14227b42001-12-06 02:35:58 +0000665 }
666
Tim Peters6d6c1a32001-08-02 04:15:00 +0000667 /* If we added a dict, DECREF it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000668 if (type->tp_dictoffset && !base->tp_dictoffset) {
669 PyObject **dictptr = _PyObject_GetDictPtr(self);
670 if (dictptr != NULL) {
671 PyObject *dict = *dictptr;
672 if (dict != NULL) {
673 Py_DECREF(dict);
674 *dictptr = NULL;
675 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000676 }
677 }
678
Guido van Rossum9676b222001-08-17 20:32:36 +0000679 /* If we added weaklist, we clear it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000680 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
Guido van Rossum9676b222001-08-17 20:32:36 +0000681 PyObject_ClearWeakRefs(self);
682
Tim Peters6d6c1a32001-08-02 04:15:00 +0000683 /* Finalize GC if the base doesn't do GC and we do */
Guido van Rossum22b13872002-08-06 21:41:44 +0000684 if (!PyType_IS_GC(base))
Guido van Rossum048eb752001-10-02 21:24:57 +0000685 _PyObject_GC_UNTRACK(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000686
687 /* Call the base tp_dealloc() */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000688 assert(basedealloc);
689 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000690
691 /* Can't reference self beyond this point */
Guido van Rossum22b13872002-08-06 21:41:44 +0000692 Py_DECREF(type);
693
Guido van Rossum0906e072002-08-07 20:42:09 +0000694 endlabel:
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000695 ++_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000696 Py_TRASHCAN_SAFE_END(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000697 --_PyTrash_delete_nesting;
698
699 /* Explanation of the weirdness around the trashcan macros:
700
701 Q. What do the trashcan macros do?
702
703 A. Read the comment titled "Trashcan mechanism" in object.h.
704 For one, this explains why there must be a call to GC-untrack
705 before the trashcan begin macro. Without understanding the
706 trashcan code, the answers to the following questions don't make
707 sense.
708
709 Q. Why do we GC-untrack before the trashcan and then immediately
710 GC-track again afterward?
711
712 A. In the case that the base class is GC-aware, the base class
713 probably GC-untracks the object. If it does that using the
714 UNTRACK macro, this will crash when the object is already
715 untracked. Because we don't know what the base class does, the
716 only safe thing is to make sure the object is tracked when we
717 call the base class dealloc. But... The trashcan begin macro
718 requires that the object is *untracked* before it is called. So
719 the dance becomes:
720
721 GC untrack
722 trashcan begin
723 GC track
724
725 Q. Why the bizarre (net-zero) manipulation of
726 _PyTrash_delete_nesting around the trashcan macros?
727
728 A. Some base classes (e.g. list) also use the trashcan mechanism.
729 The following scenario used to be possible:
730
731 - suppose the trashcan level is one below the trashcan limit
732
733 - subtype_dealloc() is called
734
735 - the trashcan limit is not yet reached, so the trashcan level
736 is incremented and the code between trashcan begin and end is
737 executed
738
739 - this destroys much of the object's contents, including its
740 slots and __dict__
741
742 - basedealloc() is called; this is really list_dealloc(), or
743 some other type which also uses the trashcan macros
744
745 - the trashcan limit is now reached, so the object is put on the
746 trashcan's to-be-deleted-later list
747
748 - basedealloc() returns
749
750 - subtype_dealloc() decrefs the object's type
751
752 - subtype_dealloc() returns
753
754 - later, the trashcan code starts deleting the objects from its
755 to-be-deleted-later list
756
757 - subtype_dealloc() is called *AGAIN* for the same object
758
759 - at the very least (if the destroyed slots and __dict__ don't
760 cause problems) the object's type gets decref'ed a second
761 time, which is *BAD*!!!
762
763 The remedy is to make sure that if the code between trashcan
764 begin and end in subtype_dealloc() is called, the code between
765 trashcan begin and end in basedealloc() will also be called.
766 This is done by decrementing the level after passing into the
767 trashcan block, and incrementing it just before leaving the
768 block.
769
770 But now it's possible that a chain of objects consisting solely
771 of objects whose deallocator is subtype_dealloc() will defeat
772 the trashcan mechanism completely: the decremented level means
773 that the effective level never reaches the limit. Therefore, we
774 *increment* the level *before* entering the trashcan block, and
775 matchingly decrement it after leaving. This means the trashcan
776 code will trigger a little early, but that's no big deal.
777
778 Q. Are there any live examples of code in need of all this
779 complexity?
780
781 A. Yes. See SF bug 668433 for code that crashed (when Python was
782 compiled in debug mode) before the trashcan level manipulations
783 were added. For more discussion, see SF patches 581742, 575073
784 and bug 574207.
785 */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000786}
787
Jeremy Hylton938ace62002-07-17 16:30:39 +0000788static PyTypeObject *solid_base(PyTypeObject *type);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000789
Tim Peters6d6c1a32001-08-02 04:15:00 +0000790/* type test with subclassing support */
791
792int
793PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
794{
795 PyObject *mro;
796
Guido van Rossum9478d072001-09-07 18:52:13 +0000797 if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
798 return b == a || b == &PyBaseObject_Type;
799
Tim Peters6d6c1a32001-08-02 04:15:00 +0000800 mro = a->tp_mro;
801 if (mro != NULL) {
802 /* Deal with multiple inheritance without recursion
803 by walking the MRO tuple */
804 int i, n;
805 assert(PyTuple_Check(mro));
806 n = PyTuple_GET_SIZE(mro);
807 for (i = 0; i < n; i++) {
808 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
809 return 1;
810 }
811 return 0;
812 }
813 else {
814 /* a is not completely initilized yet; follow tp_base */
815 do {
816 if (a == b)
817 return 1;
818 a = a->tp_base;
819 } while (a != NULL);
820 return b == &PyBaseObject_Type;
821 }
822}
823
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000824/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +0000825 without looking in the instance dictionary
826 (so we can't use PyObject_GetAttr) but still binding
827 it to the instance. The arguments are the object,
828 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000829 static variable used to cache the interned Python string.
830
831 Two variants:
832
833 - lookup_maybe() returns NULL without raising an exception
834 when the _PyType_Lookup() call fails;
835
836 - lookup_method() always raises an exception upon errors.
837*/
Guido van Rossum60718732001-08-28 17:47:51 +0000838
839static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000840lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +0000841{
842 PyObject *res;
843
844 if (*attrobj == NULL) {
845 *attrobj = PyString_InternFromString(attrstr);
846 if (*attrobj == NULL)
847 return NULL;
848 }
849 res = _PyType_Lookup(self->ob_type, *attrobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000850 if (res != NULL) {
Guido van Rossum60718732001-08-28 17:47:51 +0000851 descrgetfunc f;
852 if ((f = res->ob_type->tp_descr_get) == NULL)
853 Py_INCREF(res);
854 else
855 res = f(res, self, (PyObject *)(self->ob_type));
856 }
857 return res;
858}
859
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000860static PyObject *
861lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
862{
863 PyObject *res = lookup_maybe(self, attrstr, attrobj);
864 if (res == NULL && !PyErr_Occurred())
865 PyErr_SetObject(PyExc_AttributeError, *attrobj);
866 return res;
867}
868
Guido van Rossum2730b132001-08-28 18:22:14 +0000869/* A variation of PyObject_CallMethod that uses lookup_method()
870 instead of PyObject_GetAttrString(). This uses the same convention
871 as lookup_method to cache the interned name string object. */
872
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000873static PyObject *
Guido van Rossum2730b132001-08-28 18:22:14 +0000874call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
875{
876 va_list va;
877 PyObject *args, *func = 0, *retval;
Guido van Rossum2730b132001-08-28 18:22:14 +0000878 va_start(va, format);
879
Guido van Rossumda21c012001-10-03 00:50:18 +0000880 func = lookup_maybe(o, name, nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000881 if (func == NULL) {
882 va_end(va);
883 if (!PyErr_Occurred())
Guido van Rossumda21c012001-10-03 00:50:18 +0000884 PyErr_SetObject(PyExc_AttributeError, *nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000885 return NULL;
886 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000887
888 if (format && *format)
889 args = Py_VaBuildValue(format, va);
890 else
891 args = PyTuple_New(0);
892
893 va_end(va);
894
895 if (args == NULL)
896 return NULL;
897
898 assert(PyTuple_Check(args));
899 retval = PyObject_Call(func, args, NULL);
900
901 Py_DECREF(args);
902 Py_DECREF(func);
903
904 return retval;
905}
906
907/* Clone of call_method() that returns NotImplemented when the lookup fails. */
908
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000909static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000910call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
911{
912 va_list va;
913 PyObject *args, *func = 0, *retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000914 va_start(va, format);
915
Guido van Rossumda21c012001-10-03 00:50:18 +0000916 func = lookup_maybe(o, name, nameobj);
Guido van Rossum2730b132001-08-28 18:22:14 +0000917 if (func == NULL) {
918 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000919 if (!PyErr_Occurred()) {
920 Py_INCREF(Py_NotImplemented);
921 return Py_NotImplemented;
922 }
Guido van Rossum717ce002001-09-14 16:58:08 +0000923 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +0000924 }
925
926 if (format && *format)
927 args = Py_VaBuildValue(format, va);
928 else
929 args = PyTuple_New(0);
930
931 va_end(va);
932
Guido van Rossum717ce002001-09-14 16:58:08 +0000933 if (args == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +0000934 return NULL;
935
Guido van Rossum717ce002001-09-14 16:58:08 +0000936 assert(PyTuple_Check(args));
937 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +0000938
939 Py_DECREF(args);
940 Py_DECREF(func);
941
942 return retval;
943}
944
Tim Petersa91e9642001-11-14 23:32:33 +0000945static int
946fill_classic_mro(PyObject *mro, PyObject *cls)
947{
948 PyObject *bases, *base;
949 int i, n;
950
951 assert(PyList_Check(mro));
952 assert(PyClass_Check(cls));
953 i = PySequence_Contains(mro, cls);
954 if (i < 0)
955 return -1;
956 if (!i) {
957 if (PyList_Append(mro, cls) < 0)
958 return -1;
959 }
960 bases = ((PyClassObject *)cls)->cl_bases;
961 assert(bases && PyTuple_Check(bases));
962 n = PyTuple_GET_SIZE(bases);
963 for (i = 0; i < n; i++) {
964 base = PyTuple_GET_ITEM(bases, i);
965 if (fill_classic_mro(mro, base) < 0)
966 return -1;
967 }
968 return 0;
969}
970
971static PyObject *
972classic_mro(PyObject *cls)
973{
974 PyObject *mro;
975
976 assert(PyClass_Check(cls));
977 mro = PyList_New(0);
978 if (mro != NULL) {
979 if (fill_classic_mro(mro, cls) == 0)
980 return mro;
981 Py_DECREF(mro);
982 }
983 return NULL;
984}
985
Tim Petersea7f75d2002-12-07 21:39:16 +0000986/*
Guido van Rossum1f121312002-11-14 19:49:16 +0000987 Method resolution order algorithm C3 described in
988 "A Monotonic Superclass Linearization for Dylan",
989 by Kim Barrett, Bob Cassel, Paul Haahr,
Tim Petersea7f75d2002-12-07 21:39:16 +0000990 David A. Moon, Keith Playford, and P. Tucker Withington.
Guido van Rossum1f121312002-11-14 19:49:16 +0000991 (OOPSLA 1996)
992
Guido van Rossum98f33732002-11-25 21:36:54 +0000993 Some notes about the rules implied by C3:
994
Tim Petersea7f75d2002-12-07 21:39:16 +0000995 No duplicate bases.
Guido van Rossum98f33732002-11-25 21:36:54 +0000996 It isn't legal to repeat a class in a list of base classes.
997
998 The next three properties are the 3 constraints in "C3".
999
Tim Petersea7f75d2002-12-07 21:39:16 +00001000 Local precendece order.
Guido van Rossum98f33732002-11-25 21:36:54 +00001001 If A precedes B in C's MRO, then A will precede B in the MRO of all
1002 subclasses of C.
1003
1004 Monotonicity.
1005 The MRO of a class must be an extension without reordering of the
1006 MRO of each of its superclasses.
1007
1008 Extended Precedence Graph (EPG).
1009 Linearization is consistent if there is a path in the EPG from
1010 each class to all its successors in the linearization. See
1011 the paper for definition of EPG.
Guido van Rossum1f121312002-11-14 19:49:16 +00001012 */
1013
Tim Petersea7f75d2002-12-07 21:39:16 +00001014static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001015tail_contains(PyObject *list, int whence, PyObject *o) {
1016 int j, size;
1017 size = PyList_GET_SIZE(list);
1018
1019 for (j = whence+1; j < size; j++) {
1020 if (PyList_GET_ITEM(list, j) == o)
1021 return 1;
1022 }
1023 return 0;
1024}
1025
Guido van Rossum98f33732002-11-25 21:36:54 +00001026static PyObject *
1027class_name(PyObject *cls)
1028{
1029 PyObject *name = PyObject_GetAttrString(cls, "__name__");
1030 if (name == NULL) {
1031 PyErr_Clear();
1032 Py_XDECREF(name);
1033 name = PyObject_Repr(cls);
1034 }
1035 if (name == NULL)
1036 return NULL;
1037 if (!PyString_Check(name)) {
1038 Py_DECREF(name);
1039 return NULL;
1040 }
1041 return name;
1042}
1043
1044static int
1045check_duplicates(PyObject *list)
1046{
1047 int i, j, n;
1048 /* Let's use a quadratic time algorithm,
1049 assuming that the bases lists is short.
1050 */
1051 n = PyList_GET_SIZE(list);
1052 for (i = 0; i < n; i++) {
1053 PyObject *o = PyList_GET_ITEM(list, i);
1054 for (j = i + 1; j < n; j++) {
1055 if (PyList_GET_ITEM(list, j) == o) {
1056 o = class_name(o);
1057 PyErr_Format(PyExc_TypeError,
1058 "duplicate base class %s",
1059 o ? PyString_AS_STRING(o) : "?");
1060 Py_XDECREF(o);
1061 return -1;
1062 }
1063 }
1064 }
1065 return 0;
1066}
1067
1068/* Raise a TypeError for an MRO order disagreement.
1069
1070 It's hard to produce a good error message. In the absence of better
1071 insight into error reporting, report the classes that were candidates
1072 to be put next into the MRO. There is some conflict between the
1073 order in which they should be put in the MRO, but it's hard to
1074 diagnose what constraint can't be satisfied.
1075*/
1076
1077static void
1078set_mro_error(PyObject *to_merge, int *remain)
1079{
1080 int i, n, off, to_merge_size;
1081 char buf[1000];
1082 PyObject *k, *v;
1083 PyObject *set = PyDict_New();
1084
1085 to_merge_size = PyList_GET_SIZE(to_merge);
1086 for (i = 0; i < to_merge_size; i++) {
1087 PyObject *L = PyList_GET_ITEM(to_merge, i);
1088 if (remain[i] < PyList_GET_SIZE(L)) {
1089 PyObject *c = PyList_GET_ITEM(L, remain[i]);
1090 if (PyDict_SetItem(set, c, Py_None) < 0)
1091 return;
1092 }
1093 }
1094 n = PyDict_Size(set);
1095
1096 off = PyOS_snprintf(buf, sizeof(buf), "MRO conflict among bases");
1097 i = 0;
1098 while (PyDict_Next(set, &i, &k, &v) && off < sizeof(buf)) {
1099 PyObject *name = class_name(k);
1100 off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s",
1101 name ? PyString_AS_STRING(name) : "?");
1102 Py_XDECREF(name);
1103 if (--n && off+1 < sizeof(buf)) {
1104 buf[off++] = ',';
1105 buf[off] = '\0';
1106 }
1107 }
1108 PyErr_SetString(PyExc_TypeError, buf);
1109 Py_DECREF(set);
1110}
1111
Tim Petersea7f75d2002-12-07 21:39:16 +00001112static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001113pmerge(PyObject *acc, PyObject* to_merge) {
1114 int i, j, to_merge_size;
1115 int *remain;
1116 int ok, empty_cnt;
Tim Petersea7f75d2002-12-07 21:39:16 +00001117
Guido van Rossum1f121312002-11-14 19:49:16 +00001118 to_merge_size = PyList_GET_SIZE(to_merge);
1119
Guido van Rossum98f33732002-11-25 21:36:54 +00001120 /* remain stores an index into each sublist of to_merge.
1121 remain[i] is the index of the next base in to_merge[i]
1122 that is not included in acc.
1123 */
Guido van Rossum1f121312002-11-14 19:49:16 +00001124 remain = PyMem_MALLOC(SIZEOF_INT*to_merge_size);
1125 if (remain == NULL)
1126 return -1;
1127 for (i = 0; i < to_merge_size; i++)
1128 remain[i] = 0;
1129
1130 again:
1131 empty_cnt = 0;
1132 for (i = 0; i < to_merge_size; i++) {
1133 PyObject *candidate;
Tim Petersea7f75d2002-12-07 21:39:16 +00001134
Guido van Rossum1f121312002-11-14 19:49:16 +00001135 PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
1136
1137 if (remain[i] >= PyList_GET_SIZE(cur_list)) {
1138 empty_cnt++;
1139 continue;
1140 }
1141
Guido van Rossum98f33732002-11-25 21:36:54 +00001142 /* Choose next candidate for MRO.
1143
1144 The input sequences alone can determine the choice.
1145 If not, choose the class which appears in the MRO
1146 of the earliest direct superclass of the new class.
1147 */
1148
Guido van Rossum1f121312002-11-14 19:49:16 +00001149 candidate = PyList_GET_ITEM(cur_list, remain[i]);
1150 for (j = 0; j < to_merge_size; j++) {
1151 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum98f33732002-11-25 21:36:54 +00001152 if (tail_contains(j_lst, remain[j], candidate)) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001153 goto skip; /* continue outer loop */
Guido van Rossum98f33732002-11-25 21:36:54 +00001154 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001155 }
1156 ok = PyList_Append(acc, candidate);
1157 if (ok < 0) {
1158 PyMem_Free(remain);
1159 return -1;
1160 }
1161 for (j = 0; j < to_merge_size; j++) {
1162 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum768158c2002-12-31 16:33:01 +00001163 if (remain[j] < PyList_GET_SIZE(j_lst) &&
1164 PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001165 remain[j]++;
1166 }
1167 }
1168 goto again;
Tim Peters9a6b8d82002-11-14 23:22:33 +00001169 skip: ;
Guido van Rossum1f121312002-11-14 19:49:16 +00001170 }
1171
Guido van Rossum98f33732002-11-25 21:36:54 +00001172 if (empty_cnt == to_merge_size) {
1173 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001174 return 0;
Guido van Rossum98f33732002-11-25 21:36:54 +00001175 }
1176 set_mro_error(to_merge, remain);
1177 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001178 return -1;
1179}
1180
Tim Peters6d6c1a32001-08-02 04:15:00 +00001181static PyObject *
1182mro_implementation(PyTypeObject *type)
1183{
1184 int i, n, ok;
1185 PyObject *bases, *result;
Guido van Rossum1f121312002-11-14 19:49:16 +00001186 PyObject *to_merge, *bases_aslist;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001187
Guido van Rossum63517572002-06-18 16:44:57 +00001188 if(type->tp_dict == NULL) {
1189 if(PyType_Ready(type) < 0)
1190 return NULL;
1191 }
1192
Guido van Rossum98f33732002-11-25 21:36:54 +00001193 /* Find a superclass linearization that honors the constraints
1194 of the explicit lists of bases and the constraints implied by
Tim Petersea7f75d2002-12-07 21:39:16 +00001195 each base class.
Guido van Rossum98f33732002-11-25 21:36:54 +00001196
1197 to_merge is a list of lists, where each list is a superclass
1198 linearization implied by a base class. The last element of
1199 to_merge is the declared list of bases.
1200 */
1201
Tim Peters6d6c1a32001-08-02 04:15:00 +00001202 bases = type->tp_bases;
1203 n = PyTuple_GET_SIZE(bases);
Guido van Rossum1f121312002-11-14 19:49:16 +00001204
1205 to_merge = PyList_New(n+1);
1206 if (to_merge == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001207 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001208
Tim Peters6d6c1a32001-08-02 04:15:00 +00001209 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001210 PyObject *base = PyTuple_GET_ITEM(bases, i);
1211 PyObject *parentMRO;
1212 if (PyType_Check(base))
1213 parentMRO = PySequence_List(
1214 ((PyTypeObject*)base)->tp_mro);
1215 else
1216 parentMRO = classic_mro(base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001217 if (parentMRO == NULL) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001218 Py_DECREF(to_merge);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001219 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001220 }
1221
1222 PyList_SET_ITEM(to_merge, i, parentMRO);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001223 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001224
1225 bases_aslist = PySequence_List(bases);
1226 if (bases_aslist == NULL) {
1227 Py_DECREF(to_merge);
1228 return NULL;
1229 }
Guido van Rossum98f33732002-11-25 21:36:54 +00001230 /* This is just a basic sanity check. */
1231 if (check_duplicates(bases_aslist) < 0) {
1232 Py_DECREF(to_merge);
1233 Py_DECREF(bases_aslist);
1234 return NULL;
1235 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001236 PyList_SET_ITEM(to_merge, n, bases_aslist);
1237
1238 result = Py_BuildValue("[O]", (PyObject *)type);
1239 if (result == NULL) {
1240 Py_DECREF(to_merge);
1241 return NULL;
1242 }
1243
1244 ok = pmerge(result, to_merge);
1245 Py_DECREF(to_merge);
1246 if (ok < 0) {
1247 Py_DECREF(result);
1248 return NULL;
1249 }
1250
Tim Peters6d6c1a32001-08-02 04:15:00 +00001251 return result;
1252}
1253
1254static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001255mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001256{
1257 PyTypeObject *type = (PyTypeObject *)self;
1258
Tim Peters6d6c1a32001-08-02 04:15:00 +00001259 return mro_implementation(type);
1260}
1261
1262static int
1263mro_internal(PyTypeObject *type)
1264{
1265 PyObject *mro, *result, *tuple;
1266
1267 if (type->ob_type == &PyType_Type) {
1268 result = mro_implementation(type);
1269 }
1270 else {
Guido van Rossum60718732001-08-28 17:47:51 +00001271 static PyObject *mro_str;
1272 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001273 if (mro == NULL)
1274 return -1;
1275 result = PyObject_CallObject(mro, NULL);
1276 Py_DECREF(mro);
1277 }
1278 if (result == NULL)
1279 return -1;
1280 tuple = PySequence_Tuple(result);
1281 Py_DECREF(result);
1282 type->tp_mro = tuple;
1283 return 0;
1284}
1285
1286
1287/* Calculate the best base amongst multiple base classes.
1288 This is the first one that's on the path to the "solid base". */
1289
1290static PyTypeObject *
1291best_base(PyObject *bases)
1292{
1293 int i, n;
1294 PyTypeObject *base, *winner, *candidate, *base_i;
Tim Petersa91e9642001-11-14 23:32:33 +00001295 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001296
1297 assert(PyTuple_Check(bases));
1298 n = PyTuple_GET_SIZE(bases);
1299 assert(n > 0);
Tim Petersa91e9642001-11-14 23:32:33 +00001300 base = NULL;
1301 winner = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001302 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001303 base_proto = PyTuple_GET_ITEM(bases, i);
1304 if (PyClass_Check(base_proto))
1305 continue;
1306 if (!PyType_Check(base_proto)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001307 PyErr_SetString(
1308 PyExc_TypeError,
1309 "bases must be types");
1310 return NULL;
1311 }
Tim Petersa91e9642001-11-14 23:32:33 +00001312 base_i = (PyTypeObject *)base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001313 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001314 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001315 return NULL;
1316 }
1317 candidate = solid_base(base_i);
Tim Petersa91e9642001-11-14 23:32:33 +00001318 if (winner == NULL) {
1319 winner = candidate;
1320 base = base_i;
1321 }
1322 else if (PyType_IsSubtype(winner, candidate))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001323 ;
1324 else if (PyType_IsSubtype(candidate, winner)) {
1325 winner = candidate;
1326 base = base_i;
1327 }
1328 else {
1329 PyErr_SetString(
1330 PyExc_TypeError,
1331 "multiple bases have "
1332 "instance lay-out conflict");
1333 return NULL;
1334 }
1335 }
Guido van Rossume54616c2001-12-14 04:19:56 +00001336 if (base == NULL)
1337 PyErr_SetString(PyExc_TypeError,
1338 "a new-style class can't have only classic bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001339 return base;
1340}
1341
1342static int
1343extra_ivars(PyTypeObject *type, PyTypeObject *base)
1344{
Neil Schemenauerc806c882001-08-29 23:54:54 +00001345 size_t t_size = type->tp_basicsize;
1346 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001347
Guido van Rossum9676b222001-08-17 20:32:36 +00001348 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001349 if (type->tp_itemsize || base->tp_itemsize) {
1350 /* If itemsize is involved, stricter rules */
1351 return t_size != b_size ||
1352 type->tp_itemsize != base->tp_itemsize;
1353 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001354 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
1355 type->tp_weaklistoffset + sizeof(PyObject *) == t_size)
1356 t_size -= sizeof(PyObject *);
1357 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
1358 type->tp_dictoffset + sizeof(PyObject *) == t_size)
1359 t_size -= sizeof(PyObject *);
1360
1361 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001362}
1363
1364static PyTypeObject *
1365solid_base(PyTypeObject *type)
1366{
1367 PyTypeObject *base;
1368
1369 if (type->tp_base)
1370 base = solid_base(type->tp_base);
1371 else
1372 base = &PyBaseObject_Type;
1373 if (extra_ivars(type, base))
1374 return type;
1375 else
1376 return base;
1377}
1378
Jeremy Hylton938ace62002-07-17 16:30:39 +00001379static void object_dealloc(PyObject *);
1380static int object_init(PyObject *, PyObject *, PyObject *);
1381static int update_slot(PyTypeObject *, PyObject *);
1382static void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001383
1384static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001385subtype_dict(PyObject *obj, void *context)
1386{
1387 PyObject **dictptr = _PyObject_GetDictPtr(obj);
1388 PyObject *dict;
1389
1390 if (dictptr == NULL) {
1391 PyErr_SetString(PyExc_AttributeError,
1392 "This object has no __dict__");
1393 return NULL;
1394 }
1395 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +00001396 if (dict == NULL)
1397 *dictptr = dict = PyDict_New();
1398 Py_XINCREF(dict);
1399 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001400}
1401
Guido van Rossum6661be32001-10-26 04:26:12 +00001402static int
1403subtype_setdict(PyObject *obj, PyObject *value, void *context)
1404{
1405 PyObject **dictptr = _PyObject_GetDictPtr(obj);
1406 PyObject *dict;
1407
1408 if (dictptr == NULL) {
1409 PyErr_SetString(PyExc_AttributeError,
1410 "This object has no __dict__");
1411 return -1;
1412 }
Guido van Rossumd331cb52001-12-05 19:46:42 +00001413 if (value != NULL && !PyDict_Check(value)) {
Guido van Rossum6661be32001-10-26 04:26:12 +00001414 PyErr_SetString(PyExc_TypeError,
1415 "__dict__ must be set to a dictionary");
1416 return -1;
1417 }
1418 dict = *dictptr;
Guido van Rossumd331cb52001-12-05 19:46:42 +00001419 Py_XINCREF(value);
Guido van Rossum6661be32001-10-26 04:26:12 +00001420 *dictptr = value;
1421 Py_XDECREF(dict);
1422 return 0;
1423}
1424
Guido van Rossumad47da02002-08-12 19:05:44 +00001425static PyObject *
1426subtype_getweakref(PyObject *obj, void *context)
1427{
1428 PyObject **weaklistptr;
1429 PyObject *result;
1430
1431 if (obj->ob_type->tp_weaklistoffset == 0) {
1432 PyErr_SetString(PyExc_AttributeError,
1433 "This object has no __weaklist__");
1434 return NULL;
1435 }
1436 assert(obj->ob_type->tp_weaklistoffset > 0);
1437 assert(obj->ob_type->tp_weaklistoffset + sizeof(PyObject *) <=
Guido van Rossum3747a0f2002-08-12 19:25:08 +00001438 (size_t)(obj->ob_type->tp_basicsize));
Guido van Rossumad47da02002-08-12 19:05:44 +00001439 weaklistptr = (PyObject **)
Guido van Rossum3747a0f2002-08-12 19:25:08 +00001440 ((char *)obj + obj->ob_type->tp_weaklistoffset);
Guido van Rossumad47da02002-08-12 19:05:44 +00001441 if (*weaklistptr == NULL)
1442 result = Py_None;
1443 else
1444 result = *weaklistptr;
1445 Py_INCREF(result);
1446 return result;
1447}
1448
Guido van Rossum373c7412003-01-07 13:41:37 +00001449/* Three variants on the subtype_getsets list. */
1450
1451static PyGetSetDef subtype_getsets_full[] = {
Guido van Rossumad47da02002-08-12 19:05:44 +00001452 {"__dict__", subtype_dict, subtype_setdict,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001453 PyDoc_STR("dictionary for instance variables (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001454 {"__weakref__", subtype_getweakref, NULL,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001455 PyDoc_STR("list of weak references to the object (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001456 {0}
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001457};
1458
Guido van Rossum373c7412003-01-07 13:41:37 +00001459static PyGetSetDef subtype_getsets_dict_only[] = {
1460 {"__dict__", subtype_dict, subtype_setdict,
1461 PyDoc_STR("dictionary for instance variables (if defined)")},
1462 {0}
1463};
1464
1465static PyGetSetDef subtype_getsets_weakref_only[] = {
1466 {"__weakref__", subtype_getweakref, NULL,
1467 PyDoc_STR("list of weak references to the object (if defined)")},
1468 {0}
1469};
1470
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001471static int
1472valid_identifier(PyObject *s)
1473{
Guido van Rossum03013a02002-07-16 14:30:28 +00001474 unsigned char *p;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001475 int i, n;
1476
1477 if (!PyString_Check(s)) {
1478 PyErr_SetString(PyExc_TypeError,
1479 "__slots__ must be strings");
1480 return 0;
1481 }
Guido van Rossum03013a02002-07-16 14:30:28 +00001482 p = (unsigned char *) PyString_AS_STRING(s);
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001483 n = PyString_GET_SIZE(s);
1484 /* We must reject an empty name. As a hack, we bump the
1485 length to 1 so that the loop will balk on the trailing \0. */
1486 if (n == 0)
1487 n = 1;
1488 for (i = 0; i < n; i++, p++) {
1489 if (!(i == 0 ? isalpha(*p) : isalnum(*p)) && *p != '_') {
1490 PyErr_SetString(PyExc_TypeError,
1491 "__slots__ must be identifiers");
1492 return 0;
1493 }
1494 }
1495 return 1;
1496}
1497
Martin v. Löwisd919a592002-10-14 21:07:28 +00001498#ifdef Py_USING_UNICODE
1499/* Replace Unicode objects in slots. */
1500
1501static PyObject *
1502_unicode_to_string(PyObject *slots, int nslots)
1503{
1504 PyObject *tmp = slots;
1505 PyObject *o, *o1;
1506 int i;
1507 intintargfunc copy = slots->ob_type->tp_as_sequence->sq_slice;
1508 for (i = 0; i < nslots; i++) {
1509 if (PyUnicode_Check(o = PyTuple_GET_ITEM(tmp, i))) {
1510 if (tmp == slots) {
1511 tmp = copy(slots, 0, PyTuple_GET_SIZE(slots));
1512 if (tmp == NULL)
1513 return NULL;
1514 }
1515 o1 = _PyUnicode_AsDefaultEncodedString
1516 (o, NULL);
1517 if (o1 == NULL) {
1518 Py_DECREF(tmp);
1519 return 0;
1520 }
1521 Py_INCREF(o1);
1522 Py_DECREF(o);
1523 PyTuple_SET_ITEM(tmp, i, o1);
1524 }
1525 }
1526 return tmp;
1527}
1528#endif
1529
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001530static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001531type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
1532{
1533 PyObject *name, *bases, *dict;
1534 static char *kwlist[] = {"name", "bases", "dict", 0};
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001535 PyObject *slots, *tmp, *newslots;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001536 PyTypeObject *type, *base, *tmptype, *winner;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001537 etype *et;
Guido van Rossum6f799372001-09-20 20:46:19 +00001538 PyMemberDef *mp;
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001539 int i, nbases, nslots, slotoffset, add_dict, add_weak;
Guido van Rossumad47da02002-08-12 19:05:44 +00001540 int j, may_add_dict, may_add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001541
Tim Peters3abca122001-10-27 19:37:48 +00001542 assert(args != NULL && PyTuple_Check(args));
1543 assert(kwds == NULL || PyDict_Check(kwds));
1544
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001545 /* Special case: type(x) should return x->ob_type */
Tim Peters3abca122001-10-27 19:37:48 +00001546 {
1547 const int nargs = PyTuple_GET_SIZE(args);
1548 const int nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
1549
1550 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
1551 PyObject *x = PyTuple_GET_ITEM(args, 0);
1552 Py_INCREF(x->ob_type);
1553 return (PyObject *) x->ob_type;
1554 }
1555
1556 /* SF bug 475327 -- if that didn't trigger, we need 3
1557 arguments. but PyArg_ParseTupleAndKeywords below may give
1558 a msg saying type() needs exactly 3. */
1559 if (nargs + nkwds != 3) {
1560 PyErr_SetString(PyExc_TypeError,
1561 "type() takes 1 or 3 arguments");
1562 return NULL;
1563 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001564 }
1565
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001566 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001567 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
1568 &name,
1569 &PyTuple_Type, &bases,
1570 &PyDict_Type, &dict))
1571 return NULL;
1572
1573 /* Determine the proper metatype to deal with this,
1574 and check for metatype conflicts while we're at it.
1575 Note that if some other metatype wins to contract,
1576 it's possible that its instances are not types. */
1577 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001578 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001579 for (i = 0; i < nbases; i++) {
1580 tmp = PyTuple_GET_ITEM(bases, i);
1581 tmptype = tmp->ob_type;
Tim Petersa91e9642001-11-14 23:32:33 +00001582 if (tmptype == &PyClass_Type)
1583 continue; /* Special case classic classes */
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001584 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001585 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001586 if (PyType_IsSubtype(tmptype, winner)) {
1587 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001588 continue;
1589 }
1590 PyErr_SetString(PyExc_TypeError,
1591 "metatype conflict among bases");
1592 return NULL;
1593 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001594 if (winner != metatype) {
1595 if (winner->tp_new != type_new) /* Pass it to the winner */
1596 return winner->tp_new(winner, args, kwds);
1597 metatype = winner;
1598 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001599
1600 /* Adjust for empty tuple bases */
1601 if (nbases == 0) {
1602 bases = Py_BuildValue("(O)", &PyBaseObject_Type);
1603 if (bases == NULL)
1604 return NULL;
1605 nbases = 1;
1606 }
1607 else
1608 Py_INCREF(bases);
1609
1610 /* XXX From here until type is allocated, "return NULL" leaks bases! */
1611
1612 /* Calculate best base, and check that all bases are type objects */
1613 base = best_base(bases);
1614 if (base == NULL)
1615 return NULL;
1616 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
1617 PyErr_Format(PyExc_TypeError,
1618 "type '%.100s' is not an acceptable base type",
1619 base->tp_name);
1620 return NULL;
1621 }
1622
Tim Peters6d6c1a32001-08-02 04:15:00 +00001623 /* Check for a __slots__ sequence variable in dict, and count it */
1624 slots = PyDict_GetItemString(dict, "__slots__");
1625 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +00001626 add_dict = 0;
1627 add_weak = 0;
Guido van Rossumad47da02002-08-12 19:05:44 +00001628 may_add_dict = base->tp_dictoffset == 0;
1629 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
1630 if (slots == NULL) {
1631 if (may_add_dict) {
1632 add_dict++;
1633 }
1634 if (may_add_weak) {
1635 add_weak++;
1636 }
1637 }
1638 else {
1639 /* Have slots */
1640
Tim Peters6d6c1a32001-08-02 04:15:00 +00001641 /* Make it into a tuple */
1642 if (PyString_Check(slots))
1643 slots = Py_BuildValue("(O)", slots);
1644 else
1645 slots = PySequence_Tuple(slots);
1646 if (slots == NULL)
1647 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00001648 assert(PyTuple_Check(slots));
1649
1650 /* Are slots allowed? */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001651 nslots = PyTuple_GET_SIZE(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +00001652 if (nslots > 0 && base->tp_itemsize != 0) {
1653 PyErr_Format(PyExc_TypeError,
1654 "nonempty __slots__ "
1655 "not supported for subtype of '%s'",
1656 base->tp_name);
Guido van Rossumad47da02002-08-12 19:05:44 +00001657 bad_slots:
1658 Py_DECREF(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +00001659 return NULL;
1660 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001661
Martin v. Löwisd919a592002-10-14 21:07:28 +00001662#ifdef Py_USING_UNICODE
1663 tmp = _unicode_to_string(slots, nslots);
Martin v. Löwis13b1a5c2002-10-14 21:11:34 +00001664 if (tmp != slots) {
1665 Py_DECREF(slots);
1666 slots = tmp;
1667 }
Martin v. Löwisd919a592002-10-14 21:07:28 +00001668 if (!tmp)
1669 return NULL;
1670#endif
Guido van Rossumad47da02002-08-12 19:05:44 +00001671 /* Check for valid slot names and two special cases */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001672 for (i = 0; i < nslots; i++) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001673 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
1674 char *s;
1675 if (!valid_identifier(tmp))
1676 goto bad_slots;
1677 assert(PyString_Check(tmp));
1678 s = PyString_AS_STRING(tmp);
1679 if (strcmp(s, "__dict__") == 0) {
1680 if (!may_add_dict || add_dict) {
1681 PyErr_SetString(PyExc_TypeError,
1682 "__dict__ slot disallowed: "
1683 "we already got one");
1684 goto bad_slots;
1685 }
1686 add_dict++;
1687 }
1688 if (strcmp(s, "__weakref__") == 0) {
1689 if (!may_add_weak || add_weak) {
1690 PyErr_SetString(PyExc_TypeError,
1691 "__weakref__ slot disallowed: "
1692 "either we already got one, "
1693 "or __itemsize__ != 0");
1694 goto bad_slots;
1695 }
1696 add_weak++;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001697 }
1698 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001699
Guido van Rossumad47da02002-08-12 19:05:44 +00001700 /* Copy slots into yet another tuple, demangling names */
1701 newslots = PyTuple_New(nslots - add_dict - add_weak);
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001702 if (newslots == NULL)
Guido van Rossumad47da02002-08-12 19:05:44 +00001703 goto bad_slots;
1704 for (i = j = 0; i < nslots; i++) {
1705 char *s;
Guido van Rossum8e829202002-08-16 03:47:49 +00001706 char buffer[256];
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001707 tmp = PyTuple_GET_ITEM(slots, i);
Guido van Rossumad47da02002-08-12 19:05:44 +00001708 s = PyString_AS_STRING(tmp);
1709 if ((add_dict && strcmp(s, "__dict__") == 0) ||
1710 (add_weak && strcmp(s, "__weakref__") == 0))
1711 continue;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001712 if (_Py_Mangle(PyString_AS_STRING(name),
Guido van Rossumad47da02002-08-12 19:05:44 +00001713 PyString_AS_STRING(tmp),
1714 buffer, sizeof(buffer)))
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001715 {
1716 tmp = PyString_FromString(buffer);
1717 } else {
1718 Py_INCREF(tmp);
1719 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001720 PyTuple_SET_ITEM(newslots, j, tmp);
1721 j++;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001722 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001723 assert(j == nslots - add_dict - add_weak);
1724 nslots = j;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001725 Py_DECREF(slots);
1726 slots = newslots;
1727
Guido van Rossumad47da02002-08-12 19:05:44 +00001728 /* Secondary bases may provide weakrefs or dict */
1729 if (nbases > 1 &&
1730 ((may_add_dict && !add_dict) ||
1731 (may_add_weak && !add_weak))) {
1732 for (i = 0; i < nbases; i++) {
1733 tmp = PyTuple_GET_ITEM(bases, i);
1734 if (tmp == (PyObject *)base)
1735 continue; /* Skip primary base */
1736 if (PyClass_Check(tmp)) {
1737 /* Classic base class provides both */
1738 if (may_add_dict && !add_dict)
1739 add_dict++;
1740 if (may_add_weak && !add_weak)
1741 add_weak++;
1742 break;
1743 }
1744 assert(PyType_Check(tmp));
1745 tmptype = (PyTypeObject *)tmp;
1746 if (may_add_dict && !add_dict &&
1747 tmptype->tp_dictoffset != 0)
1748 add_dict++;
1749 if (may_add_weak && !add_weak &&
1750 tmptype->tp_weaklistoffset != 0)
1751 add_weak++;
1752 if (may_add_dict && !add_dict)
1753 continue;
1754 if (may_add_weak && !add_weak)
1755 continue;
1756 /* Nothing more to check */
1757 break;
1758 }
1759 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001760 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001761
1762 /* XXX From here until type is safely allocated,
1763 "return NULL" may leak slots! */
1764
1765 /* Allocate the type object */
1766 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
Guido van Rossumad47da02002-08-12 19:05:44 +00001767 if (type == NULL) {
1768 Py_XDECREF(slots);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001769 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00001770 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001771
1772 /* Keep name and slots alive in the extended type object */
1773 et = (etype *)type;
1774 Py_INCREF(name);
1775 et->name = name;
1776 et->slots = slots;
1777
Guido van Rossumdc91b992001-08-08 22:26:22 +00001778 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001779 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
1780 Py_TPFLAGS_BASETYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00001781 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
1782 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00001783
1784 /* It's a new-style number unless it specifically inherits any
1785 old-style numeric behavior */
1786 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
1787 (base->tp_as_number == NULL))
1788 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
1789
1790 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001791 type->tp_as_number = &et->as_number;
1792 type->tp_as_sequence = &et->as_sequence;
1793 type->tp_as_mapping = &et->as_mapping;
1794 type->tp_as_buffer = &et->as_buffer;
1795 type->tp_name = PyString_AS_STRING(name);
1796
1797 /* Set tp_base and tp_bases */
1798 type->tp_bases = bases;
1799 Py_INCREF(base);
1800 type->tp_base = base;
1801
Guido van Rossum687ae002001-10-15 22:03:32 +00001802 /* Initialize tp_dict from passed-in dict */
1803 type->tp_dict = dict = PyDict_Copy(dict);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001804 if (dict == NULL) {
1805 Py_DECREF(type);
1806 return NULL;
1807 }
1808
Guido van Rossumc3542212001-08-16 09:18:56 +00001809 /* Set __module__ in the dict */
1810 if (PyDict_GetItemString(dict, "__module__") == NULL) {
1811 tmp = PyEval_GetGlobals();
1812 if (tmp != NULL) {
1813 tmp = PyDict_GetItemString(tmp, "__name__");
1814 if (tmp != NULL) {
1815 if (PyDict_SetItemString(dict, "__module__",
1816 tmp) < 0)
1817 return NULL;
1818 }
1819 }
1820 }
1821
Tim Peters2f93e282001-10-04 05:27:00 +00001822 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
Tim Peters24008312002-03-17 18:56:20 +00001823 and is a string. The __doc__ accessor will first look for tp_doc;
1824 if that fails, it will still look into __dict__.
Tim Peters2f93e282001-10-04 05:27:00 +00001825 */
1826 {
1827 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
1828 if (doc != NULL && PyString_Check(doc)) {
1829 const size_t n = (size_t)PyString_GET_SIZE(doc);
Tim Peters59f809d2001-10-04 05:43:02 +00001830 type->tp_doc = (char *)PyObject_MALLOC(n+1);
Tim Peters2f93e282001-10-04 05:27:00 +00001831 if (type->tp_doc == NULL) {
1832 Py_DECREF(type);
1833 return NULL;
1834 }
1835 memcpy(type->tp_doc, PyString_AS_STRING(doc), n+1);
1836 }
1837 }
1838
Tim Peters6d6c1a32001-08-02 04:15:00 +00001839 /* Special-case __new__: if it's a plain function,
1840 make it a static function */
1841 tmp = PyDict_GetItemString(dict, "__new__");
1842 if (tmp != NULL && PyFunction_Check(tmp)) {
1843 tmp = PyStaticMethod_New(tmp);
1844 if (tmp == NULL) {
1845 Py_DECREF(type);
1846 return NULL;
1847 }
1848 PyDict_SetItemString(dict, "__new__", tmp);
1849 Py_DECREF(tmp);
1850 }
1851
1852 /* Add descriptors for custom slots from __slots__, or for __dict__ */
1853 mp = et->members;
Neil Schemenauerc806c882001-08-29 23:54:54 +00001854 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001855 if (slots != NULL) {
1856 for (i = 0; i < nslots; i++, mp++) {
1857 mp->name = PyString_AS_STRING(
1858 PyTuple_GET_ITEM(slots, i));
Guido van Rossum64b206c2001-12-04 17:13:22 +00001859 mp->type = T_OBJECT_EX;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001860 mp->offset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +00001861 if (base->tp_weaklistoffset == 0 &&
Guido van Rossum64b206c2001-12-04 17:13:22 +00001862 strcmp(mp->name, "__weakref__") == 0) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001863 add_weak++;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001864 mp->type = T_OBJECT;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001865 mp->flags = READONLY;
Guido van Rossum9676b222001-08-17 20:32:36 +00001866 type->tp_weaklistoffset = slotoffset;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001867 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001868 slotoffset += sizeof(PyObject *);
1869 }
1870 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001871 if (add_dict) {
1872 if (base->tp_itemsize)
1873 type->tp_dictoffset = -(long)sizeof(PyObject *);
1874 else
1875 type->tp_dictoffset = slotoffset;
1876 slotoffset += sizeof(PyObject *);
1877 }
1878 if (add_weak) {
1879 assert(!base->tp_itemsize);
1880 type->tp_weaklistoffset = slotoffset;
1881 slotoffset += sizeof(PyObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001882 }
1883 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001884 type->tp_itemsize = base->tp_itemsize;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001885 type->tp_members = et->members;
Guido van Rossum373c7412003-01-07 13:41:37 +00001886
1887 if (type->tp_weaklistoffset && type->tp_dictoffset)
1888 type->tp_getset = subtype_getsets_full;
1889 else if (type->tp_weaklistoffset && !type->tp_dictoffset)
1890 type->tp_getset = subtype_getsets_weakref_only;
1891 else if (!type->tp_weaklistoffset && type->tp_dictoffset)
1892 type->tp_getset = subtype_getsets_dict_only;
1893 else
1894 type->tp_getset = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001895
1896 /* Special case some slots */
1897 if (type->tp_dictoffset != 0 || nslots > 0) {
1898 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
1899 type->tp_getattro = PyObject_GenericGetAttr;
1900 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
1901 type->tp_setattro = PyObject_GenericSetAttr;
1902 }
1903 type->tp_dealloc = subtype_dealloc;
1904
Guido van Rossum9475a232001-10-05 20:51:39 +00001905 /* Enable GC unless there are really no instance variables possible */
1906 if (!(type->tp_basicsize == sizeof(PyObject) &&
1907 type->tp_itemsize == 0))
1908 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
1909
Tim Peters6d6c1a32001-08-02 04:15:00 +00001910 /* Always override allocation strategy to use regular heap */
1911 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00001912 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001913 type->tp_free = PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00001914 type->tp_traverse = subtype_traverse;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001915 type->tp_clear = subtype_clear;
Guido van Rossum048eb752001-10-02 21:24:57 +00001916 }
1917 else
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001918 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001919
1920 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001921 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001922 Py_DECREF(type);
1923 return NULL;
1924 }
1925
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001926 /* Put the proper slots in place */
1927 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00001928
Tim Peters6d6c1a32001-08-02 04:15:00 +00001929 return (PyObject *)type;
1930}
1931
1932/* Internal API to look for a name through the MRO.
1933 This returns a borrowed reference, and doesn't set an exception! */
1934PyObject *
1935_PyType_Lookup(PyTypeObject *type, PyObject *name)
1936{
1937 int i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00001938 PyObject *mro, *res, *base, *dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001939
Guido van Rossum687ae002001-10-15 22:03:32 +00001940 /* Look in tp_dict of types in MRO */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001941 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00001942
1943 /* If mro is NULL, the type is either not yet initialized
1944 by PyType_Ready(), or already cleared by type_clear().
1945 Either way the safest thing to do is to return NULL. */
1946 if (mro == NULL)
1947 return NULL;
1948
Tim Peters6d6c1a32001-08-02 04:15:00 +00001949 assert(PyTuple_Check(mro));
1950 n = PyTuple_GET_SIZE(mro);
1951 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001952 base = PyTuple_GET_ITEM(mro, i);
1953 if (PyClass_Check(base))
1954 dict = ((PyClassObject *)base)->cl_dict;
1955 else {
1956 assert(PyType_Check(base));
1957 dict = ((PyTypeObject *)base)->tp_dict;
1958 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001959 assert(dict && PyDict_Check(dict));
1960 res = PyDict_GetItem(dict, name);
1961 if (res != NULL)
1962 return res;
1963 }
1964 return NULL;
1965}
1966
1967/* This is similar to PyObject_GenericGetAttr(),
1968 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
1969static PyObject *
1970type_getattro(PyTypeObject *type, PyObject *name)
1971{
1972 PyTypeObject *metatype = type->ob_type;
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001973 PyObject *meta_attribute, *attribute;
1974 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001975
1976 /* Initialize this type (we'll assume the metatype is initialized) */
1977 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001978 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001979 return NULL;
1980 }
1981
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001982 /* No readable descriptor found yet */
1983 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00001984
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001985 /* Look for the attribute in the metatype */
1986 meta_attribute = _PyType_Lookup(metatype, name);
1987
1988 if (meta_attribute != NULL) {
1989 meta_get = meta_attribute->ob_type->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00001990
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001991 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
1992 /* Data descriptors implement tp_descr_set to intercept
1993 * writes. Assume the attribute is not overridden in
1994 * type's tp_dict (and bases): call the descriptor now.
1995 */
1996 return meta_get(meta_attribute, (PyObject *)type,
1997 (PyObject *)metatype);
1998 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001999 }
2000
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002001 /* No data descriptor found on metatype. Look in tp_dict of this
2002 * type and its bases */
2003 attribute = _PyType_Lookup(type, name);
2004 if (attribute != NULL) {
2005 /* Implement descriptor functionality, if any */
2006 descrgetfunc local_get = attribute->ob_type->tp_descr_get;
2007 if (local_get != NULL) {
2008 /* NULL 2nd argument indicates the descriptor was
2009 * found on the target object itself (or a base) */
2010 return local_get(attribute, (PyObject *)NULL,
2011 (PyObject *)type);
2012 }
Tim Peters34592512002-07-11 06:23:50 +00002013
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002014 Py_INCREF(attribute);
2015 return attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002016 }
2017
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002018 /* No attribute found in local __dict__ (or bases): use the
2019 * descriptor from the metatype, if any */
2020 if (meta_get != NULL)
2021 return meta_get(meta_attribute, (PyObject *)type,
2022 (PyObject *)metatype);
2023
2024 /* If an ordinary attribute was found on the metatype, return it now */
2025 if (meta_attribute != NULL) {
2026 Py_INCREF(meta_attribute);
2027 return meta_attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002028 }
2029
2030 /* Give up */
2031 PyErr_Format(PyExc_AttributeError,
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002032 "type object '%.50s' has no attribute '%.400s'",
2033 type->tp_name, PyString_AS_STRING(name));
Tim Peters6d6c1a32001-08-02 04:15:00 +00002034 return NULL;
2035}
2036
2037static int
2038type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
2039{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002040 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2041 PyErr_Format(
2042 PyExc_TypeError,
2043 "can't set attributes of built-in/extension type '%s'",
2044 type->tp_name);
2045 return -1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002046 }
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002047 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
2048 return -1;
2049 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002050}
2051
2052static void
2053type_dealloc(PyTypeObject *type)
2054{
2055 etype *et;
2056
2057 /* Assert this is a heap-allocated type object */
2058 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002059 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00002060 PyObject_ClearWeakRefs((PyObject *)type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002061 et = (etype *)type;
2062 Py_XDECREF(type->tp_base);
2063 Py_XDECREF(type->tp_dict);
2064 Py_XDECREF(type->tp_bases);
2065 Py_XDECREF(type->tp_mro);
Guido van Rossum687ae002001-10-15 22:03:32 +00002066 Py_XDECREF(type->tp_cache);
Guido van Rossum1c450732001-10-08 15:18:27 +00002067 Py_XDECREF(type->tp_subclasses);
Neal Norwitzcee5ca02002-07-30 00:42:06 +00002068 PyObject_Free(type->tp_doc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002069 Py_XDECREF(et->name);
2070 Py_XDECREF(et->slots);
2071 type->ob_type->tp_free((PyObject *)type);
2072}
2073
Guido van Rossum1c450732001-10-08 15:18:27 +00002074static PyObject *
2075type_subclasses(PyTypeObject *type, PyObject *args_ignored)
2076{
2077 PyObject *list, *raw, *ref;
2078 int i, n;
2079
2080 list = PyList_New(0);
2081 if (list == NULL)
2082 return NULL;
2083 raw = type->tp_subclasses;
2084 if (raw == NULL)
2085 return list;
2086 assert(PyList_Check(raw));
2087 n = PyList_GET_SIZE(raw);
2088 for (i = 0; i < n; i++) {
2089 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00002090 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00002091 ref = PyWeakref_GET_OBJECT(ref);
2092 if (ref != Py_None) {
2093 if (PyList_Append(list, ref) < 0) {
2094 Py_DECREF(list);
2095 return NULL;
2096 }
2097 }
2098 }
2099 return list;
2100}
2101
Tim Peters6d6c1a32001-08-02 04:15:00 +00002102static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002103 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002104 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
Guido van Rossum1c450732001-10-08 15:18:27 +00002105 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002106 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002107 {0}
2108};
2109
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002110PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002111"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002112"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002113
Guido van Rossum048eb752001-10-02 21:24:57 +00002114static int
2115type_traverse(PyTypeObject *type, visitproc visit, void *arg)
2116{
Guido van Rossum048eb752001-10-02 21:24:57 +00002117 int err;
2118
Guido van Rossuma3862092002-06-10 15:24:42 +00002119 /* Because of type_is_gc(), the collector only calls this
2120 for heaptypes. */
2121 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002122
2123#define VISIT(SLOT) \
2124 if (SLOT) { \
2125 err = visit((PyObject *)(SLOT), arg); \
2126 if (err) \
2127 return err; \
2128 }
2129
2130 VISIT(type->tp_dict);
Guido van Rossum687ae002001-10-15 22:03:32 +00002131 VISIT(type->tp_cache);
Guido van Rossum048eb752001-10-02 21:24:57 +00002132 VISIT(type->tp_mro);
2133 VISIT(type->tp_bases);
2134 VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00002135
2136 /* There's no need to visit type->tp_subclasses or
2137 ((etype *)type)->slots, because they can't be involved
2138 in cycles; tp_subclasses is a list of weak references,
2139 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00002140
2141#undef VISIT
2142
2143 return 0;
2144}
2145
2146static int
2147type_clear(PyTypeObject *type)
2148{
Guido van Rossum048eb752001-10-02 21:24:57 +00002149 PyObject *tmp;
2150
Guido van Rossuma3862092002-06-10 15:24:42 +00002151 /* Because of type_is_gc(), the collector only calls this
2152 for heaptypes. */
2153 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002154
2155#define CLEAR(SLOT) \
2156 if (SLOT) { \
2157 tmp = (PyObject *)(SLOT); \
2158 SLOT = NULL; \
2159 Py_DECREF(tmp); \
2160 }
2161
Guido van Rossuma3862092002-06-10 15:24:42 +00002162 /* The only field we need to clear is tp_mro, which is part of a
2163 hard cycle (its first element is the class itself) that won't
2164 be broken otherwise (it's a tuple and tuples don't have a
2165 tp_clear handler). None of the other fields need to be
2166 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00002167
Guido van Rossuma3862092002-06-10 15:24:42 +00002168 tp_dict:
2169 It is a dict, so the collector will call its tp_clear.
2170
2171 tp_cache:
2172 Not used; if it were, it would be a dict.
2173
2174 tp_bases, tp_base:
2175 If these are involved in a cycle, there must be at least
2176 one other, mutable object in the cycle, e.g. a base
2177 class's dict; the cycle will be broken that way.
2178
2179 tp_subclasses:
2180 A list of weak references can't be part of a cycle; and
2181 lists have their own tp_clear.
2182
2183 slots (in etype):
2184 A tuple of strings can't be part of a cycle.
2185 */
2186
2187 CLEAR(type->tp_mro);
Tim Peters2f93e282001-10-04 05:27:00 +00002188
Guido van Rossum048eb752001-10-02 21:24:57 +00002189#undef CLEAR
2190
2191 return 0;
2192}
2193
2194static int
2195type_is_gc(PyTypeObject *type)
2196{
2197 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
2198}
2199
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002200PyTypeObject PyType_Type = {
2201 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002202 0, /* ob_size */
2203 "type", /* tp_name */
2204 sizeof(etype), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00002205 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002206 (destructor)type_dealloc, /* tp_dealloc */
2207 0, /* tp_print */
2208 0, /* tp_getattr */
2209 0, /* tp_setattr */
2210 type_compare, /* tp_compare */
2211 (reprfunc)type_repr, /* tp_repr */
2212 0, /* tp_as_number */
2213 0, /* tp_as_sequence */
2214 0, /* tp_as_mapping */
2215 (hashfunc)_Py_HashPointer, /* tp_hash */
2216 (ternaryfunc)type_call, /* tp_call */
2217 0, /* tp_str */
2218 (getattrofunc)type_getattro, /* tp_getattro */
2219 (setattrofunc)type_setattro, /* tp_setattro */
2220 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00002221 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2222 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002223 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00002224 (traverseproc)type_traverse, /* tp_traverse */
2225 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002226 0, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00002227 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002228 0, /* tp_iter */
2229 0, /* tp_iternext */
2230 type_methods, /* tp_methods */
2231 type_members, /* tp_members */
2232 type_getsets, /* tp_getset */
2233 0, /* tp_base */
2234 0, /* tp_dict */
2235 0, /* tp_descr_get */
2236 0, /* tp_descr_set */
2237 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
2238 0, /* tp_init */
2239 0, /* tp_alloc */
2240 type_new, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002241 PyObject_GC_Del, /* tp_free */
Guido van Rossum048eb752001-10-02 21:24:57 +00002242 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002243};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002244
2245
2246/* The base type of all types (eventually)... except itself. */
2247
2248static int
2249object_init(PyObject *self, PyObject *args, PyObject *kwds)
2250{
2251 return 0;
2252}
2253
Guido van Rossum298e4212003-02-13 16:30:16 +00002254/* If we don't have a tp_new for a new-style class, new will use this one.
2255 Therefore this should take no arguments/keywords. However, this new may
2256 also be inherited by objects that define a tp_init but no tp_new. These
2257 objects WILL pass argumets to tp_new, because it gets the same args as
2258 tp_init. So only allow arguments if we aren't using the default init, in
2259 which case we expect init to handle argument parsing. */
2260static PyObject *
2261object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2262{
2263 if (type->tp_init == object_init && (PyTuple_GET_SIZE(args) ||
2264 (kwds && PyDict_Check(kwds) && PyDict_Size(kwds)))) {
2265 PyErr_SetString(PyExc_TypeError,
2266 "default __new__ takes no parameters");
2267 return NULL;
2268 }
2269 return type->tp_alloc(type, 0);
2270}
2271
Tim Peters6d6c1a32001-08-02 04:15:00 +00002272static void
2273object_dealloc(PyObject *self)
2274{
2275 self->ob_type->tp_free(self);
2276}
2277
Guido van Rossum8e248182001-08-12 05:17:56 +00002278static PyObject *
2279object_repr(PyObject *self)
2280{
Guido van Rossum76e69632001-08-16 18:52:43 +00002281 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00002282 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002283
Guido van Rossum76e69632001-08-16 18:52:43 +00002284 type = self->ob_type;
2285 mod = type_module(type, NULL);
2286 if (mod == NULL)
2287 PyErr_Clear();
2288 else if (!PyString_Check(mod)) {
2289 Py_DECREF(mod);
2290 mod = NULL;
2291 }
2292 name = type_name(type, NULL);
2293 if (name == NULL)
2294 return NULL;
2295 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002296 rtn = PyString_FromFormat("<%s.%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002297 PyString_AS_STRING(mod),
2298 PyString_AS_STRING(name),
2299 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002300 else
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002301 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002302 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002303 Py_XDECREF(mod);
2304 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00002305 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002306}
2307
Guido van Rossumb8f63662001-08-15 23:57:02 +00002308static PyObject *
2309object_str(PyObject *self)
2310{
2311 unaryfunc f;
2312
2313 f = self->ob_type->tp_repr;
2314 if (f == NULL)
2315 f = object_repr;
2316 return f(self);
2317}
2318
Guido van Rossum8e248182001-08-12 05:17:56 +00002319static long
2320object_hash(PyObject *self)
2321{
2322 return _Py_HashPointer(self);
2323}
Guido van Rossum8e248182001-08-12 05:17:56 +00002324
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002325static PyObject *
2326object_get_class(PyObject *self, void *closure)
2327{
2328 Py_INCREF(self->ob_type);
2329 return (PyObject *)(self->ob_type);
2330}
2331
2332static int
2333equiv_structs(PyTypeObject *a, PyTypeObject *b)
2334{
2335 return a == b ||
2336 (a != NULL &&
2337 b != NULL &&
2338 a->tp_basicsize == b->tp_basicsize &&
2339 a->tp_itemsize == b->tp_itemsize &&
2340 a->tp_dictoffset == b->tp_dictoffset &&
2341 a->tp_weaklistoffset == b->tp_weaklistoffset &&
2342 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
2343 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
2344}
2345
2346static int
2347same_slots_added(PyTypeObject *a, PyTypeObject *b)
2348{
2349 PyTypeObject *base = a->tp_base;
2350 int size;
2351
2352 if (base != b->tp_base)
2353 return 0;
2354 if (equiv_structs(a, base) && equiv_structs(b, base))
2355 return 1;
2356 size = base->tp_basicsize;
2357 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
2358 size += sizeof(PyObject *);
2359 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
2360 size += sizeof(PyObject *);
2361 return size == a->tp_basicsize && size == b->tp_basicsize;
2362}
2363
2364static int
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002365compatible_for_assignment(PyTypeObject* old, PyTypeObject* new, char* attr)
2366{
2367 PyTypeObject *newbase, *oldbase;
2368
2369 if (new->tp_dealloc != old->tp_dealloc ||
2370 new->tp_free != old->tp_free)
2371 {
2372 PyErr_Format(PyExc_TypeError,
2373 "%s assignment: "
2374 "'%s' deallocator differs from '%s'",
2375 attr,
2376 new->tp_name,
2377 old->tp_name);
2378 return 0;
2379 }
2380 newbase = new;
2381 oldbase = old;
2382 while (equiv_structs(newbase, newbase->tp_base))
2383 newbase = newbase->tp_base;
2384 while (equiv_structs(oldbase, oldbase->tp_base))
2385 oldbase = oldbase->tp_base;
2386 if (newbase != oldbase &&
2387 (newbase->tp_base != oldbase->tp_base ||
2388 !same_slots_added(newbase, oldbase))) {
2389 PyErr_Format(PyExc_TypeError,
2390 "%s assignment: "
2391 "'%s' object layout differs from '%s'",
2392 attr,
2393 new->tp_name,
2394 old->tp_name);
2395 return 0;
2396 }
Tim Petersea7f75d2002-12-07 21:39:16 +00002397
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002398 return 1;
2399}
2400
2401static int
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002402object_set_class(PyObject *self, PyObject *value, void *closure)
2403{
2404 PyTypeObject *old = self->ob_type;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002405 PyTypeObject *new;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002406
Guido van Rossumb6b89422002-04-15 01:03:30 +00002407 if (value == NULL) {
2408 PyErr_SetString(PyExc_TypeError,
2409 "can't delete __class__ attribute");
2410 return -1;
2411 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002412 if (!PyType_Check(value)) {
2413 PyErr_Format(PyExc_TypeError,
2414 "__class__ must be set to new-style class, not '%s' object",
2415 value->ob_type->tp_name);
2416 return -1;
2417 }
2418 new = (PyTypeObject *)value;
Guido van Rossum40af8892002-08-10 05:42:07 +00002419 if (!(new->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
2420 !(old->tp_flags & Py_TPFLAGS_HEAPTYPE))
2421 {
2422 PyErr_Format(PyExc_TypeError,
2423 "__class__ assignment: only for heap types");
2424 return -1;
2425 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002426 if (compatible_for_assignment(new, old, "__class__")) {
2427 Py_INCREF(new);
2428 self->ob_type = new;
2429 Py_DECREF(old);
2430 return 0;
2431 }
2432 else {
Guido van Rossum9ee4b942002-05-24 18:47:47 +00002433 return -1;
2434 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002435}
2436
2437static PyGetSetDef object_getsets[] = {
2438 {"__class__", object_get_class, object_set_class,
Neal Norwitz858e34f2002-08-13 17:18:45 +00002439 PyDoc_STR("the object's class")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002440 {0}
2441};
2442
Guido van Rossumc53f0092003-02-18 22:05:12 +00002443
Guido van Rossum036f9992003-02-21 22:02:54 +00002444/* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
2445 We fall back to helpers in copy_reg for:
2446 - pickle protocols < 2
2447 - calculating the list of slot names (done only once per class)
2448 - the __newobj__ function (which is used as a token but never called)
2449*/
2450
2451static PyObject *
2452import_copy_reg(void)
2453{
2454 static PyObject *copy_reg_str;
Guido van Rossum3926a632001-09-25 16:25:58 +00002455
2456 if (!copy_reg_str) {
2457 copy_reg_str = PyString_InternFromString("copy_reg");
2458 if (copy_reg_str == NULL)
2459 return NULL;
2460 }
Guido van Rossum036f9992003-02-21 22:02:54 +00002461
2462 return PyImport_Import(copy_reg_str);
2463}
2464
2465static PyObject *
2466slotnames(PyObject *cls)
2467{
2468 PyObject *clsdict;
2469 PyObject *copy_reg;
2470 PyObject *slotnames;
2471
2472 if (!PyType_Check(cls)) {
2473 Py_INCREF(Py_None);
2474 return Py_None;
2475 }
2476
2477 clsdict = ((PyTypeObject *)cls)->tp_dict;
2478 slotnames = PyDict_GetItemString(clsdict, "__slotnames__");
2479 if (slotnames != NULL) {
2480 Py_INCREF(slotnames);
2481 return slotnames;
2482 }
2483
2484 copy_reg = import_copy_reg();
2485 if (copy_reg == NULL)
2486 return NULL;
2487
2488 slotnames = PyObject_CallMethod(copy_reg, "_slotnames", "O", cls);
2489 Py_DECREF(copy_reg);
2490 if (slotnames != NULL &&
2491 slotnames != Py_None &&
2492 !PyList_Check(slotnames))
2493 {
2494 PyErr_SetString(PyExc_TypeError,
2495 "copy_reg._slotnames didn't return a list or None");
2496 Py_DECREF(slotnames);
2497 slotnames = NULL;
2498 }
2499
2500 return slotnames;
2501}
2502
2503static PyObject *
2504reduce_2(PyObject *obj)
2505{
2506 PyObject *cls, *getnewargs;
2507 PyObject *args = NULL, *args2 = NULL;
2508 PyObject *getstate = NULL, *state = NULL, *names = NULL;
2509 PyObject *slots = NULL, *listitems = NULL, *dictitems = NULL;
2510 PyObject *copy_reg = NULL, *newobj = NULL, *res = NULL;
2511 int i, n;
2512
2513 cls = PyObject_GetAttrString(obj, "__class__");
2514 if (cls == NULL)
2515 return NULL;
2516
2517 getnewargs = PyObject_GetAttrString(obj, "__getnewargs__");
2518 if (getnewargs != NULL) {
2519 args = PyObject_CallObject(getnewargs, NULL);
2520 Py_DECREF(getnewargs);
2521 if (args != NULL && !PyTuple_Check(args)) {
2522 PyErr_SetString(PyExc_TypeError,
2523 "__getnewargs__ should return a tuple");
2524 goto end;
2525 }
2526 }
2527 else {
2528 PyErr_Clear();
2529 args = PyTuple_New(0);
2530 }
2531 if (args == NULL)
2532 goto end;
2533
2534 getstate = PyObject_GetAttrString(obj, "__getstate__");
2535 if (getstate != NULL) {
2536 state = PyObject_CallObject(getstate, NULL);
2537 Py_DECREF(getstate);
2538 }
2539 else {
2540 state = PyObject_GetAttrString(obj, "__dict__");
2541 if (state == NULL) {
2542 PyErr_Clear();
2543 state = Py_None;
2544 Py_INCREF(state);
2545 }
2546 names = slotnames(cls);
2547 if (names == NULL)
2548 goto end;
2549 if (names != Py_None) {
2550 assert(PyList_Check(names));
2551 slots = PyDict_New();
2552 if (slots == NULL)
2553 goto end;
2554 n = 0;
2555 /* Can't pre-compute the list size; the list
2556 is stored on the class so accessible to other
2557 threads, which may be run by DECREF */
2558 for (i = 0; i < PyList_GET_SIZE(names); i++) {
2559 PyObject *name, *value;
2560 name = PyList_GET_ITEM(names, i);
2561 value = PyObject_GetAttr(obj, name);
2562 if (value == NULL)
2563 PyErr_Clear();
2564 else {
2565 int err = PyDict_SetItem(slots, name,
2566 value);
2567 Py_DECREF(value);
2568 if (err)
2569 goto end;
2570 n++;
2571 }
2572 }
2573 if (n) {
2574 state = Py_BuildValue("(NO)", state, slots);
2575 if (state == NULL)
2576 goto end;
2577 }
2578 }
2579 }
2580
2581 if (!PyList_Check(obj)) {
2582 listitems = Py_None;
2583 Py_INCREF(listitems);
2584 }
2585 else {
2586 listitems = PyObject_GetIter(obj);
2587 if (listitems == NULL)
2588 goto end;
2589 }
2590
2591 if (!PyDict_Check(obj)) {
2592 dictitems = Py_None;
2593 Py_INCREF(dictitems);
2594 }
2595 else {
2596 dictitems = PyObject_CallMethod(obj, "iteritems", "");
2597 if (dictitems == NULL)
2598 goto end;
2599 }
2600
2601 copy_reg = import_copy_reg();
2602 if (copy_reg == NULL)
2603 goto end;
2604 newobj = PyObject_GetAttrString(copy_reg, "__newobj__");
2605 if (newobj == NULL)
2606 goto end;
2607
2608 n = PyTuple_GET_SIZE(args);
2609 args2 = PyTuple_New(n+1);
2610 if (args2 == NULL)
2611 goto end;
2612 PyTuple_SET_ITEM(args2, 0, cls);
2613 cls = NULL;
2614 for (i = 0; i < n; i++) {
2615 PyObject *v = PyTuple_GET_ITEM(args, i);
2616 Py_INCREF(v);
2617 PyTuple_SET_ITEM(args2, i+1, v);
2618 }
2619
2620 res = Py_BuildValue("(OOOOO)",
2621 newobj, args2, state, listitems, dictitems);
2622
2623 end:
2624 Py_XDECREF(cls);
2625 Py_XDECREF(args);
2626 Py_XDECREF(args2);
2627 Py_XDECREF(state);
2628 Py_XDECREF(names);
2629 Py_XDECREF(listitems);
2630 Py_XDECREF(dictitems);
2631 Py_XDECREF(copy_reg);
2632 Py_XDECREF(newobj);
2633 return res;
2634}
2635
2636static PyObject *
2637object_reduce_ex(PyObject *self, PyObject *args)
2638{
2639 /* Call copy_reg._reduce_ex(self, proto) */
2640 PyObject *reduce, *copy_reg, *res;
2641 int proto = 0;
2642
2643 if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
2644 return NULL;
2645
2646 reduce = PyObject_GetAttrString(self, "__reduce__");
2647 if (reduce == NULL)
2648 PyErr_Clear();
2649 else {
2650 PyObject *cls, *clsreduce, *objreduce;
2651 int override;
2652 cls = PyObject_GetAttrString(self, "__class__");
2653 if (cls == NULL) {
2654 Py_DECREF(reduce);
2655 return NULL;
2656 }
2657 clsreduce = PyObject_GetAttrString(cls, "__reduce__");
2658 Py_DECREF(cls);
2659 if (clsreduce == NULL) {
2660 Py_DECREF(reduce);
2661 return NULL;
2662 }
2663 objreduce = PyDict_GetItemString(PyBaseObject_Type.tp_dict,
2664 "__reduce__");
2665 override = (clsreduce != objreduce);
2666 Py_DECREF(clsreduce);
2667 if (override) {
2668 res = PyObject_CallObject(reduce, NULL);
2669 Py_DECREF(reduce);
2670 return res;
2671 }
2672 else
2673 Py_DECREF(reduce);
2674 }
2675
2676 if (proto >= 2)
2677 return reduce_2(self);
2678
2679 copy_reg = import_copy_reg();
Guido van Rossum3926a632001-09-25 16:25:58 +00002680 if (!copy_reg)
2681 return NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00002682
Guido van Rossumc53f0092003-02-18 22:05:12 +00002683 res = PyEval_CallMethod(copy_reg, "_reduce_ex", "(Oi)", self, proto);
Guido van Rossum3926a632001-09-25 16:25:58 +00002684 Py_DECREF(copy_reg);
Guido van Rossum036f9992003-02-21 22:02:54 +00002685
Guido van Rossum3926a632001-09-25 16:25:58 +00002686 return res;
2687}
2688
2689static PyMethodDef object_methods[] = {
Guido van Rossumc53f0092003-02-18 22:05:12 +00002690 {"__reduce_ex__", object_reduce_ex, METH_VARARGS,
2691 PyDoc_STR("helper for pickle")},
2692 {"__reduce__", object_reduce_ex, METH_VARARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002693 PyDoc_STR("helper for pickle")},
Guido van Rossum3926a632001-09-25 16:25:58 +00002694 {0}
2695};
2696
Guido van Rossum036f9992003-02-21 22:02:54 +00002697
Tim Peters6d6c1a32001-08-02 04:15:00 +00002698PyTypeObject PyBaseObject_Type = {
2699 PyObject_HEAD_INIT(&PyType_Type)
2700 0, /* ob_size */
2701 "object", /* tp_name */
2702 sizeof(PyObject), /* tp_basicsize */
2703 0, /* tp_itemsize */
2704 (destructor)object_dealloc, /* tp_dealloc */
2705 0, /* tp_print */
2706 0, /* tp_getattr */
2707 0, /* tp_setattr */
2708 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002709 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002710 0, /* tp_as_number */
2711 0, /* tp_as_sequence */
2712 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002713 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002714 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002715 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002716 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002717 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002718 0, /* tp_as_buffer */
2719 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002720 PyDoc_STR("The most base type"), /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002721 0, /* tp_traverse */
2722 0, /* tp_clear */
2723 0, /* tp_richcompare */
2724 0, /* tp_weaklistoffset */
2725 0, /* tp_iter */
2726 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00002727 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002728 0, /* tp_members */
2729 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002730 0, /* tp_base */
2731 0, /* tp_dict */
2732 0, /* tp_descr_get */
2733 0, /* tp_descr_set */
2734 0, /* tp_dictoffset */
2735 object_init, /* tp_init */
2736 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossum298e4212003-02-13 16:30:16 +00002737 object_new, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002738 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002739};
2740
2741
2742/* Initialize the __dict__ in a type object */
2743
2744static int
2745add_methods(PyTypeObject *type, PyMethodDef *meth)
2746{
Guido van Rossum687ae002001-10-15 22:03:32 +00002747 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002748
2749 for (; meth->ml_name != NULL; meth++) {
2750 PyObject *descr;
2751 if (PyDict_GetItemString(dict, meth->ml_name))
2752 continue;
Fred Drake7bf97152002-03-28 05:33:33 +00002753 if (meth->ml_flags & METH_CLASS) {
2754 if (meth->ml_flags & METH_STATIC) {
2755 PyErr_SetString(PyExc_ValueError,
2756 "method cannot be both class and static");
2757 return -1;
2758 }
Tim Petersbca1cbc2002-12-09 22:56:13 +00002759 descr = PyDescr_NewClassMethod(type, meth);
Fred Drake7bf97152002-03-28 05:33:33 +00002760 }
2761 else if (meth->ml_flags & METH_STATIC) {
Guido van Rossum9af48ff2003-02-11 17:12:46 +00002762 PyObject *cfunc = PyCFunction_New(meth, NULL);
2763 if (cfunc == NULL)
2764 return -1;
2765 descr = PyStaticMethod_New(cfunc);
2766 Py_DECREF(cfunc);
Fred Drake7bf97152002-03-28 05:33:33 +00002767 }
2768 else {
2769 descr = PyDescr_NewMethod(type, meth);
2770 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002771 if (descr == NULL)
2772 return -1;
Fred Drake7bf97152002-03-28 05:33:33 +00002773 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002774 return -1;
2775 Py_DECREF(descr);
2776 }
2777 return 0;
2778}
2779
2780static int
Guido van Rossum6f799372001-09-20 20:46:19 +00002781add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002782{
Guido van Rossum687ae002001-10-15 22:03:32 +00002783 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002784
2785 for (; memb->name != NULL; memb++) {
2786 PyObject *descr;
2787 if (PyDict_GetItemString(dict, memb->name))
2788 continue;
2789 descr = PyDescr_NewMember(type, memb);
2790 if (descr == NULL)
2791 return -1;
2792 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
2793 return -1;
2794 Py_DECREF(descr);
2795 }
2796 return 0;
2797}
2798
2799static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00002800add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002801{
Guido van Rossum687ae002001-10-15 22:03:32 +00002802 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002803
2804 for (; gsp->name != NULL; gsp++) {
2805 PyObject *descr;
2806 if (PyDict_GetItemString(dict, gsp->name))
2807 continue;
2808 descr = PyDescr_NewGetSet(type, gsp);
2809
2810 if (descr == NULL)
2811 return -1;
2812 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
2813 return -1;
2814 Py_DECREF(descr);
2815 }
2816 return 0;
2817}
2818
Guido van Rossum13d52f02001-08-10 21:24:08 +00002819static void
2820inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002821{
2822 int oldsize, newsize;
2823
Guido van Rossum13d52f02001-08-10 21:24:08 +00002824 /* Special flag magic */
2825 if (!type->tp_as_buffer && base->tp_as_buffer) {
2826 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
2827 type->tp_flags |=
2828 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
2829 }
2830 if (!type->tp_as_sequence && base->tp_as_sequence) {
2831 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
2832 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
2833 }
2834 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
2835 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
2836 if ((!type->tp_as_number && base->tp_as_number) ||
2837 (!type->tp_as_sequence && base->tp_as_sequence)) {
2838 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
2839 if (!type->tp_as_number && !type->tp_as_sequence) {
2840 type->tp_flags |= base->tp_flags &
2841 Py_TPFLAGS_HAVE_INPLACEOPS;
2842 }
2843 }
2844 /* Wow */
2845 }
2846 if (!type->tp_as_number && base->tp_as_number) {
2847 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
2848 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
2849 }
2850
2851 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00002852 oldsize = base->tp_basicsize;
2853 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
2854 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
2855 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00002856 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
2857 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00002858 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00002859 if (type->tp_traverse == NULL)
2860 type->tp_traverse = base->tp_traverse;
2861 if (type->tp_clear == NULL)
2862 type->tp_clear = base->tp_clear;
2863 }
2864 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
Guido van Rossumf884b742001-12-17 17:14:22 +00002865 /* The condition below could use some explanation.
2866 It appears that tp_new is not inherited for static types
2867 whose base class is 'object'; this seems to be a precaution
2868 so that old extension types don't suddenly become
2869 callable (object.__new__ wouldn't insure the invariants
2870 that the extension type's own factory function ensures).
2871 Heap types, of course, are under our control, so they do
2872 inherit tp_new; static extension types that specify some
2873 other built-in type as the default are considered
2874 new-style-aware so they also inherit object.__new__. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002875 if (base != &PyBaseObject_Type ||
2876 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2877 if (type->tp_new == NULL)
2878 type->tp_new = base->tp_new;
2879 }
2880 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00002881 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00002882
2883 /* Copy other non-function slots */
2884
2885#undef COPYVAL
2886#define COPYVAL(SLOT) \
2887 if (type->SLOT == 0) type->SLOT = base->SLOT
2888
2889 COPYVAL(tp_itemsize);
2890 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
2891 COPYVAL(tp_weaklistoffset);
2892 }
2893 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2894 COPYVAL(tp_dictoffset);
2895 }
Guido van Rossum13d52f02001-08-10 21:24:08 +00002896}
2897
2898static void
2899inherit_slots(PyTypeObject *type, PyTypeObject *base)
2900{
2901 PyTypeObject *basebase;
2902
2903#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00002904#undef COPYSLOT
2905#undef COPYNUM
2906#undef COPYSEQ
2907#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00002908#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00002909
2910#define SLOTDEFINED(SLOT) \
2911 (base->SLOT != 0 && \
2912 (basebase == NULL || base->SLOT != basebase->SLOT))
2913
Tim Peters6d6c1a32001-08-02 04:15:00 +00002914#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00002915 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00002916
2917#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
2918#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
2919#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00002920#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002921
Guido van Rossum13d52f02001-08-10 21:24:08 +00002922 /* This won't inherit indirect slots (from tp_as_number etc.)
2923 if type doesn't provide the space. */
2924
2925 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
2926 basebase = base->tp_base;
2927 if (basebase->tp_as_number == NULL)
2928 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002929 COPYNUM(nb_add);
2930 COPYNUM(nb_subtract);
2931 COPYNUM(nb_multiply);
2932 COPYNUM(nb_divide);
2933 COPYNUM(nb_remainder);
2934 COPYNUM(nb_divmod);
2935 COPYNUM(nb_power);
2936 COPYNUM(nb_negative);
2937 COPYNUM(nb_positive);
2938 COPYNUM(nb_absolute);
2939 COPYNUM(nb_nonzero);
2940 COPYNUM(nb_invert);
2941 COPYNUM(nb_lshift);
2942 COPYNUM(nb_rshift);
2943 COPYNUM(nb_and);
2944 COPYNUM(nb_xor);
2945 COPYNUM(nb_or);
2946 COPYNUM(nb_coerce);
2947 COPYNUM(nb_int);
2948 COPYNUM(nb_long);
2949 COPYNUM(nb_float);
2950 COPYNUM(nb_oct);
2951 COPYNUM(nb_hex);
2952 COPYNUM(nb_inplace_add);
2953 COPYNUM(nb_inplace_subtract);
2954 COPYNUM(nb_inplace_multiply);
2955 COPYNUM(nb_inplace_divide);
2956 COPYNUM(nb_inplace_remainder);
2957 COPYNUM(nb_inplace_power);
2958 COPYNUM(nb_inplace_lshift);
2959 COPYNUM(nb_inplace_rshift);
2960 COPYNUM(nb_inplace_and);
2961 COPYNUM(nb_inplace_xor);
2962 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00002963 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
2964 COPYNUM(nb_true_divide);
2965 COPYNUM(nb_floor_divide);
2966 COPYNUM(nb_inplace_true_divide);
2967 COPYNUM(nb_inplace_floor_divide);
2968 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002969 }
2970
Guido van Rossum13d52f02001-08-10 21:24:08 +00002971 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
2972 basebase = base->tp_base;
2973 if (basebase->tp_as_sequence == NULL)
2974 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002975 COPYSEQ(sq_length);
2976 COPYSEQ(sq_concat);
2977 COPYSEQ(sq_repeat);
2978 COPYSEQ(sq_item);
2979 COPYSEQ(sq_slice);
2980 COPYSEQ(sq_ass_item);
2981 COPYSEQ(sq_ass_slice);
2982 COPYSEQ(sq_contains);
2983 COPYSEQ(sq_inplace_concat);
2984 COPYSEQ(sq_inplace_repeat);
2985 }
2986
Guido van Rossum13d52f02001-08-10 21:24:08 +00002987 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
2988 basebase = base->tp_base;
2989 if (basebase->tp_as_mapping == NULL)
2990 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002991 COPYMAP(mp_length);
2992 COPYMAP(mp_subscript);
2993 COPYMAP(mp_ass_subscript);
2994 }
2995
Tim Petersfc57ccb2001-10-12 02:38:24 +00002996 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
2997 basebase = base->tp_base;
2998 if (basebase->tp_as_buffer == NULL)
2999 basebase = NULL;
3000 COPYBUF(bf_getreadbuffer);
3001 COPYBUF(bf_getwritebuffer);
3002 COPYBUF(bf_getsegcount);
3003 COPYBUF(bf_getcharbuffer);
3004 }
3005
Guido van Rossum13d52f02001-08-10 21:24:08 +00003006 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003007
Tim Peters6d6c1a32001-08-02 04:15:00 +00003008 COPYSLOT(tp_dealloc);
3009 COPYSLOT(tp_print);
3010 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
3011 type->tp_getattr = base->tp_getattr;
3012 type->tp_getattro = base->tp_getattro;
3013 }
3014 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
3015 type->tp_setattr = base->tp_setattr;
3016 type->tp_setattro = base->tp_setattro;
3017 }
3018 /* tp_compare see tp_richcompare */
3019 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003020 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003021 COPYSLOT(tp_call);
3022 COPYSLOT(tp_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003023 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003024 if (type->tp_compare == NULL &&
3025 type->tp_richcompare == NULL &&
3026 type->tp_hash == NULL)
3027 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003028 type->tp_compare = base->tp_compare;
3029 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003030 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003031 }
3032 }
3033 else {
3034 COPYSLOT(tp_compare);
3035 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003036 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
3037 COPYSLOT(tp_iter);
3038 COPYSLOT(tp_iternext);
3039 }
3040 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
3041 COPYSLOT(tp_descr_get);
3042 COPYSLOT(tp_descr_set);
3043 COPYSLOT(tp_dictoffset);
3044 COPYSLOT(tp_init);
3045 COPYSLOT(tp_alloc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003046 COPYSLOT(tp_free);
Guido van Rossumcc8fe042002-04-05 17:10:16 +00003047 COPYSLOT(tp_is_gc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003048 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003049}
3050
Jeremy Hylton938ace62002-07-17 16:30:39 +00003051static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00003052
Tim Peters6d6c1a32001-08-02 04:15:00 +00003053int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00003054PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003055{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003056 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003057 PyTypeObject *base;
3058 int i, n;
3059
Guido van Rossumcab05802002-06-10 15:29:03 +00003060 if (type->tp_flags & Py_TPFLAGS_READY) {
3061 assert(type->tp_dict != NULL);
Guido van Rossumd614f972001-08-10 17:39:49 +00003062 return 0;
Guido van Rossumcab05802002-06-10 15:29:03 +00003063 }
Guido van Rossumd614f972001-08-10 17:39:49 +00003064 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00003065
3066 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003067
3068 /* Initialize tp_base (defaults to BaseObject unless that's us) */
3069 base = type->tp_base;
3070 if (base == NULL && type != &PyBaseObject_Type)
3071 base = type->tp_base = &PyBaseObject_Type;
3072
Guido van Rossum323a9cf2002-08-14 17:26:30 +00003073 /* Initialize the base class */
3074 if (base && base->tp_dict == NULL) {
3075 if (PyType_Ready(base) < 0)
3076 goto error;
3077 }
3078
Guido van Rossum0986d822002-04-08 01:38:42 +00003079 /* Initialize ob_type if NULL. This means extensions that want to be
3080 compilable separately on Windows can call PyType_Ready() instead of
3081 initializing the ob_type field of their type objects. */
3082 if (type->ob_type == NULL)
3083 type->ob_type = base->ob_type;
3084
Tim Peters6d6c1a32001-08-02 04:15:00 +00003085 /* Initialize tp_bases */
3086 bases = type->tp_bases;
3087 if (bases == NULL) {
3088 if (base == NULL)
3089 bases = PyTuple_New(0);
3090 else
3091 bases = Py_BuildValue("(O)", base);
3092 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003093 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003094 type->tp_bases = bases;
3095 }
3096
Guido van Rossum687ae002001-10-15 22:03:32 +00003097 /* Initialize tp_dict */
3098 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003099 if (dict == NULL) {
3100 dict = PyDict_New();
3101 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003102 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00003103 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003104 }
3105
Guido van Rossum687ae002001-10-15 22:03:32 +00003106 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003107 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003108 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003109 if (type->tp_methods != NULL) {
3110 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003111 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003112 }
3113 if (type->tp_members != NULL) {
3114 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003115 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003116 }
3117 if (type->tp_getset != NULL) {
3118 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003119 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003120 }
3121
Tim Peters6d6c1a32001-08-02 04:15:00 +00003122 /* Calculate method resolution order */
3123 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00003124 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003125 }
3126
Guido van Rossum13d52f02001-08-10 21:24:08 +00003127 /* Inherit special flags from dominant base */
3128 if (type->tp_base != NULL)
3129 inherit_special(type, type->tp_base);
3130
Tim Peters6d6c1a32001-08-02 04:15:00 +00003131 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003132 bases = type->tp_mro;
3133 assert(bases != NULL);
3134 assert(PyTuple_Check(bases));
3135 n = PyTuple_GET_SIZE(bases);
3136 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003137 PyObject *b = PyTuple_GET_ITEM(bases, i);
3138 if (PyType_Check(b))
3139 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003140 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003141
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003142 /* if the type dictionary doesn't contain a __doc__, set it from
3143 the tp_doc slot.
3144 */
3145 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
3146 if (type->tp_doc != NULL) {
3147 PyObject *doc = PyString_FromString(type->tp_doc);
3148 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
3149 Py_DECREF(doc);
3150 } else {
Guido van Rossumd4641072002-04-03 02:13:37 +00003151 PyDict_SetItemString(type->tp_dict,
3152 "__doc__", Py_None);
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003153 }
3154 }
3155
Guido van Rossum13d52f02001-08-10 21:24:08 +00003156 /* Some more special stuff */
3157 base = type->tp_base;
3158 if (base != NULL) {
3159 if (type->tp_as_number == NULL)
3160 type->tp_as_number = base->tp_as_number;
3161 if (type->tp_as_sequence == NULL)
3162 type->tp_as_sequence = base->tp_as_sequence;
3163 if (type->tp_as_mapping == NULL)
3164 type->tp_as_mapping = base->tp_as_mapping;
Guido van Rossumeea47182003-02-11 20:39:59 +00003165 if (type->tp_as_buffer == NULL)
3166 type->tp_as_buffer = base->tp_as_buffer;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003167 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003168
Guido van Rossum1c450732001-10-08 15:18:27 +00003169 /* Link into each base class's list of subclasses */
3170 bases = type->tp_bases;
3171 n = PyTuple_GET_SIZE(bases);
3172 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003173 PyObject *b = PyTuple_GET_ITEM(bases, i);
3174 if (PyType_Check(b) &&
3175 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00003176 goto error;
3177 }
3178
Guido van Rossum13d52f02001-08-10 21:24:08 +00003179 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00003180 assert(type->tp_dict != NULL);
3181 type->tp_flags =
3182 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003183 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00003184
3185 error:
3186 type->tp_flags &= ~Py_TPFLAGS_READYING;
3187 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003188}
3189
Guido van Rossum1c450732001-10-08 15:18:27 +00003190static int
3191add_subclass(PyTypeObject *base, PyTypeObject *type)
3192{
3193 int i;
3194 PyObject *list, *ref, *new;
3195
3196 list = base->tp_subclasses;
3197 if (list == NULL) {
3198 base->tp_subclasses = list = PyList_New(0);
3199 if (list == NULL)
3200 return -1;
3201 }
3202 assert(PyList_Check(list));
3203 new = PyWeakref_NewRef((PyObject *)type, NULL);
3204 i = PyList_GET_SIZE(list);
3205 while (--i >= 0) {
3206 ref = PyList_GET_ITEM(list, i);
3207 assert(PyWeakref_CheckRef(ref));
Guido van Rossum3930bc32002-10-18 13:51:49 +00003208 if (PyWeakref_GET_OBJECT(ref) == Py_None)
3209 return PyList_SetItem(list, i, new);
Guido van Rossum1c450732001-10-08 15:18:27 +00003210 }
3211 i = PyList_Append(list, new);
3212 Py_DECREF(new);
3213 return i;
3214}
3215
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003216static void
3217remove_subclass(PyTypeObject *base, PyTypeObject *type)
3218{
3219 int i;
3220 PyObject *list, *ref;
3221
3222 list = base->tp_subclasses;
3223 if (list == NULL) {
3224 return;
3225 }
3226 assert(PyList_Check(list));
3227 i = PyList_GET_SIZE(list);
3228 while (--i >= 0) {
3229 ref = PyList_GET_ITEM(list, i);
3230 assert(PyWeakref_CheckRef(ref));
3231 if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
3232 /* this can't fail, right? */
3233 PySequence_DelItem(list, i);
3234 return;
3235 }
3236 }
3237}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003238
3239/* Generic wrappers for overloadable 'operators' such as __getitem__ */
3240
3241/* There's a wrapper *function* for each distinct function typedef used
3242 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
3243 wrapper *table* for each distinct operation (e.g. __len__, __add__).
3244 Most tables have only one entry; the tables for binary operators have two
3245 entries, one regular and one with reversed arguments. */
3246
3247static PyObject *
3248wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
3249{
3250 inquiry func = (inquiry)wrapped;
3251 int res;
3252
3253 if (!PyArg_ParseTuple(args, ""))
3254 return NULL;
3255 res = (*func)(self);
3256 if (res == -1 && PyErr_Occurred())
3257 return NULL;
3258 return PyInt_FromLong((long)res);
3259}
3260
Tim Peters6d6c1a32001-08-02 04:15:00 +00003261static PyObject *
3262wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
3263{
3264 binaryfunc func = (binaryfunc)wrapped;
3265 PyObject *other;
3266
3267 if (!PyArg_ParseTuple(args, "O", &other))
3268 return NULL;
3269 return (*func)(self, other);
3270}
3271
3272static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003273wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
3274{
3275 binaryfunc func = (binaryfunc)wrapped;
3276 PyObject *other;
3277
3278 if (!PyArg_ParseTuple(args, "O", &other))
3279 return NULL;
3280 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003281 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003282 Py_INCREF(Py_NotImplemented);
3283 return Py_NotImplemented;
3284 }
3285 return (*func)(self, other);
3286}
3287
3288static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003289wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3290{
3291 binaryfunc func = (binaryfunc)wrapped;
3292 PyObject *other;
3293
3294 if (!PyArg_ParseTuple(args, "O", &other))
3295 return NULL;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003296 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003297 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003298 Py_INCREF(Py_NotImplemented);
3299 return Py_NotImplemented;
3300 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003301 return (*func)(other, self);
3302}
3303
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003304static PyObject *
3305wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
3306{
3307 coercion func = (coercion)wrapped;
3308 PyObject *other, *res;
3309 int ok;
3310
3311 if (!PyArg_ParseTuple(args, "O", &other))
3312 return NULL;
3313 ok = func(&self, &other);
3314 if (ok < 0)
3315 return NULL;
3316 if (ok > 0) {
3317 Py_INCREF(Py_NotImplemented);
3318 return Py_NotImplemented;
3319 }
3320 res = PyTuple_New(2);
3321 if (res == NULL) {
3322 Py_DECREF(self);
3323 Py_DECREF(other);
3324 return NULL;
3325 }
3326 PyTuple_SET_ITEM(res, 0, self);
3327 PyTuple_SET_ITEM(res, 1, other);
3328 return res;
3329}
3330
Tim Peters6d6c1a32001-08-02 04:15:00 +00003331static PyObject *
3332wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
3333{
3334 ternaryfunc func = (ternaryfunc)wrapped;
3335 PyObject *other;
3336 PyObject *third = Py_None;
3337
3338 /* Note: This wrapper only works for __pow__() */
3339
3340 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
3341 return NULL;
3342 return (*func)(self, other, third);
3343}
3344
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00003345static PyObject *
3346wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3347{
3348 ternaryfunc func = (ternaryfunc)wrapped;
3349 PyObject *other;
3350 PyObject *third = Py_None;
3351
3352 /* Note: This wrapper only works for __pow__() */
3353
3354 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
3355 return NULL;
3356 return (*func)(other, self, third);
3357}
3358
Tim Peters6d6c1a32001-08-02 04:15:00 +00003359static PyObject *
3360wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
3361{
3362 unaryfunc func = (unaryfunc)wrapped;
3363
3364 if (!PyArg_ParseTuple(args, ""))
3365 return NULL;
3366 return (*func)(self);
3367}
3368
Tim Peters6d6c1a32001-08-02 04:15:00 +00003369static PyObject *
3370wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
3371{
3372 intargfunc func = (intargfunc)wrapped;
3373 int i;
3374
3375 if (!PyArg_ParseTuple(args, "i", &i))
3376 return NULL;
3377 return (*func)(self, i);
3378}
3379
Guido van Rossum5d815f32001-08-17 21:57:47 +00003380static int
3381getindex(PyObject *self, PyObject *arg)
3382{
3383 int i;
3384
3385 i = PyInt_AsLong(arg);
3386 if (i == -1 && PyErr_Occurred())
3387 return -1;
3388 if (i < 0) {
3389 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
3390 if (sq && sq->sq_length) {
3391 int n = (*sq->sq_length)(self);
3392 if (n < 0)
3393 return -1;
3394 i += n;
3395 }
3396 }
3397 return i;
3398}
3399
3400static PyObject *
3401wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
3402{
3403 intargfunc func = (intargfunc)wrapped;
3404 PyObject *arg;
3405 int i;
3406
Guido van Rossumf4593e02001-10-03 12:09:30 +00003407 if (PyTuple_GET_SIZE(args) == 1) {
3408 arg = PyTuple_GET_ITEM(args, 0);
3409 i = getindex(self, arg);
3410 if (i == -1 && PyErr_Occurred())
3411 return NULL;
3412 return (*func)(self, i);
3413 }
3414 PyArg_ParseTuple(args, "O", &arg);
3415 assert(PyErr_Occurred());
3416 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003417}
3418
Tim Peters6d6c1a32001-08-02 04:15:00 +00003419static PyObject *
3420wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
3421{
3422 intintargfunc func = (intintargfunc)wrapped;
3423 int i, j;
3424
3425 if (!PyArg_ParseTuple(args, "ii", &i, &j))
3426 return NULL;
3427 return (*func)(self, i, j);
3428}
3429
Tim Peters6d6c1a32001-08-02 04:15:00 +00003430static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003431wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003432{
3433 intobjargproc func = (intobjargproc)wrapped;
3434 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003435 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003436
Guido van Rossum5d815f32001-08-17 21:57:47 +00003437 if (!PyArg_ParseTuple(args, "OO", &arg, &value))
3438 return NULL;
3439 i = getindex(self, arg);
3440 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00003441 return NULL;
3442 res = (*func)(self, i, value);
3443 if (res == -1 && PyErr_Occurred())
3444 return NULL;
3445 Py_INCREF(Py_None);
3446 return Py_None;
3447}
3448
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003449static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003450wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003451{
3452 intobjargproc func = (intobjargproc)wrapped;
3453 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003454 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003455
Guido van Rossum5d815f32001-08-17 21:57:47 +00003456 if (!PyArg_ParseTuple(args, "O", &arg))
3457 return NULL;
3458 i = getindex(self, arg);
3459 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003460 return NULL;
3461 res = (*func)(self, i, NULL);
3462 if (res == -1 && PyErr_Occurred())
3463 return NULL;
3464 Py_INCREF(Py_None);
3465 return Py_None;
3466}
3467
Tim Peters6d6c1a32001-08-02 04:15:00 +00003468static PyObject *
3469wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
3470{
3471 intintobjargproc func = (intintobjargproc)wrapped;
3472 int i, j, res;
3473 PyObject *value;
3474
3475 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
3476 return NULL;
3477 res = (*func)(self, i, j, value);
3478 if (res == -1 && PyErr_Occurred())
3479 return NULL;
3480 Py_INCREF(Py_None);
3481 return Py_None;
3482}
3483
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003484static PyObject *
3485wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
3486{
3487 intintobjargproc func = (intintobjargproc)wrapped;
3488 int i, j, res;
3489
3490 if (!PyArg_ParseTuple(args, "ii", &i, &j))
3491 return NULL;
3492 res = (*func)(self, i, j, NULL);
3493 if (res == -1 && PyErr_Occurred())
3494 return NULL;
3495 Py_INCREF(Py_None);
3496 return Py_None;
3497}
3498
Tim Peters6d6c1a32001-08-02 04:15:00 +00003499/* XXX objobjproc is a misnomer; should be objargpred */
3500static PyObject *
3501wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
3502{
3503 objobjproc func = (objobjproc)wrapped;
3504 int res;
3505 PyObject *value;
3506
3507 if (!PyArg_ParseTuple(args, "O", &value))
3508 return NULL;
3509 res = (*func)(self, value);
3510 if (res == -1 && PyErr_Occurred())
3511 return NULL;
3512 return PyInt_FromLong((long)res);
3513}
3514
Tim Peters6d6c1a32001-08-02 04:15:00 +00003515static PyObject *
3516wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
3517{
3518 objobjargproc func = (objobjargproc)wrapped;
3519 int res;
3520 PyObject *key, *value;
3521
3522 if (!PyArg_ParseTuple(args, "OO", &key, &value))
3523 return NULL;
3524 res = (*func)(self, key, value);
3525 if (res == -1 && PyErr_Occurred())
3526 return NULL;
3527 Py_INCREF(Py_None);
3528 return Py_None;
3529}
3530
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003531static PyObject *
3532wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
3533{
3534 objobjargproc func = (objobjargproc)wrapped;
3535 int res;
3536 PyObject *key;
3537
3538 if (!PyArg_ParseTuple(args, "O", &key))
3539 return NULL;
3540 res = (*func)(self, key, NULL);
3541 if (res == -1 && PyErr_Occurred())
3542 return NULL;
3543 Py_INCREF(Py_None);
3544 return Py_None;
3545}
3546
Tim Peters6d6c1a32001-08-02 04:15:00 +00003547static PyObject *
3548wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
3549{
3550 cmpfunc func = (cmpfunc)wrapped;
3551 int res;
3552 PyObject *other;
3553
3554 if (!PyArg_ParseTuple(args, "O", &other))
3555 return NULL;
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00003556 if (other->ob_type->tp_compare != func &&
3557 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00003558 PyErr_Format(
3559 PyExc_TypeError,
3560 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
3561 self->ob_type->tp_name,
3562 self->ob_type->tp_name,
3563 other->ob_type->tp_name);
3564 return NULL;
3565 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003566 res = (*func)(self, other);
3567 if (PyErr_Occurred())
3568 return NULL;
3569 return PyInt_FromLong((long)res);
3570}
3571
Tim Peters6d6c1a32001-08-02 04:15:00 +00003572static PyObject *
3573wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
3574{
3575 setattrofunc func = (setattrofunc)wrapped;
3576 int res;
3577 PyObject *name, *value;
3578
3579 if (!PyArg_ParseTuple(args, "OO", &name, &value))
3580 return NULL;
3581 res = (*func)(self, name, value);
3582 if (res < 0)
3583 return NULL;
3584 Py_INCREF(Py_None);
3585 return Py_None;
3586}
3587
3588static PyObject *
3589wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
3590{
3591 setattrofunc func = (setattrofunc)wrapped;
3592 int res;
3593 PyObject *name;
3594
3595 if (!PyArg_ParseTuple(args, "O", &name))
3596 return NULL;
3597 res = (*func)(self, name, NULL);
3598 if (res < 0)
3599 return NULL;
3600 Py_INCREF(Py_None);
3601 return Py_None;
3602}
3603
Tim Peters6d6c1a32001-08-02 04:15:00 +00003604static PyObject *
3605wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
3606{
3607 hashfunc func = (hashfunc)wrapped;
3608 long res;
3609
3610 if (!PyArg_ParseTuple(args, ""))
3611 return NULL;
3612 res = (*func)(self);
3613 if (res == -1 && PyErr_Occurred())
3614 return NULL;
3615 return PyInt_FromLong(res);
3616}
3617
Tim Peters6d6c1a32001-08-02 04:15:00 +00003618static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00003619wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003620{
3621 ternaryfunc func = (ternaryfunc)wrapped;
3622
Guido van Rossumc8e56452001-10-22 00:43:43 +00003623 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003624}
3625
Tim Peters6d6c1a32001-08-02 04:15:00 +00003626static PyObject *
3627wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
3628{
3629 richcmpfunc func = (richcmpfunc)wrapped;
3630 PyObject *other;
3631
3632 if (!PyArg_ParseTuple(args, "O", &other))
3633 return NULL;
3634 return (*func)(self, other, op);
3635}
3636
3637#undef RICHCMP_WRAPPER
3638#define RICHCMP_WRAPPER(NAME, OP) \
3639static PyObject * \
3640richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
3641{ \
3642 return wrap_richcmpfunc(self, args, wrapped, OP); \
3643}
3644
Jack Jansen8e938b42001-08-08 15:29:49 +00003645RICHCMP_WRAPPER(lt, Py_LT)
3646RICHCMP_WRAPPER(le, Py_LE)
3647RICHCMP_WRAPPER(eq, Py_EQ)
3648RICHCMP_WRAPPER(ne, Py_NE)
3649RICHCMP_WRAPPER(gt, Py_GT)
3650RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003651
Tim Peters6d6c1a32001-08-02 04:15:00 +00003652static PyObject *
3653wrap_next(PyObject *self, PyObject *args, void *wrapped)
3654{
3655 unaryfunc func = (unaryfunc)wrapped;
3656 PyObject *res;
3657
3658 if (!PyArg_ParseTuple(args, ""))
3659 return NULL;
3660 res = (*func)(self);
3661 if (res == NULL && !PyErr_Occurred())
3662 PyErr_SetNone(PyExc_StopIteration);
3663 return res;
3664}
3665
Tim Peters6d6c1a32001-08-02 04:15:00 +00003666static PyObject *
3667wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
3668{
3669 descrgetfunc func = (descrgetfunc)wrapped;
3670 PyObject *obj;
3671 PyObject *type = NULL;
3672
3673 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
3674 return NULL;
Guido van Rossum82ed25c2003-02-11 16:25:43 +00003675 if (obj == Py_None)
3676 obj = NULL;
3677 if (type == Py_None)
3678 type = NULL;
3679 if (type == NULL &&obj == NULL) {
3680 PyErr_SetString(PyExc_TypeError,
3681 "__get__(None, None) is invalid");
3682 return NULL;
3683 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003684 return (*func)(self, obj, type);
3685}
3686
Tim Peters6d6c1a32001-08-02 04:15:00 +00003687static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003688wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003689{
3690 descrsetfunc func = (descrsetfunc)wrapped;
3691 PyObject *obj, *value;
3692 int ret;
3693
3694 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
3695 return NULL;
3696 ret = (*func)(self, obj, value);
3697 if (ret < 0)
3698 return NULL;
3699 Py_INCREF(Py_None);
3700 return Py_None;
3701}
Guido van Rossum22b13872002-08-06 21:41:44 +00003702
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00003703static PyObject *
3704wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
3705{
3706 descrsetfunc func = (descrsetfunc)wrapped;
3707 PyObject *obj;
3708 int ret;
3709
3710 if (!PyArg_ParseTuple(args, "O", &obj))
3711 return NULL;
3712 ret = (*func)(self, obj, NULL);
3713 if (ret < 0)
3714 return NULL;
3715 Py_INCREF(Py_None);
3716 return Py_None;
3717}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003718
Tim Peters6d6c1a32001-08-02 04:15:00 +00003719static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00003720wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003721{
3722 initproc func = (initproc)wrapped;
3723
Guido van Rossumc8e56452001-10-22 00:43:43 +00003724 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003725 return NULL;
3726 Py_INCREF(Py_None);
3727 return Py_None;
3728}
3729
Tim Peters6d6c1a32001-08-02 04:15:00 +00003730static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003731tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003732{
Barry Warsaw60f01882001-08-22 19:24:42 +00003733 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003734 PyObject *arg0, *res;
3735
3736 if (self == NULL || !PyType_Check(self))
3737 Py_FatalError("__new__() called with non-type 'self'");
3738 type = (PyTypeObject *)self;
3739 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003740 PyErr_Format(PyExc_TypeError,
3741 "%s.__new__(): not enough arguments",
3742 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003743 return NULL;
3744 }
3745 arg0 = PyTuple_GET_ITEM(args, 0);
3746 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003747 PyErr_Format(PyExc_TypeError,
3748 "%s.__new__(X): X is not a type object (%s)",
3749 type->tp_name,
3750 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003751 return NULL;
3752 }
3753 subtype = (PyTypeObject *)arg0;
3754 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003755 PyErr_Format(PyExc_TypeError,
3756 "%s.__new__(%s): %s is not a subtype of %s",
3757 type->tp_name,
3758 subtype->tp_name,
3759 subtype->tp_name,
3760 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003761 return NULL;
3762 }
Barry Warsaw60f01882001-08-22 19:24:42 +00003763
3764 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00003765 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00003766 most derived base that's not a heap type is this type. */
3767 staticbase = subtype;
3768 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
3769 staticbase = staticbase->tp_base;
Guido van Rossuma8c60f42001-09-14 19:43:36 +00003770 if (staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003771 PyErr_Format(PyExc_TypeError,
3772 "%s.__new__(%s) is not safe, use %s.__new__()",
3773 type->tp_name,
3774 subtype->tp_name,
3775 staticbase == NULL ? "?" : staticbase->tp_name);
3776 return NULL;
3777 }
3778
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003779 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
3780 if (args == NULL)
3781 return NULL;
3782 res = type->tp_new(subtype, args, kwds);
3783 Py_DECREF(args);
3784 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003785}
3786
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003787static struct PyMethodDef tp_new_methoddef[] = {
3788 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00003789 PyDoc_STR("T.__new__(S, ...) -> "
3790 "a new object with type S, a subtype of T")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00003791 {0}
3792};
3793
3794static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003795add_tp_new_wrapper(PyTypeObject *type)
3796{
Guido van Rossumf040ede2001-08-07 16:40:56 +00003797 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003798
Guido van Rossum687ae002001-10-15 22:03:32 +00003799 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00003800 return 0;
3801 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003802 if (func == NULL)
3803 return -1;
Guido van Rossum687ae002001-10-15 22:03:32 +00003804 return PyDict_SetItemString(type->tp_dict, "__new__", func);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003805}
3806
Guido van Rossumf040ede2001-08-07 16:40:56 +00003807/* Slot wrappers that call the corresponding __foo__ slot. See comments
3808 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003809
Guido van Rossumdc91b992001-08-08 22:26:22 +00003810#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003811static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003812FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003813{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00003814 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003815 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003816}
3817
Guido van Rossumdc91b992001-08-08 22:26:22 +00003818#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003819static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003820FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003821{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003822 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003823 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003824}
3825
Guido van Rossumcd118802003-01-06 22:57:47 +00003826/* Boolean helper for SLOT1BINFULL().
3827 right.__class__ is a nontrivial subclass of left.__class__. */
3828static int
3829method_is_overloaded(PyObject *left, PyObject *right, char *name)
3830{
3831 PyObject *a, *b;
3832 int ok;
3833
3834 b = PyObject_GetAttrString((PyObject *)(right->ob_type), name);
3835 if (b == NULL) {
3836 PyErr_Clear();
3837 /* If right doesn't have it, it's not overloaded */
3838 return 0;
3839 }
3840
3841 a = PyObject_GetAttrString((PyObject *)(left->ob_type), name);
3842 if (a == NULL) {
3843 PyErr_Clear();
3844 Py_DECREF(b);
3845 /* If right has it but left doesn't, it's overloaded */
3846 return 1;
3847 }
3848
3849 ok = PyObject_RichCompareBool(a, b, Py_NE);
3850 Py_DECREF(a);
3851 Py_DECREF(b);
3852 if (ok < 0) {
3853 PyErr_Clear();
3854 return 0;
3855 }
3856
3857 return ok;
3858}
3859
Guido van Rossumdc91b992001-08-08 22:26:22 +00003860
3861#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003862static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003863FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003864{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003865 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00003866 int do_other = self->ob_type != other->ob_type && \
3867 other->ob_type->tp_as_number != NULL && \
3868 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003869 if (self->ob_type->tp_as_number != NULL && \
3870 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
3871 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00003872 if (do_other && \
Guido van Rossumcd118802003-01-06 22:57:47 +00003873 PyType_IsSubtype(other->ob_type, self->ob_type) && \
3874 method_is_overloaded(self, other, ROPSTR)) { \
Guido van Rossum55f20992001-10-01 17:18:22 +00003875 r = call_maybe( \
3876 other, ROPSTR, &rcache_str, "(O)", self); \
3877 if (r != Py_NotImplemented) \
3878 return r; \
3879 Py_DECREF(r); \
3880 do_other = 0; \
3881 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00003882 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00003883 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003884 if (r != Py_NotImplemented || \
3885 other->ob_type == self->ob_type) \
3886 return r; \
3887 Py_DECREF(r); \
3888 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00003889 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00003890 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00003891 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003892 } \
3893 Py_INCREF(Py_NotImplemented); \
3894 return Py_NotImplemented; \
3895}
3896
3897#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
3898 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
3899
3900#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
3901static PyObject * \
3902FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
3903{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003904 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003905 return call_method(self, OPSTR, &cache_str, \
3906 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003907}
3908
3909static int
3910slot_sq_length(PyObject *self)
3911{
Guido van Rossum2730b132001-08-28 18:22:14 +00003912 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00003913 PyObject *res = call_method(self, "__len__", &len_str, "()");
Guido van Rossum26111622001-10-01 16:42:49 +00003914 int len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003915
3916 if (res == NULL)
3917 return -1;
Guido van Rossum26111622001-10-01 16:42:49 +00003918 len = (int)PyInt_AsLong(res);
3919 Py_DECREF(res);
Jeremy Hylton73a088e2002-07-25 16:43:29 +00003920 if (len == -1 && PyErr_Occurred())
3921 return -1;
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00003922 if (len < 0) {
Guido van Rossum22b13872002-08-06 21:41:44 +00003923 PyErr_SetString(PyExc_ValueError,
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00003924 "__len__() should return >= 0");
3925 return -1;
3926 }
Guido van Rossum26111622001-10-01 16:42:49 +00003927 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003928}
3929
Guido van Rossumdc91b992001-08-08 22:26:22 +00003930SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
3931SLOT1(slot_sq_repeat, "__mul__", int, "i")
Guido van Rossumf4593e02001-10-03 12:09:30 +00003932
3933/* Super-optimized version of slot_sq_item.
3934 Other slots could do the same... */
3935static PyObject *
3936slot_sq_item(PyObject *self, int i)
3937{
3938 static PyObject *getitem_str;
3939 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
3940 descrgetfunc f;
3941
3942 if (getitem_str == NULL) {
3943 getitem_str = PyString_InternFromString("__getitem__");
3944 if (getitem_str == NULL)
3945 return NULL;
3946 }
3947 func = _PyType_Lookup(self->ob_type, getitem_str);
3948 if (func != NULL) {
Guido van Rossumf4593e02001-10-03 12:09:30 +00003949 if ((f = func->ob_type->tp_descr_get) == NULL)
3950 Py_INCREF(func);
Neal Norwitz673cd822002-10-18 16:33:13 +00003951 else {
Guido van Rossumf4593e02001-10-03 12:09:30 +00003952 func = f(func, self, (PyObject *)(self->ob_type));
Neal Norwitz673cd822002-10-18 16:33:13 +00003953 if (func == NULL) {
3954 return NULL;
3955 }
3956 }
Guido van Rossumf4593e02001-10-03 12:09:30 +00003957 ival = PyInt_FromLong(i);
3958 if (ival != NULL) {
3959 args = PyTuple_New(1);
3960 if (args != NULL) {
3961 PyTuple_SET_ITEM(args, 0, ival);
3962 retval = PyObject_Call(func, args, NULL);
3963 Py_XDECREF(args);
3964 Py_XDECREF(func);
3965 return retval;
3966 }
3967 }
3968 }
3969 else {
3970 PyErr_SetObject(PyExc_AttributeError, getitem_str);
3971 }
3972 Py_XDECREF(args);
3973 Py_XDECREF(ival);
3974 Py_XDECREF(func);
3975 return NULL;
3976}
3977
Guido van Rossumdc91b992001-08-08 22:26:22 +00003978SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003979
3980static int
3981slot_sq_ass_item(PyObject *self, int index, PyObject *value)
3982{
3983 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003984 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003985
3986 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003987 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003988 "(i)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003989 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003990 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003991 "(iO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003992 if (res == NULL)
3993 return -1;
3994 Py_DECREF(res);
3995 return 0;
3996}
3997
3998static int
3999slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
4000{
4001 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004002 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004003
4004 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004005 res = call_method(self, "__delslice__", &delslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004006 "(ii)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004007 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004008 res = call_method(self, "__setslice__", &setslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004009 "(iiO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004010 if (res == NULL)
4011 return -1;
4012 Py_DECREF(res);
4013 return 0;
4014}
4015
4016static int
4017slot_sq_contains(PyObject *self, PyObject *value)
4018{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004019 PyObject *func, *res, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00004020 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004021
Guido van Rossum55f20992001-10-01 17:18:22 +00004022 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004023
4024 if (func != NULL) {
4025 args = Py_BuildValue("(O)", value);
4026 if (args == NULL)
4027 res = NULL;
4028 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004029 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004030 Py_DECREF(args);
4031 }
4032 Py_DECREF(func);
4033 if (res == NULL)
4034 return -1;
4035 return PyObject_IsTrue(res);
4036 }
Guido van Rossum55f20992001-10-01 17:18:22 +00004037 else if (PyErr_Occurred())
4038 return -1;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004039 else {
Tim Peters16a77ad2001-09-08 04:00:12 +00004040 return _PySequence_IterSearch(self, value,
4041 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004042 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004043}
4044
Guido van Rossumdc91b992001-08-08 22:26:22 +00004045SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
4046SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004047
4048#define slot_mp_length slot_sq_length
4049
Guido van Rossumdc91b992001-08-08 22:26:22 +00004050SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004051
4052static int
4053slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
4054{
4055 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004056 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004057
4058 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004059 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004060 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004061 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004062 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004063 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004064 if (res == NULL)
4065 return -1;
4066 Py_DECREF(res);
4067 return 0;
4068}
4069
Guido van Rossumdc91b992001-08-08 22:26:22 +00004070SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
4071SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
4072SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
4073SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
4074SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
4075SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
4076
Jeremy Hylton938ace62002-07-17 16:30:39 +00004077static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00004078
4079SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
4080 nb_power, "__pow__", "__rpow__")
4081
4082static PyObject *
4083slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
4084{
Guido van Rossum2730b132001-08-28 18:22:14 +00004085 static PyObject *pow_str;
4086
Guido van Rossumdc91b992001-08-08 22:26:22 +00004087 if (modulus == Py_None)
4088 return slot_nb_power_binary(self, other);
Guido van Rossum23094982002-06-10 14:30:43 +00004089 /* Three-arg power doesn't use __rpow__. But ternary_op
4090 can call this when the second argument's type uses
4091 slot_nb_power, so check before calling self.__pow__. */
4092 if (self->ob_type->tp_as_number != NULL &&
4093 self->ob_type->tp_as_number->nb_power == slot_nb_power) {
4094 return call_method(self, "__pow__", &pow_str,
4095 "(OO)", other, modulus);
4096 }
4097 Py_INCREF(Py_NotImplemented);
4098 return Py_NotImplemented;
Guido van Rossumdc91b992001-08-08 22:26:22 +00004099}
4100
4101SLOT0(slot_nb_negative, "__neg__")
4102SLOT0(slot_nb_positive, "__pos__")
4103SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004104
4105static int
4106slot_nb_nonzero(PyObject *self)
4107{
Tim Petersea7f75d2002-12-07 21:39:16 +00004108 PyObject *func, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00004109 static PyObject *nonzero_str, *len_str;
Tim Petersea7f75d2002-12-07 21:39:16 +00004110 int result = -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004111
Guido van Rossum55f20992001-10-01 17:18:22 +00004112 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004113 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00004114 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00004115 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00004116 func = lookup_maybe(self, "__len__", &len_str);
Tim Petersea7f75d2002-12-07 21:39:16 +00004117 if (func == NULL)
4118 return PyErr_Occurred() ? -1 : 1;
4119 }
4120 args = PyTuple_New(0);
4121 if (args != NULL) {
4122 PyObject *temp = PyObject_Call(func, args, NULL);
4123 Py_DECREF(args);
4124 if (temp != NULL) {
4125 result = PyObject_IsTrue(temp);
4126 Py_DECREF(temp);
Guido van Rossum55f20992001-10-01 17:18:22 +00004127 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004128 }
Guido van Rossum55f20992001-10-01 17:18:22 +00004129 Py_DECREF(func);
Tim Petersea7f75d2002-12-07 21:39:16 +00004130 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004131}
4132
Guido van Rossumdc91b992001-08-08 22:26:22 +00004133SLOT0(slot_nb_invert, "__invert__")
4134SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
4135SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
4136SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
4137SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
4138SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004139
4140static int
4141slot_nb_coerce(PyObject **a, PyObject **b)
4142{
4143 static PyObject *coerce_str;
4144 PyObject *self = *a, *other = *b;
4145
4146 if (self->ob_type->tp_as_number != NULL &&
4147 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
4148 PyObject *r;
4149 r = call_maybe(
4150 self, "__coerce__", &coerce_str, "(O)", other);
4151 if (r == NULL)
4152 return -1;
4153 if (r == Py_NotImplemented) {
4154 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004155 }
Guido van Rossum55f20992001-10-01 17:18:22 +00004156 else {
4157 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
4158 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004159 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00004160 Py_DECREF(r);
4161 return -1;
4162 }
4163 *a = PyTuple_GET_ITEM(r, 0);
4164 Py_INCREF(*a);
4165 *b = PyTuple_GET_ITEM(r, 1);
4166 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004167 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00004168 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004169 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004170 }
4171 if (other->ob_type->tp_as_number != NULL &&
4172 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
4173 PyObject *r;
4174 r = call_maybe(
4175 other, "__coerce__", &coerce_str, "(O)", self);
4176 if (r == NULL)
4177 return -1;
4178 if (r == Py_NotImplemented) {
4179 Py_DECREF(r);
4180 return 1;
4181 }
4182 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
4183 PyErr_SetString(PyExc_TypeError,
4184 "__coerce__ didn't return a 2-tuple");
4185 Py_DECREF(r);
4186 return -1;
4187 }
4188 *a = PyTuple_GET_ITEM(r, 1);
4189 Py_INCREF(*a);
4190 *b = PyTuple_GET_ITEM(r, 0);
4191 Py_INCREF(*b);
4192 Py_DECREF(r);
4193 return 0;
4194 }
4195 return 1;
4196}
4197
Guido van Rossumdc91b992001-08-08 22:26:22 +00004198SLOT0(slot_nb_int, "__int__")
4199SLOT0(slot_nb_long, "__long__")
4200SLOT0(slot_nb_float, "__float__")
4201SLOT0(slot_nb_oct, "__oct__")
4202SLOT0(slot_nb_hex, "__hex__")
4203SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
4204SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
4205SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
4206SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
4207SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Guido van Rossum6e5680f2002-10-15 01:01:53 +00004208SLOT1(slot_nb_inplace_power, "__ipow__", PyObject *, "O")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004209SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
4210SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
4211SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
4212SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
4213SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
4214SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
4215 "__floordiv__", "__rfloordiv__")
4216SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
4217SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
4218SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004219
4220static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00004221half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004222{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004223 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004224 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004225 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004226
Guido van Rossum60718732001-08-28 17:47:51 +00004227 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004228 if (func == NULL) {
4229 PyErr_Clear();
4230 }
4231 else {
4232 args = Py_BuildValue("(O)", other);
4233 if (args == NULL)
4234 res = NULL;
4235 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004236 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004237 Py_DECREF(args);
4238 }
Raymond Hettingerab5dae32002-06-24 13:08:16 +00004239 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004240 if (res != Py_NotImplemented) {
4241 if (res == NULL)
4242 return -2;
4243 c = PyInt_AsLong(res);
4244 Py_DECREF(res);
4245 if (c == -1 && PyErr_Occurred())
4246 return -2;
4247 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
4248 }
4249 Py_DECREF(res);
4250 }
4251 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004252}
4253
Guido van Rossumab3b0342001-09-18 20:38:53 +00004254/* This slot is published for the benefit of try_3way_compare in object.c */
4255int
4256_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00004257{
4258 int c;
4259
Guido van Rossumab3b0342001-09-18 20:38:53 +00004260 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004261 c = half_compare(self, other);
4262 if (c <= 1)
4263 return c;
4264 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00004265 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004266 c = half_compare(other, self);
4267 if (c < -1)
4268 return -2;
4269 if (c <= 1)
4270 return -c;
4271 }
4272 return (void *)self < (void *)other ? -1 :
4273 (void *)self > (void *)other ? 1 : 0;
4274}
4275
4276static PyObject *
4277slot_tp_repr(PyObject *self)
4278{
4279 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004280 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004281
Guido van Rossum60718732001-08-28 17:47:51 +00004282 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004283 if (func != NULL) {
4284 res = PyEval_CallObject(func, NULL);
4285 Py_DECREF(func);
4286 return res;
4287 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00004288 PyErr_Clear();
4289 return PyString_FromFormat("<%s object at %p>",
4290 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004291}
4292
4293static PyObject *
4294slot_tp_str(PyObject *self)
4295{
4296 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004297 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004298
Guido van Rossum60718732001-08-28 17:47:51 +00004299 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004300 if (func != NULL) {
4301 res = PyEval_CallObject(func, NULL);
4302 Py_DECREF(func);
4303 return res;
4304 }
4305 else {
4306 PyErr_Clear();
4307 return slot_tp_repr(self);
4308 }
4309}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004310
4311static long
4312slot_tp_hash(PyObject *self)
4313{
Tim Peters61ce0a92002-12-06 23:38:02 +00004314 PyObject *func;
Guido van Rossum60718732001-08-28 17:47:51 +00004315 static PyObject *hash_str, *eq_str, *cmp_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004316 long h;
4317
Guido van Rossum60718732001-08-28 17:47:51 +00004318 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004319
4320 if (func != NULL) {
Tim Peters61ce0a92002-12-06 23:38:02 +00004321 PyObject *res = PyEval_CallObject(func, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004322 Py_DECREF(func);
4323 if (res == NULL)
4324 return -1;
4325 h = PyInt_AsLong(res);
Tim Peters61ce0a92002-12-06 23:38:02 +00004326 Py_DECREF(res);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004327 }
4328 else {
4329 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004330 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004331 if (func == NULL) {
4332 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004333 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004334 }
4335 if (func != NULL) {
4336 Py_DECREF(func);
4337 PyErr_SetString(PyExc_TypeError, "unhashable type");
4338 return -1;
4339 }
4340 PyErr_Clear();
4341 h = _Py_HashPointer((void *)self);
4342 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004343 if (h == -1 && !PyErr_Occurred())
4344 h = -2;
4345 return h;
4346}
4347
4348static PyObject *
4349slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
4350{
Guido van Rossum60718732001-08-28 17:47:51 +00004351 static PyObject *call_str;
4352 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004353 PyObject *res;
4354
4355 if (meth == NULL)
4356 return NULL;
4357 res = PyObject_Call(meth, args, kwds);
4358 Py_DECREF(meth);
4359 return res;
4360}
4361
Guido van Rossum14a6f832001-10-17 13:59:09 +00004362/* There are two slot dispatch functions for tp_getattro.
4363
4364 - slot_tp_getattro() is used when __getattribute__ is overridden
4365 but no __getattr__ hook is present;
4366
4367 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
4368
Guido van Rossumc334df52002-04-04 23:44:47 +00004369 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
4370 detects the absence of __getattr__ and then installs the simpler slot if
4371 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00004372
Tim Peters6d6c1a32001-08-02 04:15:00 +00004373static PyObject *
4374slot_tp_getattro(PyObject *self, PyObject *name)
4375{
Guido van Rossum14a6f832001-10-17 13:59:09 +00004376 static PyObject *getattribute_str = NULL;
4377 return call_method(self, "__getattribute__", &getattribute_str,
4378 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004379}
4380
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004381static PyObject *
4382slot_tp_getattr_hook(PyObject *self, PyObject *name)
4383{
4384 PyTypeObject *tp = self->ob_type;
4385 PyObject *getattr, *getattribute, *res;
4386 static PyObject *getattribute_str = NULL;
4387 static PyObject *getattr_str = NULL;
4388
4389 if (getattr_str == NULL) {
4390 getattr_str = PyString_InternFromString("__getattr__");
4391 if (getattr_str == NULL)
4392 return NULL;
4393 }
4394 if (getattribute_str == NULL) {
4395 getattribute_str =
4396 PyString_InternFromString("__getattribute__");
4397 if (getattribute_str == NULL)
4398 return NULL;
4399 }
4400 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004401 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004402 /* No __getattr__ hook: use a simpler dispatcher */
4403 tp->tp_getattro = slot_tp_getattro;
4404 return slot_tp_getattro(self, name);
4405 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004406 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004407 if (getattribute == NULL ||
4408 (getattribute->ob_type == &PyWrapperDescr_Type &&
4409 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
4410 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004411 res = PyObject_GenericGetAttr(self, name);
4412 else
4413 res = PyObject_CallFunction(getattribute, "OO", self, name);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004414 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004415 PyErr_Clear();
4416 res = PyObject_CallFunction(getattr, "OO", self, name);
4417 }
4418 return res;
4419}
4420
Tim Peters6d6c1a32001-08-02 04:15:00 +00004421static int
4422slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
4423{
4424 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004425 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004426
4427 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004428 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004429 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004430 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004431 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004432 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004433 if (res == NULL)
4434 return -1;
4435 Py_DECREF(res);
4436 return 0;
4437}
4438
4439/* Map rich comparison operators to their __xx__ namesakes */
4440static char *name_op[] = {
4441 "__lt__",
4442 "__le__",
4443 "__eq__",
4444 "__ne__",
4445 "__gt__",
4446 "__ge__",
4447};
4448
4449static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00004450half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004451{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004452 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004453 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00004454
Guido van Rossum60718732001-08-28 17:47:51 +00004455 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004456 if (func == NULL) {
4457 PyErr_Clear();
4458 Py_INCREF(Py_NotImplemented);
4459 return Py_NotImplemented;
4460 }
4461 args = Py_BuildValue("(O)", other);
4462 if (args == NULL)
4463 res = NULL;
4464 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004465 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004466 Py_DECREF(args);
4467 }
4468 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004469 return res;
4470}
4471
Guido van Rossumb8f63662001-08-15 23:57:02 +00004472/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
4473static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
4474
4475static PyObject *
4476slot_tp_richcompare(PyObject *self, PyObject *other, int op)
4477{
4478 PyObject *res;
4479
4480 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
4481 res = half_richcompare(self, other, op);
4482 if (res != Py_NotImplemented)
4483 return res;
4484 Py_DECREF(res);
4485 }
4486 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
4487 res = half_richcompare(other, self, swapped_op[op]);
4488 if (res != Py_NotImplemented) {
4489 return res;
4490 }
4491 Py_DECREF(res);
4492 }
4493 Py_INCREF(Py_NotImplemented);
4494 return Py_NotImplemented;
4495}
4496
4497static PyObject *
4498slot_tp_iter(PyObject *self)
4499{
4500 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004501 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004502
Guido van Rossum60718732001-08-28 17:47:51 +00004503 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004504 if (func != NULL) {
Guido van Rossum84b2bed2002-08-16 17:01:09 +00004505 PyObject *args;
4506 args = res = PyTuple_New(0);
4507 if (args != NULL) {
4508 res = PyObject_Call(func, args, NULL);
4509 Py_DECREF(args);
4510 }
4511 Py_DECREF(func);
4512 return res;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004513 }
4514 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004515 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004516 if (func == NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00004517 PyErr_SetString(PyExc_TypeError,
4518 "iteration over non-sequence");
Guido van Rossumb8f63662001-08-15 23:57:02 +00004519 return NULL;
4520 }
4521 Py_DECREF(func);
4522 return PySeqIter_New(self);
4523}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004524
4525static PyObject *
4526slot_tp_iternext(PyObject *self)
4527{
Guido van Rossum2730b132001-08-28 18:22:14 +00004528 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00004529 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004530}
4531
Guido van Rossum1a493502001-08-17 16:47:50 +00004532static PyObject *
4533slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4534{
4535 PyTypeObject *tp = self->ob_type;
4536 PyObject *get;
4537 static PyObject *get_str = NULL;
4538
4539 if (get_str == NULL) {
4540 get_str = PyString_InternFromString("__get__");
4541 if (get_str == NULL)
4542 return NULL;
4543 }
4544 get = _PyType_Lookup(tp, get_str);
4545 if (get == NULL) {
4546 /* Avoid further slowdowns */
4547 if (tp->tp_descr_get == slot_tp_descr_get)
4548 tp->tp_descr_get = NULL;
4549 Py_INCREF(self);
4550 return self;
4551 }
Guido van Rossum2c252392001-08-24 10:13:31 +00004552 if (obj == NULL)
4553 obj = Py_None;
4554 if (type == NULL)
4555 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00004556 return PyObject_CallFunction(get, "OOO", self, obj, type);
4557}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004558
4559static int
4560slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
4561{
Guido van Rossum2c252392001-08-24 10:13:31 +00004562 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004563 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00004564
4565 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00004566 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004567 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00004568 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004569 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004570 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004571 if (res == NULL)
4572 return -1;
4573 Py_DECREF(res);
4574 return 0;
4575}
4576
4577static int
4578slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
4579{
Guido van Rossum60718732001-08-28 17:47:51 +00004580 static PyObject *init_str;
4581 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004582 PyObject *res;
4583
4584 if (meth == NULL)
4585 return -1;
4586 res = PyObject_Call(meth, args, kwds);
4587 Py_DECREF(meth);
4588 if (res == NULL)
4589 return -1;
4590 Py_DECREF(res);
4591 return 0;
4592}
4593
4594static PyObject *
4595slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4596{
Guido van Rossum7bed2132002-08-08 21:57:53 +00004597 static PyObject *new_str;
4598 PyObject *func;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004599 PyObject *newargs, *x;
4600 int i, n;
4601
Guido van Rossum7bed2132002-08-08 21:57:53 +00004602 if (new_str == NULL) {
4603 new_str = PyString_InternFromString("__new__");
4604 if (new_str == NULL)
4605 return NULL;
4606 }
4607 func = PyObject_GetAttr((PyObject *)type, new_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004608 if (func == NULL)
4609 return NULL;
4610 assert(PyTuple_Check(args));
4611 n = PyTuple_GET_SIZE(args);
4612 newargs = PyTuple_New(n+1);
4613 if (newargs == NULL)
4614 return NULL;
4615 Py_INCREF(type);
4616 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
4617 for (i = 0; i < n; i++) {
4618 x = PyTuple_GET_ITEM(args, i);
4619 Py_INCREF(x);
4620 PyTuple_SET_ITEM(newargs, i+1, x);
4621 }
4622 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00004623 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004624 Py_DECREF(func);
4625 return x;
4626}
4627
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004628static void
4629slot_tp_del(PyObject *self)
4630{
4631 static PyObject *del_str = NULL;
4632 PyObject *del, *res;
4633 PyObject *error_type, *error_value, *error_traceback;
4634
4635 /* Temporarily resurrect the object. */
4636 assert(self->ob_refcnt == 0);
4637 self->ob_refcnt = 1;
4638
4639 /* Save the current exception, if any. */
4640 PyErr_Fetch(&error_type, &error_value, &error_traceback);
4641
4642 /* Execute __del__ method, if any. */
4643 del = lookup_maybe(self, "__del__", &del_str);
4644 if (del != NULL) {
4645 res = PyEval_CallObject(del, NULL);
4646 if (res == NULL)
4647 PyErr_WriteUnraisable(del);
4648 else
4649 Py_DECREF(res);
4650 Py_DECREF(del);
4651 }
4652
4653 /* Restore the saved exception. */
4654 PyErr_Restore(error_type, error_value, error_traceback);
4655
4656 /* Undo the temporary resurrection; can't use DECREF here, it would
4657 * cause a recursive call.
4658 */
4659 assert(self->ob_refcnt > 0);
4660 if (--self->ob_refcnt == 0)
4661 return; /* this is the normal path out */
4662
4663 /* __del__ resurrected it! Make it look like the original Py_DECREF
4664 * never happened.
4665 */
4666 {
4667 int refcnt = self->ob_refcnt;
4668 _Py_NewReference(self);
4669 self->ob_refcnt = refcnt;
4670 }
4671 assert(!PyType_IS_GC(self->ob_type) ||
4672 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
4673 /* If Py_REF_DEBUG, the original decref dropped _Py_RefTotal, but
4674 * _Py_NewReference bumped it again, so that's a wash.
4675 * If Py_TRACE_REFS, _Py_NewReference re-added self to the object
4676 * chain, so no more to do there either.
4677 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
4678 * _Py_NewReference bumped tp_allocs: both of those need to be
4679 * undone.
4680 */
4681#ifdef COUNT_ALLOCS
4682 --self->ob_type->tp_frees;
4683 --self->ob_type->tp_allocs;
4684#endif
4685}
4686
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004687
4688/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
4689 functions. The offsets here are relative to the 'etype' structure, which
4690 incorporates the additional structures used for numbers, sequences and
4691 mappings. Note that multiple names may map to the same slot (e.g. __eq__,
4692 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00004693 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
4694 terminated with an all-zero entry. (This table is further initialized and
4695 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004696
Guido van Rossum6d204072001-10-21 00:44:31 +00004697typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004698
4699#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00004700#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004701#undef ETSLOT
4702#undef SQSLOT
4703#undef MPSLOT
4704#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00004705#undef UNSLOT
4706#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004707#undef BINSLOT
4708#undef RBINSLOT
4709
Guido van Rossum6d204072001-10-21 00:44:31 +00004710#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004711 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
4712 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00004713#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
4714 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004715 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00004716#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004717 {NAME, offsetof(etype, SLOT), (void *)(FUNCTION), WRAPPER, \
4718 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00004719#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4720 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
4721#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4722 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
4723#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4724 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
4725#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4726 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
4727 "x." NAME "() <==> " DOC)
4728#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4729 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
4730 "x." NAME "(y) <==> x" DOC "y")
4731#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
4732 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
4733 "x." NAME "(y) <==> x" DOC "y")
4734#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
4735 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
4736 "x." NAME "(y) <==> y" DOC "x")
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004737
4738static slotdef slotdefs[] = {
Guido van Rossum6d204072001-10-21 00:44:31 +00004739 SQSLOT("__len__", sq_length, slot_sq_length, wrap_inquiry,
4740 "x.__len__() <==> len(x)"),
4741 SQSLOT("__add__", sq_concat, slot_sq_concat, wrap_binaryfunc,
4742 "x.__add__(y) <==> x+y"),
4743 SQSLOT("__mul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
4744 "x.__mul__(n) <==> x*n"),
4745 SQSLOT("__rmul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
4746 "x.__rmul__(n) <==> n*x"),
4747 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
4748 "x.__getitem__(y) <==> x[y]"),
4749 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_intintargfunc,
4750 "x.__getslice__(i, j) <==> x[i:j]"),
4751 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
4752 "x.__setitem__(i, y) <==> x[i]=y"),
4753 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
4754 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004755 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Guido van Rossum6d204072001-10-21 00:44:31 +00004756 wrap_intintobjargproc,
4757 "x.__setslice__(i, j, y) <==> x[i:j]=y"),
4758 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
4759 "x.__delslice__(i, j) <==> del x[i:j]"),
4760 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
4761 "x.__contains__(y) <==> y in x"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004762 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat,
Guido van Rossum6d204072001-10-21 00:44:31 +00004763 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004764 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat,
Guido van Rossum6d204072001-10-21 00:44:31 +00004765 wrap_intargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004766
Guido van Rossum6d204072001-10-21 00:44:31 +00004767 MPSLOT("__len__", mp_length, slot_mp_length, wrap_inquiry,
4768 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00004769 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004770 wrap_binaryfunc,
4771 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004772 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004773 wrap_objobjargproc,
4774 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004775 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004776 wrap_delitem,
4777 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004778
Guido van Rossum6d204072001-10-21 00:44:31 +00004779 BINSLOT("__add__", nb_add, slot_nb_add,
4780 "+"),
4781 RBINSLOT("__radd__", nb_add, slot_nb_add,
4782 "+"),
4783 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
4784 "-"),
4785 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
4786 "-"),
4787 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
4788 "*"),
4789 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
4790 "*"),
4791 BINSLOT("__div__", nb_divide, slot_nb_divide,
4792 "/"),
4793 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
4794 "/"),
4795 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
4796 "%"),
4797 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
4798 "%"),
4799 BINSLOT("__divmod__", nb_divmod, slot_nb_divmod,
4800 "divmod(x, y)"),
4801 RBINSLOT("__rdivmod__", nb_divmod, slot_nb_divmod,
4802 "divmod(y, x)"),
4803 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
4804 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
4805 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
4806 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
4807 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
4808 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
4809 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
4810 "abs(x)"),
Guido van Rossumdfce3bf2002-03-10 14:11:16 +00004811 UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquiry,
Guido van Rossum6d204072001-10-21 00:44:31 +00004812 "x != 0"),
4813 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
4814 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
4815 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
4816 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
4817 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
4818 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
4819 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
4820 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
4821 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
4822 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
4823 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
4824 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
4825 "x.__coerce__(y) <==> coerce(x, y)"),
4826 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
4827 "int(x)"),
4828 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
4829 "long(x)"),
4830 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
4831 "float(x)"),
4832 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
4833 "oct(x)"),
4834 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
4835 "hex(x)"),
4836 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
4837 wrap_binaryfunc, "+"),
4838 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
4839 wrap_binaryfunc, "-"),
4840 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
4841 wrap_binaryfunc, "*"),
4842 IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
4843 wrap_binaryfunc, "/"),
4844 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
4845 wrap_binaryfunc, "%"),
4846 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
Guido van Rossum6e5680f2002-10-15 01:01:53 +00004847 wrap_binaryfunc, "**"),
Guido van Rossum6d204072001-10-21 00:44:31 +00004848 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
4849 wrap_binaryfunc, "<<"),
4850 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
4851 wrap_binaryfunc, ">>"),
4852 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
4853 wrap_binaryfunc, "&"),
4854 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
4855 wrap_binaryfunc, "^"),
4856 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
4857 wrap_binaryfunc, "|"),
4858 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
4859 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
4860 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
4861 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
4862 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
4863 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
4864 IBSLOT("__itruediv__", nb_inplace_true_divide,
4865 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004866
Guido van Rossum6d204072001-10-21 00:44:31 +00004867 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
4868 "x.__str__() <==> str(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00004869 TPSLOT("__str__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00004870 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
4871 "x.__repr__() <==> repr(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00004872 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00004873 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
4874 "x.__cmp__(y) <==> cmp(x,y)"),
4875 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
4876 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00004877 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
4878 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004879 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00004880 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
4881 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
4882 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
4883 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
4884 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
4885 "x.__setattr__('name', value) <==> x.name = value"),
4886 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
4887 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
4888 "x.__delattr__('name') <==> del x.name"),
4889 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
4890 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
4891 "x.__lt__(y) <==> x<y"),
4892 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
4893 "x.__le__(y) <==> x<=y"),
4894 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
4895 "x.__eq__(y) <==> x==y"),
4896 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
4897 "x.__ne__(y) <==> x!=y"),
4898 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
4899 "x.__gt__(y) <==> x>y"),
4900 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
4901 "x.__ge__(y) <==> x>=y"),
4902 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
4903 "x.__iter__() <==> iter(x)"),
4904 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
4905 "x.next() -> the next value, or raise StopIteration"),
4906 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
4907 "descr.__get__(obj[, type]) -> value"),
4908 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
4909 "descr.__set__(obj, value)"),
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004910 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
4911 wrap_descr_delete, "descr.__delete__(obj)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00004912 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00004913 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00004914 "see x.__class__.__doc__ for signature",
4915 PyWrapperFlag_KEYWORDS),
4916 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004917 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004918 {NULL}
4919};
4920
Guido van Rossumc334df52002-04-04 23:44:47 +00004921/* Given a type pointer and an offset gotten from a slotdef entry, return a
4922 pointer to the actual slot. This is not quite the same as simply adding
4923 the offset to the type pointer, since it takes care to indirect through the
4924 proper indirection pointer (as_buffer, etc.); it returns NULL if the
4925 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004926static void **
4927slotptr(PyTypeObject *type, int offset)
4928{
4929 char *ptr;
4930
Guido van Rossum09638c12002-06-13 19:17:46 +00004931 /* Note: this depends on the order of the members of etype! */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004932 assert(offset >= 0);
4933 assert(offset < offsetof(etype, as_buffer));
Guido van Rossum09638c12002-06-13 19:17:46 +00004934 if (offset >= offsetof(etype, as_sequence)) {
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004935 ptr = (void *)type->tp_as_sequence;
4936 offset -= offsetof(etype, as_sequence);
4937 }
Guido van Rossum09638c12002-06-13 19:17:46 +00004938 else if (offset >= offsetof(etype, as_mapping)) {
4939 ptr = (void *)type->tp_as_mapping;
4940 offset -= offsetof(etype, as_mapping);
4941 }
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004942 else if (offset >= offsetof(etype, as_number)) {
4943 ptr = (void *)type->tp_as_number;
4944 offset -= offsetof(etype, as_number);
4945 }
4946 else {
4947 ptr = (void *)type;
4948 }
4949 if (ptr != NULL)
4950 ptr += offset;
4951 return (void **)ptr;
4952}
Guido van Rossumf040ede2001-08-07 16:40:56 +00004953
Guido van Rossumc334df52002-04-04 23:44:47 +00004954/* Length of array of slotdef pointers used to store slots with the
4955 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
4956 the same __name__, for any __name__. Since that's a static property, it is
4957 appropriate to declare fixed-size arrays for this. */
4958#define MAX_EQUIV 10
4959
4960/* Return a slot pointer for a given name, but ONLY if the attribute has
4961 exactly one slot function. The name must be an interned string. */
4962static void **
4963resolve_slotdups(PyTypeObject *type, PyObject *name)
4964{
4965 /* XXX Maybe this could be optimized more -- but is it worth it? */
4966
4967 /* pname and ptrs act as a little cache */
4968 static PyObject *pname;
4969 static slotdef *ptrs[MAX_EQUIV];
4970 slotdef *p, **pp;
4971 void **res, **ptr;
4972
4973 if (pname != name) {
4974 /* Collect all slotdefs that match name into ptrs. */
4975 pname = name;
4976 pp = ptrs;
4977 for (p = slotdefs; p->name_strobj; p++) {
4978 if (p->name_strobj == name)
4979 *pp++ = p;
4980 }
4981 *pp = NULL;
4982 }
4983
4984 /* Look in all matching slots of the type; if exactly one of these has
4985 a filled-in slot, return its value. Otherwise return NULL. */
4986 res = NULL;
4987 for (pp = ptrs; *pp; pp++) {
4988 ptr = slotptr(type, (*pp)->offset);
4989 if (ptr == NULL || *ptr == NULL)
4990 continue;
4991 if (res != NULL)
4992 return NULL;
4993 res = ptr;
4994 }
4995 return res;
4996}
4997
4998/* Common code for update_these_slots() and fixup_slot_dispatchers(). This
4999 does some incredibly complex thinking and then sticks something into the
5000 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
5001 interests, and then stores a generic wrapper or a specific function into
5002 the slot.) Return a pointer to the next slotdef with a different offset,
5003 because that's convenient for fixup_slot_dispatchers(). */
5004static slotdef *
5005update_one_slot(PyTypeObject *type, slotdef *p)
5006{
5007 PyObject *descr;
5008 PyWrapperDescrObject *d;
5009 void *generic = NULL, *specific = NULL;
5010 int use_generic = 0;
5011 int offset = p->offset;
5012 void **ptr = slotptr(type, offset);
5013
5014 if (ptr == NULL) {
5015 do {
5016 ++p;
5017 } while (p->offset == offset);
5018 return p;
5019 }
5020 do {
5021 descr = _PyType_Lookup(type, p->name_strobj);
5022 if (descr == NULL)
5023 continue;
5024 if (descr->ob_type == &PyWrapperDescr_Type) {
5025 void **tptr = resolve_slotdups(type, p->name_strobj);
5026 if (tptr == NULL || tptr == ptr)
5027 generic = p->function;
5028 d = (PyWrapperDescrObject *)descr;
5029 if (d->d_base->wrapper == p->wrapper &&
5030 PyType_IsSubtype(type, d->d_type))
5031 {
5032 if (specific == NULL ||
5033 specific == d->d_wrapped)
5034 specific = d->d_wrapped;
5035 else
5036 use_generic = 1;
5037 }
5038 }
Guido van Rossum721f62e2002-08-09 02:14:34 +00005039 else if (descr->ob_type == &PyCFunction_Type &&
5040 PyCFunction_GET_FUNCTION(descr) ==
5041 (PyCFunction)tp_new_wrapper &&
5042 strcmp(p->name, "__new__") == 0)
5043 {
5044 /* The __new__ wrapper is not a wrapper descriptor,
5045 so must be special-cased differently.
5046 If we don't do this, creating an instance will
5047 always use slot_tp_new which will look up
5048 __new__ in the MRO which will call tp_new_wrapper
5049 which will look through the base classes looking
5050 for a static base and call its tp_new (usually
5051 PyType_GenericNew), after performing various
5052 sanity checks and constructing a new argument
5053 list. Cut all that nonsense short -- this speeds
5054 up instance creation tremendously. */
5055 specific = type->tp_new;
5056 /* XXX I'm not 100% sure that there isn't a hole
5057 in this reasoning that requires additional
5058 sanity checks. I'll buy the first person to
5059 point out a bug in this reasoning a beer. */
5060 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005061 else {
5062 use_generic = 1;
5063 generic = p->function;
5064 }
5065 } while ((++p)->offset == offset);
5066 if (specific && !use_generic)
5067 *ptr = specific;
5068 else
5069 *ptr = generic;
5070 return p;
5071}
5072
Guido van Rossum22b13872002-08-06 21:41:44 +00005073static int recurse_down_subclasses(PyTypeObject *type, slotdef **pp,
Jeremy Hylton938ace62002-07-17 16:30:39 +00005074 PyObject *name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005075
Guido van Rossumc334df52002-04-04 23:44:47 +00005076/* In the type, update the slots whose slotdefs are gathered in the pp0 array,
5077 and then do the same for all this type's subtypes. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005078static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005079update_these_slots(PyTypeObject *type, slotdef **pp0, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005080{
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005081 slotdef **pp;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005082
Guido van Rossumc334df52002-04-04 23:44:47 +00005083 for (pp = pp0; *pp; pp++)
5084 update_one_slot(type, *pp);
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005085 return recurse_down_subclasses(type, pp0, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005086}
5087
Guido van Rossumc334df52002-04-04 23:44:47 +00005088/* Update the slots whose slotdefs are gathered in the pp array in all (direct
5089 or indirect) subclasses of type. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005090static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005091recurse_down_subclasses(PyTypeObject *type, slotdef **pp, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005092{
5093 PyTypeObject *subclass;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005094 PyObject *ref, *subclasses, *dict;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005095 int i, n;
5096
5097 subclasses = type->tp_subclasses;
5098 if (subclasses == NULL)
5099 return 0;
5100 assert(PyList_Check(subclasses));
5101 n = PyList_GET_SIZE(subclasses);
5102 for (i = 0; i < n; i++) {
5103 ref = PyList_GET_ITEM(subclasses, i);
5104 assert(PyWeakref_CheckRef(ref));
5105 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
Guido van Rossum59e6c532002-06-14 02:27:07 +00005106 assert(subclass != NULL);
5107 if ((PyObject *)subclass == Py_None)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005108 continue;
5109 assert(PyType_Check(subclass));
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005110 /* Avoid recursing down into unaffected classes */
5111 dict = subclass->tp_dict;
5112 if (dict != NULL && PyDict_Check(dict) &&
5113 PyDict_GetItem(dict, name) != NULL)
5114 continue;
5115 if (update_these_slots(subclass, pp, name) < 0)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005116 return -1;
5117 }
5118 return 0;
5119}
5120
Guido van Rossumc334df52002-04-04 23:44:47 +00005121/* Comparison function for qsort() to compare slotdefs by their offset, and
5122 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005123static int
5124slotdef_cmp(const void *aa, const void *bb)
5125{
5126 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
5127 int c = a->offset - b->offset;
5128 if (c != 0)
5129 return c;
5130 else
5131 return a - b;
5132}
5133
Guido van Rossumc334df52002-04-04 23:44:47 +00005134/* Initialize the slotdefs table by adding interned string objects for the
5135 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005136static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005137init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005138{
5139 slotdef *p;
5140 static int initialized = 0;
5141
5142 if (initialized)
5143 return;
5144 for (p = slotdefs; p->name; p++) {
5145 p->name_strobj = PyString_InternFromString(p->name);
5146 if (!p->name_strobj)
Guido van Rossumc334df52002-04-04 23:44:47 +00005147 Py_FatalError("Out of memory interning slotdef names");
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005148 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005149 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
5150 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005151 initialized = 1;
5152}
5153
Guido van Rossumc334df52002-04-04 23:44:47 +00005154/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005155static int
5156update_slot(PyTypeObject *type, PyObject *name)
5157{
Guido van Rossumc334df52002-04-04 23:44:47 +00005158 slotdef *ptrs[MAX_EQUIV];
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005159 slotdef *p;
5160 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005161 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005162
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005163 init_slotdefs();
5164 pp = ptrs;
5165 for (p = slotdefs; p->name; p++) {
5166 /* XXX assume name is interned! */
5167 if (p->name_strobj == name)
5168 *pp++ = p;
5169 }
5170 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005171 for (pp = ptrs; *pp; pp++) {
5172 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005173 offset = p->offset;
5174 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005175 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005176 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005177 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005178 if (ptrs[0] == NULL)
5179 return 0; /* Not an attribute that affects any slots */
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005180 return update_these_slots(type, ptrs, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005181}
5182
Guido van Rossumc334df52002-04-04 23:44:47 +00005183/* Store the proper functions in the slot dispatches at class (type)
5184 definition time, based upon which operations the class overrides in its
5185 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00005186static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005187fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005188{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005189 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005190
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005191 init_slotdefs();
Guido van Rossumc334df52002-04-04 23:44:47 +00005192 for (p = slotdefs; p->name; )
5193 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005194}
Guido van Rossum705f0f52001-08-24 16:47:00 +00005195
Michael W. Hudson98bbc492002-11-26 14:47:27 +00005196static void
5197update_all_slots(PyTypeObject* type)
5198{
5199 slotdef *p;
5200
5201 init_slotdefs();
5202 for (p = slotdefs; p->name; p++) {
5203 /* update_slot returns int but can't actually fail */
5204 update_slot(type, p->name_strobj);
5205 }
5206}
5207
Guido van Rossum6d204072001-10-21 00:44:31 +00005208/* This function is called by PyType_Ready() to populate the type's
5209 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00005210 function slot (like tp_repr) that's defined in the type, one or more
5211 corresponding descriptors are added in the type's tp_dict dictionary
5212 under the appropriate name (like __repr__). Some function slots
5213 cause more than one descriptor to be added (for example, the nb_add
5214 slot adds both __add__ and __radd__ descriptors) and some function
5215 slots compete for the same descriptor (for example both sq_item and
5216 mp_subscript generate a __getitem__ descriptor).
5217
5218 In the latter case, the first slotdef entry encoutered wins. Since
5219 slotdef entries are sorted by the offset of the slot in the etype
5220 struct, this gives us some control over disambiguating between
5221 competing slots: the members of struct etype are listed from most
5222 general to least general, so the most general slot is preferred. In
5223 particular, because as_mapping comes before as_sequence, for a type
5224 that defines both mp_subscript and sq_item, mp_subscript wins.
5225
5226 This only adds new descriptors and doesn't overwrite entries in
5227 tp_dict that were previously defined. The descriptors contain a
5228 reference to the C function they must call, so that it's safe if they
5229 are copied into a subtype's __dict__ and the subtype has a different
5230 C function in its slot -- calling the method defined by the
5231 descriptor will call the C function that was used to create it,
5232 rather than the C function present in the slot when it is called.
5233 (This is important because a subtype may have a C function in the
5234 slot that calls the method from the dictionary, and we want to avoid
5235 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00005236
5237static int
5238add_operators(PyTypeObject *type)
5239{
5240 PyObject *dict = type->tp_dict;
5241 slotdef *p;
5242 PyObject *descr;
5243 void **ptr;
5244
5245 init_slotdefs();
5246 for (p = slotdefs; p->name; p++) {
5247 if (p->wrapper == NULL)
5248 continue;
5249 ptr = slotptr(type, p->offset);
5250 if (!ptr || !*ptr)
5251 continue;
5252 if (PyDict_GetItem(dict, p->name_strobj))
5253 continue;
5254 descr = PyDescr_NewWrapper(type, p, *ptr);
5255 if (descr == NULL)
5256 return -1;
5257 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
5258 return -1;
5259 Py_DECREF(descr);
5260 }
5261 if (type->tp_new != NULL) {
5262 if (add_tp_new_wrapper(type) < 0)
5263 return -1;
5264 }
5265 return 0;
5266}
5267
Guido van Rossum705f0f52001-08-24 16:47:00 +00005268
5269/* Cooperative 'super' */
5270
5271typedef struct {
5272 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00005273 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005274 PyObject *obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005275 PyTypeObject *obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005276} superobject;
5277
Guido van Rossum6f799372001-09-20 20:46:19 +00005278static PyMemberDef super_members[] = {
5279 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
5280 "the class invoking super()"},
5281 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
5282 "the instance invoking super(); may be None"},
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005283 {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
5284 "the type of the the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005285 {0}
5286};
5287
Guido van Rossum705f0f52001-08-24 16:47:00 +00005288static void
5289super_dealloc(PyObject *self)
5290{
5291 superobject *su = (superobject *)self;
5292
Guido van Rossum048eb752001-10-02 21:24:57 +00005293 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005294 Py_XDECREF(su->obj);
5295 Py_XDECREF(su->type);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005296 Py_XDECREF(su->obj_type);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005297 self->ob_type->tp_free(self);
5298}
5299
5300static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005301super_repr(PyObject *self)
5302{
5303 superobject *su = (superobject *)self;
5304
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005305 if (su->obj_type)
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005306 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005307 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005308 su->type ? su->type->tp_name : "NULL",
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005309 su->obj_type->tp_name);
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005310 else
5311 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005312 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005313 su->type ? su->type->tp_name : "NULL");
5314}
5315
5316static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00005317super_getattro(PyObject *self, PyObject *name)
5318{
5319 superobject *su = (superobject *)self;
5320
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005321 if (su->obj_type != NULL) {
Tim Petersa91e9642001-11-14 23:32:33 +00005322 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005323 PyTypeObject *starttype;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005324 descrgetfunc f;
5325 int i, n;
5326
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005327 starttype = su->obj_type;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005328 mro = starttype->tp_mro;
5329
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005330 if (mro == NULL)
5331 n = 0;
5332 else {
5333 assert(PyTuple_Check(mro));
5334 n = PyTuple_GET_SIZE(mro);
5335 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005336 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00005337 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00005338 break;
5339 }
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005340#if 0
Guido van Rossume705ef12001-08-29 15:47:06 +00005341 if (i >= n && PyType_Check(su->obj)) {
Guido van Rossum155db9a2002-04-02 17:53:47 +00005342 starttype = (PyTypeObject *)(su->obj);
5343 mro = starttype->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005344 if (mro == NULL)
5345 n = 0;
5346 else {
5347 assert(PyTuple_Check(mro));
5348 n = PyTuple_GET_SIZE(mro);
5349 }
Guido van Rossume705ef12001-08-29 15:47:06 +00005350 for (i = 0; i < n; i++) {
5351 if ((PyObject *)(su->type) ==
5352 PyTuple_GET_ITEM(mro, i))
5353 break;
5354 }
Guido van Rossume705ef12001-08-29 15:47:06 +00005355 }
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005356#endif
Guido van Rossum705f0f52001-08-24 16:47:00 +00005357 i++;
5358 res = NULL;
5359 for (; i < n; i++) {
5360 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00005361 if (PyType_Check(tmp))
5362 dict = ((PyTypeObject *)tmp)->tp_dict;
5363 else if (PyClass_Check(tmp))
5364 dict = ((PyClassObject *)tmp)->cl_dict;
5365 else
5366 continue;
5367 res = PyDict_GetItem(dict, name);
Guido van Rossum5b443c62001-12-03 15:38:28 +00005368 if (res != NULL && !PyDescr_IsData(res)) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00005369 Py_INCREF(res);
5370 f = res->ob_type->tp_descr_get;
5371 if (f != NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00005372 tmp = f(res, su->obj,
5373 (PyObject *)starttype);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005374 Py_DECREF(res);
5375 res = tmp;
5376 }
5377 return res;
5378 }
5379 }
5380 }
5381 return PyObject_GenericGetAttr(self, name);
5382}
5383
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005384static PyTypeObject *
Guido van Rossum5b443c62001-12-03 15:38:28 +00005385supercheck(PyTypeObject *type, PyObject *obj)
5386{
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005387 /* Check that a super() call makes sense. Return a type object.
5388
5389 obj can be a new-style class, or an instance of one:
5390
5391 - If it is a class, it must be a subclass of 'type'. This case is
5392 used for class methods; the return value is obj.
5393
5394 - If it is an instance, it must be an instance of 'type'. This is
5395 the normal case; the return value is obj.__class__.
5396
5397 But... when obj is an instance, we want to allow for the case where
5398 obj->ob_type is not a subclass of type, but obj.__class__ is!
5399 This will allow using super() with a proxy for obj.
5400 */
5401
Guido van Rossum8e80a722003-02-18 19:22:22 +00005402 /* Check for first bullet above (special case) */
5403 if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
5404 Py_INCREF(obj);
5405 return (PyTypeObject *)obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005406 }
Guido van Rossum8e80a722003-02-18 19:22:22 +00005407
5408 /* Normal case */
5409 if (PyType_IsSubtype(obj->ob_type, type)) {
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005410 Py_INCREF(obj->ob_type);
5411 return obj->ob_type;
5412 }
5413 else {
5414 /* Try the slow way */
5415 static PyObject *class_str = NULL;
5416 PyObject *class_attr;
5417
5418 if (class_str == NULL) {
5419 class_str = PyString_FromString("__class__");
5420 if (class_str == NULL)
5421 return NULL;
5422 }
5423
5424 class_attr = PyObject_GetAttr(obj, class_str);
5425
5426 if (class_attr != NULL &&
5427 PyType_Check(class_attr) &&
5428 (PyTypeObject *)class_attr != obj->ob_type)
5429 {
5430 int ok = PyType_IsSubtype(
5431 (PyTypeObject *)class_attr, type);
5432 if (ok)
5433 return (PyTypeObject *)class_attr;
5434 }
5435
5436 if (class_attr == NULL)
5437 PyErr_Clear();
5438 else
5439 Py_DECREF(class_attr);
5440 }
5441
Tim Peters97e5ff52003-02-18 19:32:50 +00005442 PyErr_SetString(PyExc_TypeError,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005443 "super(type, obj): "
5444 "obj must be an instance or subtype of type");
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005445 return NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005446}
5447
Guido van Rossum705f0f52001-08-24 16:47:00 +00005448static PyObject *
5449super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5450{
5451 superobject *su = (superobject *)self;
5452 superobject *new;
5453
5454 if (obj == NULL || obj == Py_None || su->obj != NULL) {
5455 /* Not binding to an object, or already bound */
5456 Py_INCREF(self);
5457 return self;
5458 }
Guido van Rossum5b443c62001-12-03 15:38:28 +00005459 if (su->ob_type != &PySuper_Type)
5460 /* If su is an instance of a subclass of super,
5461 call its type */
5462 return PyObject_CallFunction((PyObject *)su->ob_type,
5463 "OO", su->type, obj);
5464 else {
5465 /* Inline the common case */
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005466 PyTypeObject *obj_type = supercheck(su->type, obj);
5467 if (obj_type == NULL)
Guido van Rossum5b443c62001-12-03 15:38:28 +00005468 return NULL;
5469 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
5470 NULL, NULL);
5471 if (new == NULL)
5472 return NULL;
5473 Py_INCREF(su->type);
5474 Py_INCREF(obj);
5475 new->type = su->type;
5476 new->obj = obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005477 new->obj_type = obj_type;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005478 return (PyObject *)new;
5479 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005480}
5481
5482static int
5483super_init(PyObject *self, PyObject *args, PyObject *kwds)
5484{
5485 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00005486 PyTypeObject *type;
5487 PyObject *obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005488 PyTypeObject *obj_type = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005489
5490 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
5491 return -1;
5492 if (obj == Py_None)
5493 obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005494 if (obj != NULL) {
5495 obj_type = supercheck(type, obj);
5496 if (obj_type == NULL)
5497 return -1;
5498 Py_INCREF(obj);
5499 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005500 Py_INCREF(type);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005501 su->type = type;
5502 su->obj = obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005503 su->obj_type = obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005504 return 0;
5505}
5506
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005507PyDoc_STRVAR(super_doc,
Guido van Rossum705f0f52001-08-24 16:47:00 +00005508"super(type) -> unbound super object\n"
5509"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00005510"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00005511"Typical use to call a cooperative superclass method:\n"
5512"class C(B):\n"
5513" def meth(self, arg):\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005514" super(C, self).meth(arg)");
Guido van Rossum705f0f52001-08-24 16:47:00 +00005515
Guido van Rossum048eb752001-10-02 21:24:57 +00005516static int
5517super_traverse(PyObject *self, visitproc visit, void *arg)
5518{
5519 superobject *su = (superobject *)self;
5520 int err;
5521
5522#define VISIT(SLOT) \
5523 if (SLOT) { \
5524 err = visit((PyObject *)(SLOT), arg); \
5525 if (err) \
5526 return err; \
5527 }
5528
5529 VISIT(su->obj);
5530 VISIT(su->type);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005531 VISIT(su->obj_type);
Guido van Rossum048eb752001-10-02 21:24:57 +00005532
5533#undef VISIT
5534
5535 return 0;
5536}
5537
Guido van Rossum705f0f52001-08-24 16:47:00 +00005538PyTypeObject PySuper_Type = {
5539 PyObject_HEAD_INIT(&PyType_Type)
5540 0, /* ob_size */
5541 "super", /* tp_name */
5542 sizeof(superobject), /* tp_basicsize */
5543 0, /* tp_itemsize */
5544 /* methods */
5545 super_dealloc, /* tp_dealloc */
5546 0, /* tp_print */
5547 0, /* tp_getattr */
5548 0, /* tp_setattr */
5549 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005550 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005551 0, /* tp_as_number */
5552 0, /* tp_as_sequence */
5553 0, /* tp_as_mapping */
5554 0, /* tp_hash */
5555 0, /* tp_call */
5556 0, /* tp_str */
5557 super_getattro, /* tp_getattro */
5558 0, /* tp_setattro */
5559 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00005560 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
5561 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005562 super_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00005563 super_traverse, /* tp_traverse */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005564 0, /* tp_clear */
5565 0, /* tp_richcompare */
5566 0, /* tp_weaklistoffset */
5567 0, /* tp_iter */
5568 0, /* tp_iternext */
5569 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005570 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005571 0, /* tp_getset */
5572 0, /* tp_base */
5573 0, /* tp_dict */
5574 super_descr_get, /* tp_descr_get */
5575 0, /* tp_descr_set */
5576 0, /* tp_dictoffset */
5577 super_init, /* tp_init */
5578 PyType_GenericAlloc, /* tp_alloc */
5579 PyType_GenericNew, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00005580 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005581};