blob: 01eb7069f1dc5b61d7275111b1dd9e7ccb893d3c [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 Rossum0628dcf2002-03-14 23:03:14 +00001471/* bozo: __getstate__ that raises TypeError */
1472
1473static PyObject *
1474bozo_func(PyObject *self, PyObject *args)
1475{
1476 PyErr_SetString(PyExc_TypeError,
1477 "a class that defines __slots__ without "
1478 "defining __getstate__ cannot be pickled");
1479 return NULL;
1480}
1481
Neal Norwitz93c1e232002-03-31 16:06:11 +00001482static PyMethodDef bozo_ml = {"__getstate__", bozo_func, METH_VARARGS};
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001483
1484static PyObject *bozo_obj = NULL;
1485
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001486static int
1487valid_identifier(PyObject *s)
1488{
Guido van Rossum03013a02002-07-16 14:30:28 +00001489 unsigned char *p;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001490 int i, n;
1491
1492 if (!PyString_Check(s)) {
1493 PyErr_SetString(PyExc_TypeError,
1494 "__slots__ must be strings");
1495 return 0;
1496 }
Guido van Rossum03013a02002-07-16 14:30:28 +00001497 p = (unsigned char *) PyString_AS_STRING(s);
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001498 n = PyString_GET_SIZE(s);
1499 /* We must reject an empty name. As a hack, we bump the
1500 length to 1 so that the loop will balk on the trailing \0. */
1501 if (n == 0)
1502 n = 1;
1503 for (i = 0; i < n; i++, p++) {
1504 if (!(i == 0 ? isalpha(*p) : isalnum(*p)) && *p != '_') {
1505 PyErr_SetString(PyExc_TypeError,
1506 "__slots__ must be identifiers");
1507 return 0;
1508 }
1509 }
1510 return 1;
1511}
1512
Martin v. Löwisd919a592002-10-14 21:07:28 +00001513#ifdef Py_USING_UNICODE
1514/* Replace Unicode objects in slots. */
1515
1516static PyObject *
1517_unicode_to_string(PyObject *slots, int nslots)
1518{
1519 PyObject *tmp = slots;
1520 PyObject *o, *o1;
1521 int i;
1522 intintargfunc copy = slots->ob_type->tp_as_sequence->sq_slice;
1523 for (i = 0; i < nslots; i++) {
1524 if (PyUnicode_Check(o = PyTuple_GET_ITEM(tmp, i))) {
1525 if (tmp == slots) {
1526 tmp = copy(slots, 0, PyTuple_GET_SIZE(slots));
1527 if (tmp == NULL)
1528 return NULL;
1529 }
1530 o1 = _PyUnicode_AsDefaultEncodedString
1531 (o, NULL);
1532 if (o1 == NULL) {
1533 Py_DECREF(tmp);
1534 return 0;
1535 }
1536 Py_INCREF(o1);
1537 Py_DECREF(o);
1538 PyTuple_SET_ITEM(tmp, i, o1);
1539 }
1540 }
1541 return tmp;
1542}
1543#endif
1544
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001545static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001546type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
1547{
1548 PyObject *name, *bases, *dict;
1549 static char *kwlist[] = {"name", "bases", "dict", 0};
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001550 PyObject *slots, *tmp, *newslots;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001551 PyTypeObject *type, *base, *tmptype, *winner;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001552 etype *et;
Guido van Rossum6f799372001-09-20 20:46:19 +00001553 PyMemberDef *mp;
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001554 int i, nbases, nslots, slotoffset, add_dict, add_weak;
Guido van Rossumad47da02002-08-12 19:05:44 +00001555 int j, may_add_dict, may_add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001556
Tim Peters3abca122001-10-27 19:37:48 +00001557 assert(args != NULL && PyTuple_Check(args));
1558 assert(kwds == NULL || PyDict_Check(kwds));
1559
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001560 /* Special case: type(x) should return x->ob_type */
Tim Peters3abca122001-10-27 19:37:48 +00001561 {
1562 const int nargs = PyTuple_GET_SIZE(args);
1563 const int nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
1564
1565 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
1566 PyObject *x = PyTuple_GET_ITEM(args, 0);
1567 Py_INCREF(x->ob_type);
1568 return (PyObject *) x->ob_type;
1569 }
1570
1571 /* SF bug 475327 -- if that didn't trigger, we need 3
1572 arguments. but PyArg_ParseTupleAndKeywords below may give
1573 a msg saying type() needs exactly 3. */
1574 if (nargs + nkwds != 3) {
1575 PyErr_SetString(PyExc_TypeError,
1576 "type() takes 1 or 3 arguments");
1577 return NULL;
1578 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001579 }
1580
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001581 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001582 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
1583 &name,
1584 &PyTuple_Type, &bases,
1585 &PyDict_Type, &dict))
1586 return NULL;
1587
1588 /* Determine the proper metatype to deal with this,
1589 and check for metatype conflicts while we're at it.
1590 Note that if some other metatype wins to contract,
1591 it's possible that its instances are not types. */
1592 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001593 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001594 for (i = 0; i < nbases; i++) {
1595 tmp = PyTuple_GET_ITEM(bases, i);
1596 tmptype = tmp->ob_type;
Tim Petersa91e9642001-11-14 23:32:33 +00001597 if (tmptype == &PyClass_Type)
1598 continue; /* Special case classic classes */
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001599 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001600 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001601 if (PyType_IsSubtype(tmptype, winner)) {
1602 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001603 continue;
1604 }
1605 PyErr_SetString(PyExc_TypeError,
1606 "metatype conflict among bases");
1607 return NULL;
1608 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001609 if (winner != metatype) {
1610 if (winner->tp_new != type_new) /* Pass it to the winner */
1611 return winner->tp_new(winner, args, kwds);
1612 metatype = winner;
1613 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001614
1615 /* Adjust for empty tuple bases */
1616 if (nbases == 0) {
1617 bases = Py_BuildValue("(O)", &PyBaseObject_Type);
1618 if (bases == NULL)
1619 return NULL;
1620 nbases = 1;
1621 }
1622 else
1623 Py_INCREF(bases);
1624
1625 /* XXX From here until type is allocated, "return NULL" leaks bases! */
1626
1627 /* Calculate best base, and check that all bases are type objects */
1628 base = best_base(bases);
1629 if (base == NULL)
1630 return NULL;
1631 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
1632 PyErr_Format(PyExc_TypeError,
1633 "type '%.100s' is not an acceptable base type",
1634 base->tp_name);
1635 return NULL;
1636 }
1637
Tim Peters6d6c1a32001-08-02 04:15:00 +00001638 /* Check for a __slots__ sequence variable in dict, and count it */
1639 slots = PyDict_GetItemString(dict, "__slots__");
1640 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +00001641 add_dict = 0;
1642 add_weak = 0;
Guido van Rossumad47da02002-08-12 19:05:44 +00001643 may_add_dict = base->tp_dictoffset == 0;
1644 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
1645 if (slots == NULL) {
1646 if (may_add_dict) {
1647 add_dict++;
1648 }
1649 if (may_add_weak) {
1650 add_weak++;
1651 }
1652 }
1653 else {
1654 /* Have slots */
1655
Tim Peters6d6c1a32001-08-02 04:15:00 +00001656 /* Make it into a tuple */
1657 if (PyString_Check(slots))
1658 slots = Py_BuildValue("(O)", slots);
1659 else
1660 slots = PySequence_Tuple(slots);
1661 if (slots == NULL)
1662 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00001663 assert(PyTuple_Check(slots));
1664
1665 /* Are slots allowed? */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001666 nslots = PyTuple_GET_SIZE(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +00001667 if (nslots > 0 && base->tp_itemsize != 0) {
1668 PyErr_Format(PyExc_TypeError,
1669 "nonempty __slots__ "
1670 "not supported for subtype of '%s'",
1671 base->tp_name);
Guido van Rossumad47da02002-08-12 19:05:44 +00001672 bad_slots:
1673 Py_DECREF(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +00001674 return NULL;
1675 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001676
Martin v. Löwisd919a592002-10-14 21:07:28 +00001677#ifdef Py_USING_UNICODE
1678 tmp = _unicode_to_string(slots, nslots);
Martin v. Löwis13b1a5c2002-10-14 21:11:34 +00001679 if (tmp != slots) {
1680 Py_DECREF(slots);
1681 slots = tmp;
1682 }
Martin v. Löwisd919a592002-10-14 21:07:28 +00001683 if (!tmp)
1684 return NULL;
1685#endif
Guido van Rossumad47da02002-08-12 19:05:44 +00001686 /* Check for valid slot names and two special cases */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001687 for (i = 0; i < nslots; i++) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001688 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
1689 char *s;
1690 if (!valid_identifier(tmp))
1691 goto bad_slots;
1692 assert(PyString_Check(tmp));
1693 s = PyString_AS_STRING(tmp);
1694 if (strcmp(s, "__dict__") == 0) {
1695 if (!may_add_dict || add_dict) {
1696 PyErr_SetString(PyExc_TypeError,
1697 "__dict__ slot disallowed: "
1698 "we already got one");
1699 goto bad_slots;
1700 }
1701 add_dict++;
1702 }
1703 if (strcmp(s, "__weakref__") == 0) {
1704 if (!may_add_weak || add_weak) {
1705 PyErr_SetString(PyExc_TypeError,
1706 "__weakref__ slot disallowed: "
1707 "either we already got one, "
1708 "or __itemsize__ != 0");
1709 goto bad_slots;
1710 }
1711 add_weak++;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001712 }
1713 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001714
Guido van Rossumad47da02002-08-12 19:05:44 +00001715 /* Copy slots into yet another tuple, demangling names */
1716 newslots = PyTuple_New(nslots - add_dict - add_weak);
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001717 if (newslots == NULL)
Guido van Rossumad47da02002-08-12 19:05:44 +00001718 goto bad_slots;
1719 for (i = j = 0; i < nslots; i++) {
1720 char *s;
Guido van Rossum8e829202002-08-16 03:47:49 +00001721 char buffer[256];
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001722 tmp = PyTuple_GET_ITEM(slots, i);
Guido van Rossumad47da02002-08-12 19:05:44 +00001723 s = PyString_AS_STRING(tmp);
1724 if ((add_dict && strcmp(s, "__dict__") == 0) ||
1725 (add_weak && strcmp(s, "__weakref__") == 0))
1726 continue;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001727 if (_Py_Mangle(PyString_AS_STRING(name),
Guido van Rossumad47da02002-08-12 19:05:44 +00001728 PyString_AS_STRING(tmp),
1729 buffer, sizeof(buffer)))
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001730 {
1731 tmp = PyString_FromString(buffer);
1732 } else {
1733 Py_INCREF(tmp);
1734 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001735 PyTuple_SET_ITEM(newslots, j, tmp);
1736 j++;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001737 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001738 assert(j == nslots - add_dict - add_weak);
1739 nslots = j;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001740 Py_DECREF(slots);
1741 slots = newslots;
1742
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001743 /* See if *this* class defines __getstate__ */
Guido van Rossumad47da02002-08-12 19:05:44 +00001744 if (PyDict_GetItemString(dict, "__getstate__") == NULL) {
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001745 /* If not, provide a bozo that raises TypeError */
1746 if (bozo_obj == NULL) {
1747 bozo_obj = PyCFunction_New(&bozo_ml, NULL);
Guido van Rossumad47da02002-08-12 19:05:44 +00001748 if (bozo_obj == NULL)
1749 goto bad_slots;
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001750 }
1751 if (PyDict_SetItemString(dict,
1752 "__getstate__",
Guido van Rossumad47da02002-08-12 19:05:44 +00001753 bozo_obj) < 0)
1754 {
1755 Py_DECREF(bozo_obj);
1756 goto bad_slots;
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001757 }
1758 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001759
1760 /* Secondary bases may provide weakrefs or dict */
1761 if (nbases > 1 &&
1762 ((may_add_dict && !add_dict) ||
1763 (may_add_weak && !add_weak))) {
1764 for (i = 0; i < nbases; i++) {
1765 tmp = PyTuple_GET_ITEM(bases, i);
1766 if (tmp == (PyObject *)base)
1767 continue; /* Skip primary base */
1768 if (PyClass_Check(tmp)) {
1769 /* Classic base class provides both */
1770 if (may_add_dict && !add_dict)
1771 add_dict++;
1772 if (may_add_weak && !add_weak)
1773 add_weak++;
1774 break;
1775 }
1776 assert(PyType_Check(tmp));
1777 tmptype = (PyTypeObject *)tmp;
1778 if (may_add_dict && !add_dict &&
1779 tmptype->tp_dictoffset != 0)
1780 add_dict++;
1781 if (may_add_weak && !add_weak &&
1782 tmptype->tp_weaklistoffset != 0)
1783 add_weak++;
1784 if (may_add_dict && !add_dict)
1785 continue;
1786 if (may_add_weak && !add_weak)
1787 continue;
1788 /* Nothing more to check */
1789 break;
1790 }
1791 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001792 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001793
1794 /* XXX From here until type is safely allocated,
1795 "return NULL" may leak slots! */
1796
1797 /* Allocate the type object */
1798 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
Guido van Rossumad47da02002-08-12 19:05:44 +00001799 if (type == NULL) {
1800 Py_XDECREF(slots);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001801 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00001802 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001803
1804 /* Keep name and slots alive in the extended type object */
1805 et = (etype *)type;
1806 Py_INCREF(name);
1807 et->name = name;
1808 et->slots = slots;
1809
Guido van Rossumdc91b992001-08-08 22:26:22 +00001810 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001811 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
1812 Py_TPFLAGS_BASETYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00001813 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
1814 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00001815
1816 /* It's a new-style number unless it specifically inherits any
1817 old-style numeric behavior */
1818 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
1819 (base->tp_as_number == NULL))
1820 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
1821
1822 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001823 type->tp_as_number = &et->as_number;
1824 type->tp_as_sequence = &et->as_sequence;
1825 type->tp_as_mapping = &et->as_mapping;
1826 type->tp_as_buffer = &et->as_buffer;
1827 type->tp_name = PyString_AS_STRING(name);
1828
1829 /* Set tp_base and tp_bases */
1830 type->tp_bases = bases;
1831 Py_INCREF(base);
1832 type->tp_base = base;
1833
Guido van Rossum687ae002001-10-15 22:03:32 +00001834 /* Initialize tp_dict from passed-in dict */
1835 type->tp_dict = dict = PyDict_Copy(dict);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001836 if (dict == NULL) {
1837 Py_DECREF(type);
1838 return NULL;
1839 }
1840
Guido van Rossumc3542212001-08-16 09:18:56 +00001841 /* Set __module__ in the dict */
1842 if (PyDict_GetItemString(dict, "__module__") == NULL) {
1843 tmp = PyEval_GetGlobals();
1844 if (tmp != NULL) {
1845 tmp = PyDict_GetItemString(tmp, "__name__");
1846 if (tmp != NULL) {
1847 if (PyDict_SetItemString(dict, "__module__",
1848 tmp) < 0)
1849 return NULL;
1850 }
1851 }
1852 }
1853
Tim Peters2f93e282001-10-04 05:27:00 +00001854 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
Tim Peters24008312002-03-17 18:56:20 +00001855 and is a string. The __doc__ accessor will first look for tp_doc;
1856 if that fails, it will still look into __dict__.
Tim Peters2f93e282001-10-04 05:27:00 +00001857 */
1858 {
1859 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
1860 if (doc != NULL && PyString_Check(doc)) {
1861 const size_t n = (size_t)PyString_GET_SIZE(doc);
Tim Peters59f809d2001-10-04 05:43:02 +00001862 type->tp_doc = (char *)PyObject_MALLOC(n+1);
Tim Peters2f93e282001-10-04 05:27:00 +00001863 if (type->tp_doc == NULL) {
1864 Py_DECREF(type);
1865 return NULL;
1866 }
1867 memcpy(type->tp_doc, PyString_AS_STRING(doc), n+1);
1868 }
1869 }
1870
Tim Peters6d6c1a32001-08-02 04:15:00 +00001871 /* Special-case __new__: if it's a plain function,
1872 make it a static function */
1873 tmp = PyDict_GetItemString(dict, "__new__");
1874 if (tmp != NULL && PyFunction_Check(tmp)) {
1875 tmp = PyStaticMethod_New(tmp);
1876 if (tmp == NULL) {
1877 Py_DECREF(type);
1878 return NULL;
1879 }
1880 PyDict_SetItemString(dict, "__new__", tmp);
1881 Py_DECREF(tmp);
1882 }
1883
1884 /* Add descriptors for custom slots from __slots__, or for __dict__ */
1885 mp = et->members;
Neil Schemenauerc806c882001-08-29 23:54:54 +00001886 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001887 if (slots != NULL) {
1888 for (i = 0; i < nslots; i++, mp++) {
1889 mp->name = PyString_AS_STRING(
1890 PyTuple_GET_ITEM(slots, i));
Guido van Rossum64b206c2001-12-04 17:13:22 +00001891 mp->type = T_OBJECT_EX;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001892 mp->offset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +00001893 if (base->tp_weaklistoffset == 0 &&
Guido van Rossum64b206c2001-12-04 17:13:22 +00001894 strcmp(mp->name, "__weakref__") == 0) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001895 add_weak++;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001896 mp->type = T_OBJECT;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001897 mp->flags = READONLY;
Guido van Rossum9676b222001-08-17 20:32:36 +00001898 type->tp_weaklistoffset = slotoffset;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001899 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001900 slotoffset += sizeof(PyObject *);
1901 }
1902 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001903 if (add_dict) {
1904 if (base->tp_itemsize)
1905 type->tp_dictoffset = -(long)sizeof(PyObject *);
1906 else
1907 type->tp_dictoffset = slotoffset;
1908 slotoffset += sizeof(PyObject *);
1909 }
1910 if (add_weak) {
1911 assert(!base->tp_itemsize);
1912 type->tp_weaklistoffset = slotoffset;
1913 slotoffset += sizeof(PyObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001914 }
1915 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001916 type->tp_itemsize = base->tp_itemsize;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001917 type->tp_members = et->members;
Guido van Rossum373c7412003-01-07 13:41:37 +00001918
1919 if (type->tp_weaklistoffset && type->tp_dictoffset)
1920 type->tp_getset = subtype_getsets_full;
1921 else if (type->tp_weaklistoffset && !type->tp_dictoffset)
1922 type->tp_getset = subtype_getsets_weakref_only;
1923 else if (!type->tp_weaklistoffset && type->tp_dictoffset)
1924 type->tp_getset = subtype_getsets_dict_only;
1925 else
1926 type->tp_getset = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001927
1928 /* Special case some slots */
1929 if (type->tp_dictoffset != 0 || nslots > 0) {
1930 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
1931 type->tp_getattro = PyObject_GenericGetAttr;
1932 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
1933 type->tp_setattro = PyObject_GenericSetAttr;
1934 }
1935 type->tp_dealloc = subtype_dealloc;
1936
Guido van Rossum9475a232001-10-05 20:51:39 +00001937 /* Enable GC unless there are really no instance variables possible */
1938 if (!(type->tp_basicsize == sizeof(PyObject) &&
1939 type->tp_itemsize == 0))
1940 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
1941
Tim Peters6d6c1a32001-08-02 04:15:00 +00001942 /* Always override allocation strategy to use regular heap */
1943 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00001944 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001945 type->tp_free = PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00001946 type->tp_traverse = subtype_traverse;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001947 type->tp_clear = subtype_clear;
Guido van Rossum048eb752001-10-02 21:24:57 +00001948 }
1949 else
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001950 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001951
1952 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001953 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001954 Py_DECREF(type);
1955 return NULL;
1956 }
1957
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001958 /* Put the proper slots in place */
1959 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00001960
Tim Peters6d6c1a32001-08-02 04:15:00 +00001961 return (PyObject *)type;
1962}
1963
1964/* Internal API to look for a name through the MRO.
1965 This returns a borrowed reference, and doesn't set an exception! */
1966PyObject *
1967_PyType_Lookup(PyTypeObject *type, PyObject *name)
1968{
1969 int i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00001970 PyObject *mro, *res, *base, *dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001971
Guido van Rossum687ae002001-10-15 22:03:32 +00001972 /* Look in tp_dict of types in MRO */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001973 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00001974
1975 /* If mro is NULL, the type is either not yet initialized
1976 by PyType_Ready(), or already cleared by type_clear().
1977 Either way the safest thing to do is to return NULL. */
1978 if (mro == NULL)
1979 return NULL;
1980
Tim Peters6d6c1a32001-08-02 04:15:00 +00001981 assert(PyTuple_Check(mro));
1982 n = PyTuple_GET_SIZE(mro);
1983 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001984 base = PyTuple_GET_ITEM(mro, i);
1985 if (PyClass_Check(base))
1986 dict = ((PyClassObject *)base)->cl_dict;
1987 else {
1988 assert(PyType_Check(base));
1989 dict = ((PyTypeObject *)base)->tp_dict;
1990 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001991 assert(dict && PyDict_Check(dict));
1992 res = PyDict_GetItem(dict, name);
1993 if (res != NULL)
1994 return res;
1995 }
1996 return NULL;
1997}
1998
1999/* This is similar to PyObject_GenericGetAttr(),
2000 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
2001static PyObject *
2002type_getattro(PyTypeObject *type, PyObject *name)
2003{
2004 PyTypeObject *metatype = type->ob_type;
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002005 PyObject *meta_attribute, *attribute;
2006 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002007
2008 /* Initialize this type (we'll assume the metatype is initialized) */
2009 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002010 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002011 return NULL;
2012 }
2013
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002014 /* No readable descriptor found yet */
2015 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00002016
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002017 /* Look for the attribute in the metatype */
2018 meta_attribute = _PyType_Lookup(metatype, name);
2019
2020 if (meta_attribute != NULL) {
2021 meta_get = meta_attribute->ob_type->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00002022
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002023 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
2024 /* Data descriptors implement tp_descr_set to intercept
2025 * writes. Assume the attribute is not overridden in
2026 * type's tp_dict (and bases): call the descriptor now.
2027 */
2028 return meta_get(meta_attribute, (PyObject *)type,
2029 (PyObject *)metatype);
2030 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002031 }
2032
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002033 /* No data descriptor found on metatype. Look in tp_dict of this
2034 * type and its bases */
2035 attribute = _PyType_Lookup(type, name);
2036 if (attribute != NULL) {
2037 /* Implement descriptor functionality, if any */
2038 descrgetfunc local_get = attribute->ob_type->tp_descr_get;
2039 if (local_get != NULL) {
2040 /* NULL 2nd argument indicates the descriptor was
2041 * found on the target object itself (or a base) */
2042 return local_get(attribute, (PyObject *)NULL,
2043 (PyObject *)type);
2044 }
Tim Peters34592512002-07-11 06:23:50 +00002045
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002046 Py_INCREF(attribute);
2047 return attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002048 }
2049
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002050 /* No attribute found in local __dict__ (or bases): use the
2051 * descriptor from the metatype, if any */
2052 if (meta_get != NULL)
2053 return meta_get(meta_attribute, (PyObject *)type,
2054 (PyObject *)metatype);
2055
2056 /* If an ordinary attribute was found on the metatype, return it now */
2057 if (meta_attribute != NULL) {
2058 Py_INCREF(meta_attribute);
2059 return meta_attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002060 }
2061
2062 /* Give up */
2063 PyErr_Format(PyExc_AttributeError,
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002064 "type object '%.50s' has no attribute '%.400s'",
2065 type->tp_name, PyString_AS_STRING(name));
Tim Peters6d6c1a32001-08-02 04:15:00 +00002066 return NULL;
2067}
2068
2069static int
2070type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
2071{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002072 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2073 PyErr_Format(
2074 PyExc_TypeError,
2075 "can't set attributes of built-in/extension type '%s'",
2076 type->tp_name);
2077 return -1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002078 }
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002079 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
2080 return -1;
2081 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002082}
2083
2084static void
2085type_dealloc(PyTypeObject *type)
2086{
2087 etype *et;
2088
2089 /* Assert this is a heap-allocated type object */
2090 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002091 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00002092 PyObject_ClearWeakRefs((PyObject *)type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002093 et = (etype *)type;
2094 Py_XDECREF(type->tp_base);
2095 Py_XDECREF(type->tp_dict);
2096 Py_XDECREF(type->tp_bases);
2097 Py_XDECREF(type->tp_mro);
Guido van Rossum687ae002001-10-15 22:03:32 +00002098 Py_XDECREF(type->tp_cache);
Guido van Rossum1c450732001-10-08 15:18:27 +00002099 Py_XDECREF(type->tp_subclasses);
Neal Norwitzcee5ca02002-07-30 00:42:06 +00002100 PyObject_Free(type->tp_doc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002101 Py_XDECREF(et->name);
2102 Py_XDECREF(et->slots);
2103 type->ob_type->tp_free((PyObject *)type);
2104}
2105
Guido van Rossum1c450732001-10-08 15:18:27 +00002106static PyObject *
2107type_subclasses(PyTypeObject *type, PyObject *args_ignored)
2108{
2109 PyObject *list, *raw, *ref;
2110 int i, n;
2111
2112 list = PyList_New(0);
2113 if (list == NULL)
2114 return NULL;
2115 raw = type->tp_subclasses;
2116 if (raw == NULL)
2117 return list;
2118 assert(PyList_Check(raw));
2119 n = PyList_GET_SIZE(raw);
2120 for (i = 0; i < n; i++) {
2121 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00002122 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00002123 ref = PyWeakref_GET_OBJECT(ref);
2124 if (ref != Py_None) {
2125 if (PyList_Append(list, ref) < 0) {
2126 Py_DECREF(list);
2127 return NULL;
2128 }
2129 }
2130 }
2131 return list;
2132}
2133
Tim Peters6d6c1a32001-08-02 04:15:00 +00002134static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002135 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002136 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
Guido van Rossum1c450732001-10-08 15:18:27 +00002137 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002138 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002139 {0}
2140};
2141
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002142PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002143"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002144"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002145
Guido van Rossum048eb752001-10-02 21:24:57 +00002146static int
2147type_traverse(PyTypeObject *type, visitproc visit, void *arg)
2148{
Guido van Rossum048eb752001-10-02 21:24:57 +00002149 int err;
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 VISIT(SLOT) \
2156 if (SLOT) { \
2157 err = visit((PyObject *)(SLOT), arg); \
2158 if (err) \
2159 return err; \
2160 }
2161
2162 VISIT(type->tp_dict);
Guido van Rossum687ae002001-10-15 22:03:32 +00002163 VISIT(type->tp_cache);
Guido van Rossum048eb752001-10-02 21:24:57 +00002164 VISIT(type->tp_mro);
2165 VISIT(type->tp_bases);
2166 VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00002167
2168 /* There's no need to visit type->tp_subclasses or
2169 ((etype *)type)->slots, because they can't be involved
2170 in cycles; tp_subclasses is a list of weak references,
2171 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00002172
2173#undef VISIT
2174
2175 return 0;
2176}
2177
2178static int
2179type_clear(PyTypeObject *type)
2180{
Guido van Rossum048eb752001-10-02 21:24:57 +00002181 PyObject *tmp;
2182
Guido van Rossuma3862092002-06-10 15:24:42 +00002183 /* Because of type_is_gc(), the collector only calls this
2184 for heaptypes. */
2185 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002186
2187#define CLEAR(SLOT) \
2188 if (SLOT) { \
2189 tmp = (PyObject *)(SLOT); \
2190 SLOT = NULL; \
2191 Py_DECREF(tmp); \
2192 }
2193
Guido van Rossuma3862092002-06-10 15:24:42 +00002194 /* The only field we need to clear is tp_mro, which is part of a
2195 hard cycle (its first element is the class itself) that won't
2196 be broken otherwise (it's a tuple and tuples don't have a
2197 tp_clear handler). None of the other fields need to be
2198 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00002199
Guido van Rossuma3862092002-06-10 15:24:42 +00002200 tp_dict:
2201 It is a dict, so the collector will call its tp_clear.
2202
2203 tp_cache:
2204 Not used; if it were, it would be a dict.
2205
2206 tp_bases, tp_base:
2207 If these are involved in a cycle, there must be at least
2208 one other, mutable object in the cycle, e.g. a base
2209 class's dict; the cycle will be broken that way.
2210
2211 tp_subclasses:
2212 A list of weak references can't be part of a cycle; and
2213 lists have their own tp_clear.
2214
2215 slots (in etype):
2216 A tuple of strings can't be part of a cycle.
2217 */
2218
2219 CLEAR(type->tp_mro);
Tim Peters2f93e282001-10-04 05:27:00 +00002220
Guido van Rossum048eb752001-10-02 21:24:57 +00002221#undef CLEAR
2222
2223 return 0;
2224}
2225
2226static int
2227type_is_gc(PyTypeObject *type)
2228{
2229 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
2230}
2231
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002232PyTypeObject PyType_Type = {
2233 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002234 0, /* ob_size */
2235 "type", /* tp_name */
2236 sizeof(etype), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00002237 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002238 (destructor)type_dealloc, /* tp_dealloc */
2239 0, /* tp_print */
2240 0, /* tp_getattr */
2241 0, /* tp_setattr */
2242 type_compare, /* tp_compare */
2243 (reprfunc)type_repr, /* tp_repr */
2244 0, /* tp_as_number */
2245 0, /* tp_as_sequence */
2246 0, /* tp_as_mapping */
2247 (hashfunc)_Py_HashPointer, /* tp_hash */
2248 (ternaryfunc)type_call, /* tp_call */
2249 0, /* tp_str */
2250 (getattrofunc)type_getattro, /* tp_getattro */
2251 (setattrofunc)type_setattro, /* tp_setattro */
2252 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00002253 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2254 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002255 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00002256 (traverseproc)type_traverse, /* tp_traverse */
2257 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002258 0, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00002259 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002260 0, /* tp_iter */
2261 0, /* tp_iternext */
2262 type_methods, /* tp_methods */
2263 type_members, /* tp_members */
2264 type_getsets, /* tp_getset */
2265 0, /* tp_base */
2266 0, /* tp_dict */
2267 0, /* tp_descr_get */
2268 0, /* tp_descr_set */
2269 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
2270 0, /* tp_init */
2271 0, /* tp_alloc */
2272 type_new, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002273 PyObject_GC_Del, /* tp_free */
Guido van Rossum048eb752001-10-02 21:24:57 +00002274 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002275};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002276
2277
2278/* The base type of all types (eventually)... except itself. */
2279
2280static int
2281object_init(PyObject *self, PyObject *args, PyObject *kwds)
2282{
2283 return 0;
2284}
2285
2286static void
2287object_dealloc(PyObject *self)
2288{
2289 self->ob_type->tp_free(self);
2290}
2291
Guido van Rossum8e248182001-08-12 05:17:56 +00002292static PyObject *
2293object_repr(PyObject *self)
2294{
Guido van Rossum76e69632001-08-16 18:52:43 +00002295 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00002296 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002297
Guido van Rossum76e69632001-08-16 18:52:43 +00002298 type = self->ob_type;
2299 mod = type_module(type, NULL);
2300 if (mod == NULL)
2301 PyErr_Clear();
2302 else if (!PyString_Check(mod)) {
2303 Py_DECREF(mod);
2304 mod = NULL;
2305 }
2306 name = type_name(type, NULL);
2307 if (name == NULL)
2308 return NULL;
2309 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002310 rtn = PyString_FromFormat("<%s.%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002311 PyString_AS_STRING(mod),
2312 PyString_AS_STRING(name),
2313 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002314 else
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002315 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002316 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002317 Py_XDECREF(mod);
2318 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00002319 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002320}
2321
Guido van Rossumb8f63662001-08-15 23:57:02 +00002322static PyObject *
2323object_str(PyObject *self)
2324{
2325 unaryfunc f;
2326
2327 f = self->ob_type->tp_repr;
2328 if (f == NULL)
2329 f = object_repr;
2330 return f(self);
2331}
2332
Guido van Rossum8e248182001-08-12 05:17:56 +00002333static long
2334object_hash(PyObject *self)
2335{
2336 return _Py_HashPointer(self);
2337}
Guido van Rossum8e248182001-08-12 05:17:56 +00002338
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002339static PyObject *
2340object_get_class(PyObject *self, void *closure)
2341{
2342 Py_INCREF(self->ob_type);
2343 return (PyObject *)(self->ob_type);
2344}
2345
2346static int
2347equiv_structs(PyTypeObject *a, PyTypeObject *b)
2348{
2349 return a == b ||
2350 (a != NULL &&
2351 b != NULL &&
2352 a->tp_basicsize == b->tp_basicsize &&
2353 a->tp_itemsize == b->tp_itemsize &&
2354 a->tp_dictoffset == b->tp_dictoffset &&
2355 a->tp_weaklistoffset == b->tp_weaklistoffset &&
2356 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
2357 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
2358}
2359
2360static int
2361same_slots_added(PyTypeObject *a, PyTypeObject *b)
2362{
2363 PyTypeObject *base = a->tp_base;
2364 int size;
2365
2366 if (base != b->tp_base)
2367 return 0;
2368 if (equiv_structs(a, base) && equiv_structs(b, base))
2369 return 1;
2370 size = base->tp_basicsize;
2371 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
2372 size += sizeof(PyObject *);
2373 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
2374 size += sizeof(PyObject *);
2375 return size == a->tp_basicsize && size == b->tp_basicsize;
2376}
2377
2378static int
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002379compatible_for_assignment(PyTypeObject* old, PyTypeObject* new, char* attr)
2380{
2381 PyTypeObject *newbase, *oldbase;
2382
2383 if (new->tp_dealloc != old->tp_dealloc ||
2384 new->tp_free != old->tp_free)
2385 {
2386 PyErr_Format(PyExc_TypeError,
2387 "%s assignment: "
2388 "'%s' deallocator differs from '%s'",
2389 attr,
2390 new->tp_name,
2391 old->tp_name);
2392 return 0;
2393 }
2394 newbase = new;
2395 oldbase = old;
2396 while (equiv_structs(newbase, newbase->tp_base))
2397 newbase = newbase->tp_base;
2398 while (equiv_structs(oldbase, oldbase->tp_base))
2399 oldbase = oldbase->tp_base;
2400 if (newbase != oldbase &&
2401 (newbase->tp_base != oldbase->tp_base ||
2402 !same_slots_added(newbase, oldbase))) {
2403 PyErr_Format(PyExc_TypeError,
2404 "%s assignment: "
2405 "'%s' object layout differs from '%s'",
2406 attr,
2407 new->tp_name,
2408 old->tp_name);
2409 return 0;
2410 }
Tim Petersea7f75d2002-12-07 21:39:16 +00002411
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002412 return 1;
2413}
2414
2415static int
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002416object_set_class(PyObject *self, PyObject *value, void *closure)
2417{
2418 PyTypeObject *old = self->ob_type;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002419 PyTypeObject *new;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002420
Guido van Rossumb6b89422002-04-15 01:03:30 +00002421 if (value == NULL) {
2422 PyErr_SetString(PyExc_TypeError,
2423 "can't delete __class__ attribute");
2424 return -1;
2425 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002426 if (!PyType_Check(value)) {
2427 PyErr_Format(PyExc_TypeError,
2428 "__class__ must be set to new-style class, not '%s' object",
2429 value->ob_type->tp_name);
2430 return -1;
2431 }
2432 new = (PyTypeObject *)value;
Guido van Rossum40af8892002-08-10 05:42:07 +00002433 if (!(new->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
2434 !(old->tp_flags & Py_TPFLAGS_HEAPTYPE))
2435 {
2436 PyErr_Format(PyExc_TypeError,
2437 "__class__ assignment: only for heap types");
2438 return -1;
2439 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002440 if (compatible_for_assignment(new, old, "__class__")) {
2441 Py_INCREF(new);
2442 self->ob_type = new;
2443 Py_DECREF(old);
2444 return 0;
2445 }
2446 else {
Guido van Rossum9ee4b942002-05-24 18:47:47 +00002447 return -1;
2448 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002449}
2450
2451static PyGetSetDef object_getsets[] = {
2452 {"__class__", object_get_class, object_set_class,
Neal Norwitz858e34f2002-08-13 17:18:45 +00002453 PyDoc_STR("the object's class")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002454 {0}
2455};
2456
Guido van Rossum3926a632001-09-25 16:25:58 +00002457static PyObject *
2458object_reduce(PyObject *self, PyObject *args)
2459{
2460 /* Call copy_reg._reduce(self) */
2461 static PyObject *copy_reg_str;
2462 PyObject *copy_reg, *res;
2463
2464 if (!copy_reg_str) {
2465 copy_reg_str = PyString_InternFromString("copy_reg");
2466 if (copy_reg_str == NULL)
2467 return NULL;
2468 }
2469 copy_reg = PyImport_Import(copy_reg_str);
2470 if (!copy_reg)
2471 return NULL;
2472 res = PyEval_CallMethod(copy_reg, "_reduce", "(O)", self);
2473 Py_DECREF(copy_reg);
2474 return res;
2475}
2476
2477static PyMethodDef object_methods[] = {
Tim Petersea7f75d2002-12-07 21:39:16 +00002478 {"__reduce__", object_reduce, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002479 PyDoc_STR("helper for pickle")},
Guido van Rossum3926a632001-09-25 16:25:58 +00002480 {0}
2481};
2482
Tim Peters6d6c1a32001-08-02 04:15:00 +00002483PyTypeObject PyBaseObject_Type = {
2484 PyObject_HEAD_INIT(&PyType_Type)
2485 0, /* ob_size */
2486 "object", /* tp_name */
2487 sizeof(PyObject), /* tp_basicsize */
2488 0, /* tp_itemsize */
2489 (destructor)object_dealloc, /* tp_dealloc */
2490 0, /* tp_print */
2491 0, /* tp_getattr */
2492 0, /* tp_setattr */
2493 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002494 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002495 0, /* tp_as_number */
2496 0, /* tp_as_sequence */
2497 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002498 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002499 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002500 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002501 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002502 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002503 0, /* tp_as_buffer */
2504 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002505 PyDoc_STR("The most base type"), /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002506 0, /* tp_traverse */
2507 0, /* tp_clear */
2508 0, /* tp_richcompare */
2509 0, /* tp_weaklistoffset */
2510 0, /* tp_iter */
2511 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00002512 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002513 0, /* tp_members */
2514 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002515 0, /* tp_base */
2516 0, /* tp_dict */
2517 0, /* tp_descr_get */
2518 0, /* tp_descr_set */
2519 0, /* tp_dictoffset */
2520 object_init, /* tp_init */
2521 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossumc11e1922001-08-09 19:38:15 +00002522 PyType_GenericNew, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002523 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002524};
2525
2526
2527/* Initialize the __dict__ in a type object */
2528
Fred Drake7bf97152002-03-28 05:33:33 +00002529static PyObject *
2530create_specialmethod(PyMethodDef *meth, PyObject *(*func)(PyObject *))
2531{
2532 PyObject *cfunc;
2533 PyObject *result;
2534
2535 cfunc = PyCFunction_New(meth, NULL);
2536 if (cfunc == NULL)
2537 return NULL;
2538 result = func(cfunc);
2539 Py_DECREF(cfunc);
2540 return result;
2541}
2542
Tim Peters6d6c1a32001-08-02 04:15:00 +00002543static int
2544add_methods(PyTypeObject *type, PyMethodDef *meth)
2545{
Guido van Rossum687ae002001-10-15 22:03:32 +00002546 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002547
2548 for (; meth->ml_name != NULL; meth++) {
2549 PyObject *descr;
2550 if (PyDict_GetItemString(dict, meth->ml_name))
2551 continue;
Fred Drake7bf97152002-03-28 05:33:33 +00002552 if (meth->ml_flags & METH_CLASS) {
2553 if (meth->ml_flags & METH_STATIC) {
2554 PyErr_SetString(PyExc_ValueError,
2555 "method cannot be both class and static");
2556 return -1;
2557 }
Tim Petersbca1cbc2002-12-09 22:56:13 +00002558 descr = PyDescr_NewClassMethod(type, meth);
Fred Drake7bf97152002-03-28 05:33:33 +00002559 }
2560 else if (meth->ml_flags & METH_STATIC) {
2561 descr = create_specialmethod(meth, PyStaticMethod_New);
2562 }
2563 else {
2564 descr = PyDescr_NewMethod(type, meth);
2565 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002566 if (descr == NULL)
2567 return -1;
Fred Drake7bf97152002-03-28 05:33:33 +00002568 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002569 return -1;
2570 Py_DECREF(descr);
2571 }
2572 return 0;
2573}
2574
2575static int
Guido van Rossum6f799372001-09-20 20:46:19 +00002576add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002577{
Guido van Rossum687ae002001-10-15 22:03:32 +00002578 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002579
2580 for (; memb->name != NULL; memb++) {
2581 PyObject *descr;
2582 if (PyDict_GetItemString(dict, memb->name))
2583 continue;
2584 descr = PyDescr_NewMember(type, memb);
2585 if (descr == NULL)
2586 return -1;
2587 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
2588 return -1;
2589 Py_DECREF(descr);
2590 }
2591 return 0;
2592}
2593
2594static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00002595add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002596{
Guido van Rossum687ae002001-10-15 22:03:32 +00002597 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002598
2599 for (; gsp->name != NULL; gsp++) {
2600 PyObject *descr;
2601 if (PyDict_GetItemString(dict, gsp->name))
2602 continue;
2603 descr = PyDescr_NewGetSet(type, gsp);
2604
2605 if (descr == NULL)
2606 return -1;
2607 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
2608 return -1;
2609 Py_DECREF(descr);
2610 }
2611 return 0;
2612}
2613
Guido van Rossum13d52f02001-08-10 21:24:08 +00002614static void
2615inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002616{
2617 int oldsize, newsize;
2618
Guido van Rossum13d52f02001-08-10 21:24:08 +00002619 /* Special flag magic */
2620 if (!type->tp_as_buffer && base->tp_as_buffer) {
2621 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
2622 type->tp_flags |=
2623 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
2624 }
2625 if (!type->tp_as_sequence && base->tp_as_sequence) {
2626 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
2627 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
2628 }
2629 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
2630 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
2631 if ((!type->tp_as_number && base->tp_as_number) ||
2632 (!type->tp_as_sequence && base->tp_as_sequence)) {
2633 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
2634 if (!type->tp_as_number && !type->tp_as_sequence) {
2635 type->tp_flags |= base->tp_flags &
2636 Py_TPFLAGS_HAVE_INPLACEOPS;
2637 }
2638 }
2639 /* Wow */
2640 }
2641 if (!type->tp_as_number && base->tp_as_number) {
2642 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
2643 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
2644 }
2645
2646 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00002647 oldsize = base->tp_basicsize;
2648 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
2649 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
2650 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00002651 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
2652 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00002653 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00002654 if (type->tp_traverse == NULL)
2655 type->tp_traverse = base->tp_traverse;
2656 if (type->tp_clear == NULL)
2657 type->tp_clear = base->tp_clear;
2658 }
2659 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
Guido van Rossumf884b742001-12-17 17:14:22 +00002660 /* The condition below could use some explanation.
2661 It appears that tp_new is not inherited for static types
2662 whose base class is 'object'; this seems to be a precaution
2663 so that old extension types don't suddenly become
2664 callable (object.__new__ wouldn't insure the invariants
2665 that the extension type's own factory function ensures).
2666 Heap types, of course, are under our control, so they do
2667 inherit tp_new; static extension types that specify some
2668 other built-in type as the default are considered
2669 new-style-aware so they also inherit object.__new__. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002670 if (base != &PyBaseObject_Type ||
2671 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2672 if (type->tp_new == NULL)
2673 type->tp_new = base->tp_new;
2674 }
2675 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00002676 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00002677
2678 /* Copy other non-function slots */
2679
2680#undef COPYVAL
2681#define COPYVAL(SLOT) \
2682 if (type->SLOT == 0) type->SLOT = base->SLOT
2683
2684 COPYVAL(tp_itemsize);
2685 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
2686 COPYVAL(tp_weaklistoffset);
2687 }
2688 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2689 COPYVAL(tp_dictoffset);
2690 }
Guido van Rossum13d52f02001-08-10 21:24:08 +00002691}
2692
2693static void
2694inherit_slots(PyTypeObject *type, PyTypeObject *base)
2695{
2696 PyTypeObject *basebase;
2697
2698#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00002699#undef COPYSLOT
2700#undef COPYNUM
2701#undef COPYSEQ
2702#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00002703#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00002704
2705#define SLOTDEFINED(SLOT) \
2706 (base->SLOT != 0 && \
2707 (basebase == NULL || base->SLOT != basebase->SLOT))
2708
Tim Peters6d6c1a32001-08-02 04:15:00 +00002709#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00002710 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00002711
2712#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
2713#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
2714#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00002715#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002716
Guido van Rossum13d52f02001-08-10 21:24:08 +00002717 /* This won't inherit indirect slots (from tp_as_number etc.)
2718 if type doesn't provide the space. */
2719
2720 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
2721 basebase = base->tp_base;
2722 if (basebase->tp_as_number == NULL)
2723 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002724 COPYNUM(nb_add);
2725 COPYNUM(nb_subtract);
2726 COPYNUM(nb_multiply);
2727 COPYNUM(nb_divide);
2728 COPYNUM(nb_remainder);
2729 COPYNUM(nb_divmod);
2730 COPYNUM(nb_power);
2731 COPYNUM(nb_negative);
2732 COPYNUM(nb_positive);
2733 COPYNUM(nb_absolute);
2734 COPYNUM(nb_nonzero);
2735 COPYNUM(nb_invert);
2736 COPYNUM(nb_lshift);
2737 COPYNUM(nb_rshift);
2738 COPYNUM(nb_and);
2739 COPYNUM(nb_xor);
2740 COPYNUM(nb_or);
2741 COPYNUM(nb_coerce);
2742 COPYNUM(nb_int);
2743 COPYNUM(nb_long);
2744 COPYNUM(nb_float);
2745 COPYNUM(nb_oct);
2746 COPYNUM(nb_hex);
2747 COPYNUM(nb_inplace_add);
2748 COPYNUM(nb_inplace_subtract);
2749 COPYNUM(nb_inplace_multiply);
2750 COPYNUM(nb_inplace_divide);
2751 COPYNUM(nb_inplace_remainder);
2752 COPYNUM(nb_inplace_power);
2753 COPYNUM(nb_inplace_lshift);
2754 COPYNUM(nb_inplace_rshift);
2755 COPYNUM(nb_inplace_and);
2756 COPYNUM(nb_inplace_xor);
2757 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00002758 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
2759 COPYNUM(nb_true_divide);
2760 COPYNUM(nb_floor_divide);
2761 COPYNUM(nb_inplace_true_divide);
2762 COPYNUM(nb_inplace_floor_divide);
2763 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002764 }
2765
Guido van Rossum13d52f02001-08-10 21:24:08 +00002766 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
2767 basebase = base->tp_base;
2768 if (basebase->tp_as_sequence == NULL)
2769 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002770 COPYSEQ(sq_length);
2771 COPYSEQ(sq_concat);
2772 COPYSEQ(sq_repeat);
2773 COPYSEQ(sq_item);
2774 COPYSEQ(sq_slice);
2775 COPYSEQ(sq_ass_item);
2776 COPYSEQ(sq_ass_slice);
2777 COPYSEQ(sq_contains);
2778 COPYSEQ(sq_inplace_concat);
2779 COPYSEQ(sq_inplace_repeat);
2780 }
2781
Guido van Rossum13d52f02001-08-10 21:24:08 +00002782 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
2783 basebase = base->tp_base;
2784 if (basebase->tp_as_mapping == NULL)
2785 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002786 COPYMAP(mp_length);
2787 COPYMAP(mp_subscript);
2788 COPYMAP(mp_ass_subscript);
2789 }
2790
Tim Petersfc57ccb2001-10-12 02:38:24 +00002791 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
2792 basebase = base->tp_base;
2793 if (basebase->tp_as_buffer == NULL)
2794 basebase = NULL;
2795 COPYBUF(bf_getreadbuffer);
2796 COPYBUF(bf_getwritebuffer);
2797 COPYBUF(bf_getsegcount);
2798 COPYBUF(bf_getcharbuffer);
2799 }
2800
Guido van Rossum13d52f02001-08-10 21:24:08 +00002801 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002802
Tim Peters6d6c1a32001-08-02 04:15:00 +00002803 COPYSLOT(tp_dealloc);
2804 COPYSLOT(tp_print);
2805 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
2806 type->tp_getattr = base->tp_getattr;
2807 type->tp_getattro = base->tp_getattro;
2808 }
2809 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
2810 type->tp_setattr = base->tp_setattr;
2811 type->tp_setattro = base->tp_setattro;
2812 }
2813 /* tp_compare see tp_richcompare */
2814 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002815 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002816 COPYSLOT(tp_call);
2817 COPYSLOT(tp_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002818 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00002819 if (type->tp_compare == NULL &&
2820 type->tp_richcompare == NULL &&
2821 type->tp_hash == NULL)
2822 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00002823 type->tp_compare = base->tp_compare;
2824 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002825 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002826 }
2827 }
2828 else {
2829 COPYSLOT(tp_compare);
2830 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002831 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
2832 COPYSLOT(tp_iter);
2833 COPYSLOT(tp_iternext);
2834 }
2835 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2836 COPYSLOT(tp_descr_get);
2837 COPYSLOT(tp_descr_set);
2838 COPYSLOT(tp_dictoffset);
2839 COPYSLOT(tp_init);
2840 COPYSLOT(tp_alloc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002841 COPYSLOT(tp_free);
Guido van Rossumcc8fe042002-04-05 17:10:16 +00002842 COPYSLOT(tp_is_gc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002843 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002844}
2845
Jeremy Hylton938ace62002-07-17 16:30:39 +00002846static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00002847
Tim Peters6d6c1a32001-08-02 04:15:00 +00002848int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002849PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002850{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002851 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002852 PyTypeObject *base;
2853 int i, n;
2854
Guido van Rossumcab05802002-06-10 15:29:03 +00002855 if (type->tp_flags & Py_TPFLAGS_READY) {
2856 assert(type->tp_dict != NULL);
Guido van Rossumd614f972001-08-10 17:39:49 +00002857 return 0;
Guido van Rossumcab05802002-06-10 15:29:03 +00002858 }
Guido van Rossumd614f972001-08-10 17:39:49 +00002859 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00002860
2861 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002862
2863 /* Initialize tp_base (defaults to BaseObject unless that's us) */
2864 base = type->tp_base;
2865 if (base == NULL && type != &PyBaseObject_Type)
2866 base = type->tp_base = &PyBaseObject_Type;
2867
Guido van Rossum323a9cf2002-08-14 17:26:30 +00002868 /* Initialize the base class */
2869 if (base && base->tp_dict == NULL) {
2870 if (PyType_Ready(base) < 0)
2871 goto error;
2872 }
2873
Guido van Rossum0986d822002-04-08 01:38:42 +00002874 /* Initialize ob_type if NULL. This means extensions that want to be
2875 compilable separately on Windows can call PyType_Ready() instead of
2876 initializing the ob_type field of their type objects. */
2877 if (type->ob_type == NULL)
2878 type->ob_type = base->ob_type;
2879
Tim Peters6d6c1a32001-08-02 04:15:00 +00002880 /* Initialize tp_bases */
2881 bases = type->tp_bases;
2882 if (bases == NULL) {
2883 if (base == NULL)
2884 bases = PyTuple_New(0);
2885 else
2886 bases = Py_BuildValue("(O)", base);
2887 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00002888 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002889 type->tp_bases = bases;
2890 }
2891
Guido van Rossum687ae002001-10-15 22:03:32 +00002892 /* Initialize tp_dict */
2893 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002894 if (dict == NULL) {
2895 dict = PyDict_New();
2896 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00002897 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00002898 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002899 }
2900
Guido van Rossum687ae002001-10-15 22:03:32 +00002901 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002902 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002903 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002904 if (type->tp_methods != NULL) {
2905 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002906 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002907 }
2908 if (type->tp_members != NULL) {
2909 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002910 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002911 }
2912 if (type->tp_getset != NULL) {
2913 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002914 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002915 }
2916
Tim Peters6d6c1a32001-08-02 04:15:00 +00002917 /* Calculate method resolution order */
2918 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00002919 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002920 }
2921
Guido van Rossum13d52f02001-08-10 21:24:08 +00002922 /* Inherit special flags from dominant base */
2923 if (type->tp_base != NULL)
2924 inherit_special(type, type->tp_base);
2925
Tim Peters6d6c1a32001-08-02 04:15:00 +00002926 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002927 bases = type->tp_mro;
2928 assert(bases != NULL);
2929 assert(PyTuple_Check(bases));
2930 n = PyTuple_GET_SIZE(bases);
2931 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002932 PyObject *b = PyTuple_GET_ITEM(bases, i);
2933 if (PyType_Check(b))
2934 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002935 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002936
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00002937 /* if the type dictionary doesn't contain a __doc__, set it from
2938 the tp_doc slot.
2939 */
2940 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
2941 if (type->tp_doc != NULL) {
2942 PyObject *doc = PyString_FromString(type->tp_doc);
2943 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
2944 Py_DECREF(doc);
2945 } else {
Guido van Rossumd4641072002-04-03 02:13:37 +00002946 PyDict_SetItemString(type->tp_dict,
2947 "__doc__", Py_None);
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00002948 }
2949 }
2950
Guido van Rossum13d52f02001-08-10 21:24:08 +00002951 /* Some more special stuff */
2952 base = type->tp_base;
2953 if (base != NULL) {
2954 if (type->tp_as_number == NULL)
2955 type->tp_as_number = base->tp_as_number;
2956 if (type->tp_as_sequence == NULL)
2957 type->tp_as_sequence = base->tp_as_sequence;
2958 if (type->tp_as_mapping == NULL)
2959 type->tp_as_mapping = base->tp_as_mapping;
2960 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002961
Guido van Rossum1c450732001-10-08 15:18:27 +00002962 /* Link into each base class's list of subclasses */
2963 bases = type->tp_bases;
2964 n = PyTuple_GET_SIZE(bases);
2965 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002966 PyObject *b = PyTuple_GET_ITEM(bases, i);
2967 if (PyType_Check(b) &&
2968 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00002969 goto error;
2970 }
2971
Guido van Rossum13d52f02001-08-10 21:24:08 +00002972 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00002973 assert(type->tp_dict != NULL);
2974 type->tp_flags =
2975 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002976 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00002977
2978 error:
2979 type->tp_flags &= ~Py_TPFLAGS_READYING;
2980 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002981}
2982
Guido van Rossum1c450732001-10-08 15:18:27 +00002983static int
2984add_subclass(PyTypeObject *base, PyTypeObject *type)
2985{
2986 int i;
2987 PyObject *list, *ref, *new;
2988
2989 list = base->tp_subclasses;
2990 if (list == NULL) {
2991 base->tp_subclasses = list = PyList_New(0);
2992 if (list == NULL)
2993 return -1;
2994 }
2995 assert(PyList_Check(list));
2996 new = PyWeakref_NewRef((PyObject *)type, NULL);
2997 i = PyList_GET_SIZE(list);
2998 while (--i >= 0) {
2999 ref = PyList_GET_ITEM(list, i);
3000 assert(PyWeakref_CheckRef(ref));
Guido van Rossum3930bc32002-10-18 13:51:49 +00003001 if (PyWeakref_GET_OBJECT(ref) == Py_None)
3002 return PyList_SetItem(list, i, new);
Guido van Rossum1c450732001-10-08 15:18:27 +00003003 }
3004 i = PyList_Append(list, new);
3005 Py_DECREF(new);
3006 return i;
3007}
3008
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003009static void
3010remove_subclass(PyTypeObject *base, PyTypeObject *type)
3011{
3012 int i;
3013 PyObject *list, *ref;
3014
3015 list = base->tp_subclasses;
3016 if (list == NULL) {
3017 return;
3018 }
3019 assert(PyList_Check(list));
3020 i = PyList_GET_SIZE(list);
3021 while (--i >= 0) {
3022 ref = PyList_GET_ITEM(list, i);
3023 assert(PyWeakref_CheckRef(ref));
3024 if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
3025 /* this can't fail, right? */
3026 PySequence_DelItem(list, i);
3027 return;
3028 }
3029 }
3030}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003031
3032/* Generic wrappers for overloadable 'operators' such as __getitem__ */
3033
3034/* There's a wrapper *function* for each distinct function typedef used
3035 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
3036 wrapper *table* for each distinct operation (e.g. __len__, __add__).
3037 Most tables have only one entry; the tables for binary operators have two
3038 entries, one regular and one with reversed arguments. */
3039
3040static PyObject *
3041wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
3042{
3043 inquiry func = (inquiry)wrapped;
3044 int res;
3045
3046 if (!PyArg_ParseTuple(args, ""))
3047 return NULL;
3048 res = (*func)(self);
3049 if (res == -1 && PyErr_Occurred())
3050 return NULL;
3051 return PyInt_FromLong((long)res);
3052}
3053
Tim Peters6d6c1a32001-08-02 04:15:00 +00003054static PyObject *
3055wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
3056{
3057 binaryfunc func = (binaryfunc)wrapped;
3058 PyObject *other;
3059
3060 if (!PyArg_ParseTuple(args, "O", &other))
3061 return NULL;
3062 return (*func)(self, other);
3063}
3064
3065static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003066wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
3067{
3068 binaryfunc func = (binaryfunc)wrapped;
3069 PyObject *other;
3070
3071 if (!PyArg_ParseTuple(args, "O", &other))
3072 return NULL;
3073 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003074 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003075 Py_INCREF(Py_NotImplemented);
3076 return Py_NotImplemented;
3077 }
3078 return (*func)(self, other);
3079}
3080
3081static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003082wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3083{
3084 binaryfunc func = (binaryfunc)wrapped;
3085 PyObject *other;
3086
3087 if (!PyArg_ParseTuple(args, "O", &other))
3088 return NULL;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003089 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003090 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003091 Py_INCREF(Py_NotImplemented);
3092 return Py_NotImplemented;
3093 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003094 return (*func)(other, self);
3095}
3096
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003097static PyObject *
3098wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
3099{
3100 coercion func = (coercion)wrapped;
3101 PyObject *other, *res;
3102 int ok;
3103
3104 if (!PyArg_ParseTuple(args, "O", &other))
3105 return NULL;
3106 ok = func(&self, &other);
3107 if (ok < 0)
3108 return NULL;
3109 if (ok > 0) {
3110 Py_INCREF(Py_NotImplemented);
3111 return Py_NotImplemented;
3112 }
3113 res = PyTuple_New(2);
3114 if (res == NULL) {
3115 Py_DECREF(self);
3116 Py_DECREF(other);
3117 return NULL;
3118 }
3119 PyTuple_SET_ITEM(res, 0, self);
3120 PyTuple_SET_ITEM(res, 1, other);
3121 return res;
3122}
3123
Tim Peters6d6c1a32001-08-02 04:15:00 +00003124static PyObject *
3125wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
3126{
3127 ternaryfunc func = (ternaryfunc)wrapped;
3128 PyObject *other;
3129 PyObject *third = Py_None;
3130
3131 /* Note: This wrapper only works for __pow__() */
3132
3133 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
3134 return NULL;
3135 return (*func)(self, other, third);
3136}
3137
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00003138static PyObject *
3139wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3140{
3141 ternaryfunc func = (ternaryfunc)wrapped;
3142 PyObject *other;
3143 PyObject *third = Py_None;
3144
3145 /* Note: This wrapper only works for __pow__() */
3146
3147 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
3148 return NULL;
3149 return (*func)(other, self, third);
3150}
3151
Tim Peters6d6c1a32001-08-02 04:15:00 +00003152static PyObject *
3153wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
3154{
3155 unaryfunc func = (unaryfunc)wrapped;
3156
3157 if (!PyArg_ParseTuple(args, ""))
3158 return NULL;
3159 return (*func)(self);
3160}
3161
Tim Peters6d6c1a32001-08-02 04:15:00 +00003162static PyObject *
3163wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
3164{
3165 intargfunc func = (intargfunc)wrapped;
3166 int i;
3167
3168 if (!PyArg_ParseTuple(args, "i", &i))
3169 return NULL;
3170 return (*func)(self, i);
3171}
3172
Guido van Rossum5d815f32001-08-17 21:57:47 +00003173static int
3174getindex(PyObject *self, PyObject *arg)
3175{
3176 int i;
3177
3178 i = PyInt_AsLong(arg);
3179 if (i == -1 && PyErr_Occurred())
3180 return -1;
3181 if (i < 0) {
3182 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
3183 if (sq && sq->sq_length) {
3184 int n = (*sq->sq_length)(self);
3185 if (n < 0)
3186 return -1;
3187 i += n;
3188 }
3189 }
3190 return i;
3191}
3192
3193static PyObject *
3194wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
3195{
3196 intargfunc func = (intargfunc)wrapped;
3197 PyObject *arg;
3198 int i;
3199
Guido van Rossumf4593e02001-10-03 12:09:30 +00003200 if (PyTuple_GET_SIZE(args) == 1) {
3201 arg = PyTuple_GET_ITEM(args, 0);
3202 i = getindex(self, arg);
3203 if (i == -1 && PyErr_Occurred())
3204 return NULL;
3205 return (*func)(self, i);
3206 }
3207 PyArg_ParseTuple(args, "O", &arg);
3208 assert(PyErr_Occurred());
3209 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003210}
3211
Tim Peters6d6c1a32001-08-02 04:15:00 +00003212static PyObject *
3213wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
3214{
3215 intintargfunc func = (intintargfunc)wrapped;
3216 int i, j;
3217
3218 if (!PyArg_ParseTuple(args, "ii", &i, &j))
3219 return NULL;
3220 return (*func)(self, i, j);
3221}
3222
Tim Peters6d6c1a32001-08-02 04:15:00 +00003223static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003224wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003225{
3226 intobjargproc func = (intobjargproc)wrapped;
3227 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003228 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003229
Guido van Rossum5d815f32001-08-17 21:57:47 +00003230 if (!PyArg_ParseTuple(args, "OO", &arg, &value))
3231 return NULL;
3232 i = getindex(self, arg);
3233 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00003234 return NULL;
3235 res = (*func)(self, i, value);
3236 if (res == -1 && PyErr_Occurred())
3237 return NULL;
3238 Py_INCREF(Py_None);
3239 return Py_None;
3240}
3241
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003242static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003243wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003244{
3245 intobjargproc func = (intobjargproc)wrapped;
3246 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003247 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003248
Guido van Rossum5d815f32001-08-17 21:57:47 +00003249 if (!PyArg_ParseTuple(args, "O", &arg))
3250 return NULL;
3251 i = getindex(self, arg);
3252 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003253 return NULL;
3254 res = (*func)(self, i, NULL);
3255 if (res == -1 && PyErr_Occurred())
3256 return NULL;
3257 Py_INCREF(Py_None);
3258 return Py_None;
3259}
3260
Tim Peters6d6c1a32001-08-02 04:15:00 +00003261static PyObject *
3262wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
3263{
3264 intintobjargproc func = (intintobjargproc)wrapped;
3265 int i, j, res;
3266 PyObject *value;
3267
3268 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
3269 return NULL;
3270 res = (*func)(self, i, j, value);
3271 if (res == -1 && PyErr_Occurred())
3272 return NULL;
3273 Py_INCREF(Py_None);
3274 return Py_None;
3275}
3276
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003277static PyObject *
3278wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
3279{
3280 intintobjargproc func = (intintobjargproc)wrapped;
3281 int i, j, res;
3282
3283 if (!PyArg_ParseTuple(args, "ii", &i, &j))
3284 return NULL;
3285 res = (*func)(self, i, j, NULL);
3286 if (res == -1 && PyErr_Occurred())
3287 return NULL;
3288 Py_INCREF(Py_None);
3289 return Py_None;
3290}
3291
Tim Peters6d6c1a32001-08-02 04:15:00 +00003292/* XXX objobjproc is a misnomer; should be objargpred */
3293static PyObject *
3294wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
3295{
3296 objobjproc func = (objobjproc)wrapped;
3297 int res;
3298 PyObject *value;
3299
3300 if (!PyArg_ParseTuple(args, "O", &value))
3301 return NULL;
3302 res = (*func)(self, value);
3303 if (res == -1 && PyErr_Occurred())
3304 return NULL;
3305 return PyInt_FromLong((long)res);
3306}
3307
Tim Peters6d6c1a32001-08-02 04:15:00 +00003308static PyObject *
3309wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
3310{
3311 objobjargproc func = (objobjargproc)wrapped;
3312 int res;
3313 PyObject *key, *value;
3314
3315 if (!PyArg_ParseTuple(args, "OO", &key, &value))
3316 return NULL;
3317 res = (*func)(self, key, value);
3318 if (res == -1 && PyErr_Occurred())
3319 return NULL;
3320 Py_INCREF(Py_None);
3321 return Py_None;
3322}
3323
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003324static PyObject *
3325wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
3326{
3327 objobjargproc func = (objobjargproc)wrapped;
3328 int res;
3329 PyObject *key;
3330
3331 if (!PyArg_ParseTuple(args, "O", &key))
3332 return NULL;
3333 res = (*func)(self, key, NULL);
3334 if (res == -1 && PyErr_Occurred())
3335 return NULL;
3336 Py_INCREF(Py_None);
3337 return Py_None;
3338}
3339
Tim Peters6d6c1a32001-08-02 04:15:00 +00003340static PyObject *
3341wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
3342{
3343 cmpfunc func = (cmpfunc)wrapped;
3344 int res;
3345 PyObject *other;
3346
3347 if (!PyArg_ParseTuple(args, "O", &other))
3348 return NULL;
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00003349 if (other->ob_type->tp_compare != func &&
3350 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00003351 PyErr_Format(
3352 PyExc_TypeError,
3353 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
3354 self->ob_type->tp_name,
3355 self->ob_type->tp_name,
3356 other->ob_type->tp_name);
3357 return NULL;
3358 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003359 res = (*func)(self, other);
3360 if (PyErr_Occurred())
3361 return NULL;
3362 return PyInt_FromLong((long)res);
3363}
3364
Tim Peters6d6c1a32001-08-02 04:15:00 +00003365static PyObject *
3366wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
3367{
3368 setattrofunc func = (setattrofunc)wrapped;
3369 int res;
3370 PyObject *name, *value;
3371
3372 if (!PyArg_ParseTuple(args, "OO", &name, &value))
3373 return NULL;
3374 res = (*func)(self, name, value);
3375 if (res < 0)
3376 return NULL;
3377 Py_INCREF(Py_None);
3378 return Py_None;
3379}
3380
3381static PyObject *
3382wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
3383{
3384 setattrofunc func = (setattrofunc)wrapped;
3385 int res;
3386 PyObject *name;
3387
3388 if (!PyArg_ParseTuple(args, "O", &name))
3389 return NULL;
3390 res = (*func)(self, name, NULL);
3391 if (res < 0)
3392 return NULL;
3393 Py_INCREF(Py_None);
3394 return Py_None;
3395}
3396
Tim Peters6d6c1a32001-08-02 04:15:00 +00003397static PyObject *
3398wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
3399{
3400 hashfunc func = (hashfunc)wrapped;
3401 long res;
3402
3403 if (!PyArg_ParseTuple(args, ""))
3404 return NULL;
3405 res = (*func)(self);
3406 if (res == -1 && PyErr_Occurred())
3407 return NULL;
3408 return PyInt_FromLong(res);
3409}
3410
Tim Peters6d6c1a32001-08-02 04:15:00 +00003411static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00003412wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003413{
3414 ternaryfunc func = (ternaryfunc)wrapped;
3415
Guido van Rossumc8e56452001-10-22 00:43:43 +00003416 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003417}
3418
Tim Peters6d6c1a32001-08-02 04:15:00 +00003419static PyObject *
3420wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
3421{
3422 richcmpfunc func = (richcmpfunc)wrapped;
3423 PyObject *other;
3424
3425 if (!PyArg_ParseTuple(args, "O", &other))
3426 return NULL;
3427 return (*func)(self, other, op);
3428}
3429
3430#undef RICHCMP_WRAPPER
3431#define RICHCMP_WRAPPER(NAME, OP) \
3432static PyObject * \
3433richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
3434{ \
3435 return wrap_richcmpfunc(self, args, wrapped, OP); \
3436}
3437
Jack Jansen8e938b42001-08-08 15:29:49 +00003438RICHCMP_WRAPPER(lt, Py_LT)
3439RICHCMP_WRAPPER(le, Py_LE)
3440RICHCMP_WRAPPER(eq, Py_EQ)
3441RICHCMP_WRAPPER(ne, Py_NE)
3442RICHCMP_WRAPPER(gt, Py_GT)
3443RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003444
Tim Peters6d6c1a32001-08-02 04:15:00 +00003445static PyObject *
3446wrap_next(PyObject *self, PyObject *args, void *wrapped)
3447{
3448 unaryfunc func = (unaryfunc)wrapped;
3449 PyObject *res;
3450
3451 if (!PyArg_ParseTuple(args, ""))
3452 return NULL;
3453 res = (*func)(self);
3454 if (res == NULL && !PyErr_Occurred())
3455 PyErr_SetNone(PyExc_StopIteration);
3456 return res;
3457}
3458
Tim Peters6d6c1a32001-08-02 04:15:00 +00003459static PyObject *
3460wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
3461{
3462 descrgetfunc func = (descrgetfunc)wrapped;
3463 PyObject *obj;
3464 PyObject *type = NULL;
3465
3466 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
3467 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003468 return (*func)(self, obj, type);
3469}
3470
Tim Peters6d6c1a32001-08-02 04:15:00 +00003471static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003472wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003473{
3474 descrsetfunc func = (descrsetfunc)wrapped;
3475 PyObject *obj, *value;
3476 int ret;
3477
3478 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
3479 return NULL;
3480 ret = (*func)(self, obj, value);
3481 if (ret < 0)
3482 return NULL;
3483 Py_INCREF(Py_None);
3484 return Py_None;
3485}
Guido van Rossum22b13872002-08-06 21:41:44 +00003486
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00003487static PyObject *
3488wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
3489{
3490 descrsetfunc func = (descrsetfunc)wrapped;
3491 PyObject *obj;
3492 int ret;
3493
3494 if (!PyArg_ParseTuple(args, "O", &obj))
3495 return NULL;
3496 ret = (*func)(self, obj, NULL);
3497 if (ret < 0)
3498 return NULL;
3499 Py_INCREF(Py_None);
3500 return Py_None;
3501}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003502
Tim Peters6d6c1a32001-08-02 04:15:00 +00003503static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00003504wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003505{
3506 initproc func = (initproc)wrapped;
3507
Guido van Rossumc8e56452001-10-22 00:43:43 +00003508 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003509 return NULL;
3510 Py_INCREF(Py_None);
3511 return Py_None;
3512}
3513
Tim Peters6d6c1a32001-08-02 04:15:00 +00003514static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003515tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003516{
Barry Warsaw60f01882001-08-22 19:24:42 +00003517 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003518 PyObject *arg0, *res;
3519
3520 if (self == NULL || !PyType_Check(self))
3521 Py_FatalError("__new__() called with non-type 'self'");
3522 type = (PyTypeObject *)self;
3523 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003524 PyErr_Format(PyExc_TypeError,
3525 "%s.__new__(): not enough arguments",
3526 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003527 return NULL;
3528 }
3529 arg0 = PyTuple_GET_ITEM(args, 0);
3530 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003531 PyErr_Format(PyExc_TypeError,
3532 "%s.__new__(X): X is not a type object (%s)",
3533 type->tp_name,
3534 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003535 return NULL;
3536 }
3537 subtype = (PyTypeObject *)arg0;
3538 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003539 PyErr_Format(PyExc_TypeError,
3540 "%s.__new__(%s): %s is not a subtype of %s",
3541 type->tp_name,
3542 subtype->tp_name,
3543 subtype->tp_name,
3544 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003545 return NULL;
3546 }
Barry Warsaw60f01882001-08-22 19:24:42 +00003547
3548 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00003549 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00003550 most derived base that's not a heap type is this type. */
3551 staticbase = subtype;
3552 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
3553 staticbase = staticbase->tp_base;
Guido van Rossuma8c60f42001-09-14 19:43:36 +00003554 if (staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003555 PyErr_Format(PyExc_TypeError,
3556 "%s.__new__(%s) is not safe, use %s.__new__()",
3557 type->tp_name,
3558 subtype->tp_name,
3559 staticbase == NULL ? "?" : staticbase->tp_name);
3560 return NULL;
3561 }
3562
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003563 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
3564 if (args == NULL)
3565 return NULL;
3566 res = type->tp_new(subtype, args, kwds);
3567 Py_DECREF(args);
3568 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003569}
3570
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003571static struct PyMethodDef tp_new_methoddef[] = {
3572 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00003573 PyDoc_STR("T.__new__(S, ...) -> "
3574 "a new object with type S, a subtype of T")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00003575 {0}
3576};
3577
3578static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003579add_tp_new_wrapper(PyTypeObject *type)
3580{
Guido van Rossumf040ede2001-08-07 16:40:56 +00003581 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003582
Guido van Rossum687ae002001-10-15 22:03:32 +00003583 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00003584 return 0;
3585 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003586 if (func == NULL)
3587 return -1;
Guido van Rossum687ae002001-10-15 22:03:32 +00003588 return PyDict_SetItemString(type->tp_dict, "__new__", func);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003589}
3590
Guido van Rossumf040ede2001-08-07 16:40:56 +00003591/* Slot wrappers that call the corresponding __foo__ slot. See comments
3592 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003593
Guido van Rossumdc91b992001-08-08 22:26:22 +00003594#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003595static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003596FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003597{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00003598 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003599 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003600}
3601
Guido van Rossumdc91b992001-08-08 22:26:22 +00003602#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003603static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003604FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003605{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003606 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003607 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003608}
3609
Guido van Rossumcd118802003-01-06 22:57:47 +00003610/* Boolean helper for SLOT1BINFULL().
3611 right.__class__ is a nontrivial subclass of left.__class__. */
3612static int
3613method_is_overloaded(PyObject *left, PyObject *right, char *name)
3614{
3615 PyObject *a, *b;
3616 int ok;
3617
3618 b = PyObject_GetAttrString((PyObject *)(right->ob_type), name);
3619 if (b == NULL) {
3620 PyErr_Clear();
3621 /* If right doesn't have it, it's not overloaded */
3622 return 0;
3623 }
3624
3625 a = PyObject_GetAttrString((PyObject *)(left->ob_type), name);
3626 if (a == NULL) {
3627 PyErr_Clear();
3628 Py_DECREF(b);
3629 /* If right has it but left doesn't, it's overloaded */
3630 return 1;
3631 }
3632
3633 ok = PyObject_RichCompareBool(a, b, Py_NE);
3634 Py_DECREF(a);
3635 Py_DECREF(b);
3636 if (ok < 0) {
3637 PyErr_Clear();
3638 return 0;
3639 }
3640
3641 return ok;
3642}
3643
Guido van Rossumdc91b992001-08-08 22:26:22 +00003644
3645#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003646static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003647FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003648{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003649 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00003650 int do_other = self->ob_type != other->ob_type && \
3651 other->ob_type->tp_as_number != NULL && \
3652 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003653 if (self->ob_type->tp_as_number != NULL && \
3654 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
3655 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00003656 if (do_other && \
Guido van Rossumcd118802003-01-06 22:57:47 +00003657 PyType_IsSubtype(other->ob_type, self->ob_type) && \
3658 method_is_overloaded(self, other, ROPSTR)) { \
Guido van Rossum55f20992001-10-01 17:18:22 +00003659 r = call_maybe( \
3660 other, ROPSTR, &rcache_str, "(O)", self); \
3661 if (r != Py_NotImplemented) \
3662 return r; \
3663 Py_DECREF(r); \
3664 do_other = 0; \
3665 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00003666 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00003667 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003668 if (r != Py_NotImplemented || \
3669 other->ob_type == self->ob_type) \
3670 return r; \
3671 Py_DECREF(r); \
3672 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00003673 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00003674 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00003675 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003676 } \
3677 Py_INCREF(Py_NotImplemented); \
3678 return Py_NotImplemented; \
3679}
3680
3681#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
3682 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
3683
3684#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
3685static PyObject * \
3686FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
3687{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003688 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003689 return call_method(self, OPSTR, &cache_str, \
3690 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003691}
3692
3693static int
3694slot_sq_length(PyObject *self)
3695{
Guido van Rossum2730b132001-08-28 18:22:14 +00003696 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00003697 PyObject *res = call_method(self, "__len__", &len_str, "()");
Guido van Rossum26111622001-10-01 16:42:49 +00003698 int len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003699
3700 if (res == NULL)
3701 return -1;
Guido van Rossum26111622001-10-01 16:42:49 +00003702 len = (int)PyInt_AsLong(res);
3703 Py_DECREF(res);
Jeremy Hylton73a088e2002-07-25 16:43:29 +00003704 if (len == -1 && PyErr_Occurred())
3705 return -1;
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00003706 if (len < 0) {
Guido van Rossum22b13872002-08-06 21:41:44 +00003707 PyErr_SetString(PyExc_ValueError,
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00003708 "__len__() should return >= 0");
3709 return -1;
3710 }
Guido van Rossum26111622001-10-01 16:42:49 +00003711 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003712}
3713
Guido van Rossumdc91b992001-08-08 22:26:22 +00003714SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
3715SLOT1(slot_sq_repeat, "__mul__", int, "i")
Guido van Rossumf4593e02001-10-03 12:09:30 +00003716
3717/* Super-optimized version of slot_sq_item.
3718 Other slots could do the same... */
3719static PyObject *
3720slot_sq_item(PyObject *self, int i)
3721{
3722 static PyObject *getitem_str;
3723 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
3724 descrgetfunc f;
3725
3726 if (getitem_str == NULL) {
3727 getitem_str = PyString_InternFromString("__getitem__");
3728 if (getitem_str == NULL)
3729 return NULL;
3730 }
3731 func = _PyType_Lookup(self->ob_type, getitem_str);
3732 if (func != NULL) {
Guido van Rossumf4593e02001-10-03 12:09:30 +00003733 if ((f = func->ob_type->tp_descr_get) == NULL)
3734 Py_INCREF(func);
Neal Norwitz673cd822002-10-18 16:33:13 +00003735 else {
Guido van Rossumf4593e02001-10-03 12:09:30 +00003736 func = f(func, self, (PyObject *)(self->ob_type));
Neal Norwitz673cd822002-10-18 16:33:13 +00003737 if (func == NULL) {
3738 return NULL;
3739 }
3740 }
Guido van Rossumf4593e02001-10-03 12:09:30 +00003741 ival = PyInt_FromLong(i);
3742 if (ival != NULL) {
3743 args = PyTuple_New(1);
3744 if (args != NULL) {
3745 PyTuple_SET_ITEM(args, 0, ival);
3746 retval = PyObject_Call(func, args, NULL);
3747 Py_XDECREF(args);
3748 Py_XDECREF(func);
3749 return retval;
3750 }
3751 }
3752 }
3753 else {
3754 PyErr_SetObject(PyExc_AttributeError, getitem_str);
3755 }
3756 Py_XDECREF(args);
3757 Py_XDECREF(ival);
3758 Py_XDECREF(func);
3759 return NULL;
3760}
3761
Guido van Rossumdc91b992001-08-08 22:26:22 +00003762SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003763
3764static int
3765slot_sq_ass_item(PyObject *self, int index, PyObject *value)
3766{
3767 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003768 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003769
3770 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003771 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003772 "(i)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003773 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003774 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003775 "(iO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003776 if (res == NULL)
3777 return -1;
3778 Py_DECREF(res);
3779 return 0;
3780}
3781
3782static int
3783slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
3784{
3785 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003786 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003787
3788 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003789 res = call_method(self, "__delslice__", &delslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003790 "(ii)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003791 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003792 res = call_method(self, "__setslice__", &setslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003793 "(iiO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003794 if (res == NULL)
3795 return -1;
3796 Py_DECREF(res);
3797 return 0;
3798}
3799
3800static int
3801slot_sq_contains(PyObject *self, PyObject *value)
3802{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003803 PyObject *func, *res, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00003804 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003805
Guido van Rossum55f20992001-10-01 17:18:22 +00003806 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003807
3808 if (func != NULL) {
3809 args = Py_BuildValue("(O)", value);
3810 if (args == NULL)
3811 res = NULL;
3812 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003813 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003814 Py_DECREF(args);
3815 }
3816 Py_DECREF(func);
3817 if (res == NULL)
3818 return -1;
3819 return PyObject_IsTrue(res);
3820 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003821 else if (PyErr_Occurred())
3822 return -1;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003823 else {
Tim Peters16a77ad2001-09-08 04:00:12 +00003824 return _PySequence_IterSearch(self, value,
3825 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003826 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003827}
3828
Guido van Rossumdc91b992001-08-08 22:26:22 +00003829SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
3830SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003831
3832#define slot_mp_length slot_sq_length
3833
Guido van Rossumdc91b992001-08-08 22:26:22 +00003834SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003835
3836static int
3837slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
3838{
3839 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003840 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003841
3842 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003843 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003844 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003845 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003846 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003847 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003848 if (res == NULL)
3849 return -1;
3850 Py_DECREF(res);
3851 return 0;
3852}
3853
Guido van Rossumdc91b992001-08-08 22:26:22 +00003854SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
3855SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
3856SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
3857SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
3858SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
3859SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
3860
Jeremy Hylton938ace62002-07-17 16:30:39 +00003861static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003862
3863SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
3864 nb_power, "__pow__", "__rpow__")
3865
3866static PyObject *
3867slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
3868{
Guido van Rossum2730b132001-08-28 18:22:14 +00003869 static PyObject *pow_str;
3870
Guido van Rossumdc91b992001-08-08 22:26:22 +00003871 if (modulus == Py_None)
3872 return slot_nb_power_binary(self, other);
Guido van Rossum23094982002-06-10 14:30:43 +00003873 /* Three-arg power doesn't use __rpow__. But ternary_op
3874 can call this when the second argument's type uses
3875 slot_nb_power, so check before calling self.__pow__. */
3876 if (self->ob_type->tp_as_number != NULL &&
3877 self->ob_type->tp_as_number->nb_power == slot_nb_power) {
3878 return call_method(self, "__pow__", &pow_str,
3879 "(OO)", other, modulus);
3880 }
3881 Py_INCREF(Py_NotImplemented);
3882 return Py_NotImplemented;
Guido van Rossumdc91b992001-08-08 22:26:22 +00003883}
3884
3885SLOT0(slot_nb_negative, "__neg__")
3886SLOT0(slot_nb_positive, "__pos__")
3887SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003888
3889static int
3890slot_nb_nonzero(PyObject *self)
3891{
Tim Petersea7f75d2002-12-07 21:39:16 +00003892 PyObject *func, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00003893 static PyObject *nonzero_str, *len_str;
Tim Petersea7f75d2002-12-07 21:39:16 +00003894 int result = -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003895
Guido van Rossum55f20992001-10-01 17:18:22 +00003896 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003897 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00003898 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00003899 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00003900 func = lookup_maybe(self, "__len__", &len_str);
Tim Petersea7f75d2002-12-07 21:39:16 +00003901 if (func == NULL)
3902 return PyErr_Occurred() ? -1 : 1;
3903 }
3904 args = PyTuple_New(0);
3905 if (args != NULL) {
3906 PyObject *temp = PyObject_Call(func, args, NULL);
3907 Py_DECREF(args);
3908 if (temp != NULL) {
3909 result = PyObject_IsTrue(temp);
3910 Py_DECREF(temp);
Guido van Rossum55f20992001-10-01 17:18:22 +00003911 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00003912 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003913 Py_DECREF(func);
Tim Petersea7f75d2002-12-07 21:39:16 +00003914 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003915}
3916
Guido van Rossumdc91b992001-08-08 22:26:22 +00003917SLOT0(slot_nb_invert, "__invert__")
3918SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
3919SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
3920SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
3921SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
3922SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003923
3924static int
3925slot_nb_coerce(PyObject **a, PyObject **b)
3926{
3927 static PyObject *coerce_str;
3928 PyObject *self = *a, *other = *b;
3929
3930 if (self->ob_type->tp_as_number != NULL &&
3931 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3932 PyObject *r;
3933 r = call_maybe(
3934 self, "__coerce__", &coerce_str, "(O)", other);
3935 if (r == NULL)
3936 return -1;
3937 if (r == Py_NotImplemented) {
3938 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003939 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003940 else {
3941 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3942 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003943 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00003944 Py_DECREF(r);
3945 return -1;
3946 }
3947 *a = PyTuple_GET_ITEM(r, 0);
3948 Py_INCREF(*a);
3949 *b = PyTuple_GET_ITEM(r, 1);
3950 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003951 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00003952 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003953 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003954 }
3955 if (other->ob_type->tp_as_number != NULL &&
3956 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3957 PyObject *r;
3958 r = call_maybe(
3959 other, "__coerce__", &coerce_str, "(O)", self);
3960 if (r == NULL)
3961 return -1;
3962 if (r == Py_NotImplemented) {
3963 Py_DECREF(r);
3964 return 1;
3965 }
3966 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3967 PyErr_SetString(PyExc_TypeError,
3968 "__coerce__ didn't return a 2-tuple");
3969 Py_DECREF(r);
3970 return -1;
3971 }
3972 *a = PyTuple_GET_ITEM(r, 1);
3973 Py_INCREF(*a);
3974 *b = PyTuple_GET_ITEM(r, 0);
3975 Py_INCREF(*b);
3976 Py_DECREF(r);
3977 return 0;
3978 }
3979 return 1;
3980}
3981
Guido van Rossumdc91b992001-08-08 22:26:22 +00003982SLOT0(slot_nb_int, "__int__")
3983SLOT0(slot_nb_long, "__long__")
3984SLOT0(slot_nb_float, "__float__")
3985SLOT0(slot_nb_oct, "__oct__")
3986SLOT0(slot_nb_hex, "__hex__")
3987SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
3988SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
3989SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
3990SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
3991SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003992SLOT1(slot_nb_inplace_power, "__ipow__", PyObject *, "O")
Guido van Rossumdc91b992001-08-08 22:26:22 +00003993SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
3994SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
3995SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
3996SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
3997SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
3998SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
3999 "__floordiv__", "__rfloordiv__")
4000SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
4001SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
4002SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004003
4004static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00004005half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004006{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004007 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004008 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004009 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004010
Guido van Rossum60718732001-08-28 17:47:51 +00004011 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004012 if (func == NULL) {
4013 PyErr_Clear();
4014 }
4015 else {
4016 args = Py_BuildValue("(O)", other);
4017 if (args == NULL)
4018 res = NULL;
4019 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004020 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004021 Py_DECREF(args);
4022 }
Raymond Hettingerab5dae32002-06-24 13:08:16 +00004023 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004024 if (res != Py_NotImplemented) {
4025 if (res == NULL)
4026 return -2;
4027 c = PyInt_AsLong(res);
4028 Py_DECREF(res);
4029 if (c == -1 && PyErr_Occurred())
4030 return -2;
4031 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
4032 }
4033 Py_DECREF(res);
4034 }
4035 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004036}
4037
Guido van Rossumab3b0342001-09-18 20:38:53 +00004038/* This slot is published for the benefit of try_3way_compare in object.c */
4039int
4040_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00004041{
4042 int c;
4043
Guido van Rossumab3b0342001-09-18 20:38:53 +00004044 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004045 c = half_compare(self, other);
4046 if (c <= 1)
4047 return c;
4048 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00004049 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004050 c = half_compare(other, self);
4051 if (c < -1)
4052 return -2;
4053 if (c <= 1)
4054 return -c;
4055 }
4056 return (void *)self < (void *)other ? -1 :
4057 (void *)self > (void *)other ? 1 : 0;
4058}
4059
4060static PyObject *
4061slot_tp_repr(PyObject *self)
4062{
4063 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004064 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004065
Guido van Rossum60718732001-08-28 17:47:51 +00004066 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004067 if (func != NULL) {
4068 res = PyEval_CallObject(func, NULL);
4069 Py_DECREF(func);
4070 return res;
4071 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00004072 PyErr_Clear();
4073 return PyString_FromFormat("<%s object at %p>",
4074 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004075}
4076
4077static PyObject *
4078slot_tp_str(PyObject *self)
4079{
4080 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004081 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004082
Guido van Rossum60718732001-08-28 17:47:51 +00004083 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004084 if (func != NULL) {
4085 res = PyEval_CallObject(func, NULL);
4086 Py_DECREF(func);
4087 return res;
4088 }
4089 else {
4090 PyErr_Clear();
4091 return slot_tp_repr(self);
4092 }
4093}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004094
4095static long
4096slot_tp_hash(PyObject *self)
4097{
Tim Peters61ce0a92002-12-06 23:38:02 +00004098 PyObject *func;
Guido van Rossum60718732001-08-28 17:47:51 +00004099 static PyObject *hash_str, *eq_str, *cmp_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004100 long h;
4101
Guido van Rossum60718732001-08-28 17:47:51 +00004102 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004103
4104 if (func != NULL) {
Tim Peters61ce0a92002-12-06 23:38:02 +00004105 PyObject *res = PyEval_CallObject(func, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004106 Py_DECREF(func);
4107 if (res == NULL)
4108 return -1;
4109 h = PyInt_AsLong(res);
Tim Peters61ce0a92002-12-06 23:38:02 +00004110 Py_DECREF(res);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004111 }
4112 else {
4113 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004114 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004115 if (func == NULL) {
4116 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004117 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004118 }
4119 if (func != NULL) {
4120 Py_DECREF(func);
4121 PyErr_SetString(PyExc_TypeError, "unhashable type");
4122 return -1;
4123 }
4124 PyErr_Clear();
4125 h = _Py_HashPointer((void *)self);
4126 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004127 if (h == -1 && !PyErr_Occurred())
4128 h = -2;
4129 return h;
4130}
4131
4132static PyObject *
4133slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
4134{
Guido van Rossum60718732001-08-28 17:47:51 +00004135 static PyObject *call_str;
4136 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004137 PyObject *res;
4138
4139 if (meth == NULL)
4140 return NULL;
4141 res = PyObject_Call(meth, args, kwds);
4142 Py_DECREF(meth);
4143 return res;
4144}
4145
Guido van Rossum14a6f832001-10-17 13:59:09 +00004146/* There are two slot dispatch functions for tp_getattro.
4147
4148 - slot_tp_getattro() is used when __getattribute__ is overridden
4149 but no __getattr__ hook is present;
4150
4151 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
4152
Guido van Rossumc334df52002-04-04 23:44:47 +00004153 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
4154 detects the absence of __getattr__ and then installs the simpler slot if
4155 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00004156
Tim Peters6d6c1a32001-08-02 04:15:00 +00004157static PyObject *
4158slot_tp_getattro(PyObject *self, PyObject *name)
4159{
Guido van Rossum14a6f832001-10-17 13:59:09 +00004160 static PyObject *getattribute_str = NULL;
4161 return call_method(self, "__getattribute__", &getattribute_str,
4162 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004163}
4164
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004165static PyObject *
4166slot_tp_getattr_hook(PyObject *self, PyObject *name)
4167{
4168 PyTypeObject *tp = self->ob_type;
4169 PyObject *getattr, *getattribute, *res;
4170 static PyObject *getattribute_str = NULL;
4171 static PyObject *getattr_str = NULL;
4172
4173 if (getattr_str == NULL) {
4174 getattr_str = PyString_InternFromString("__getattr__");
4175 if (getattr_str == NULL)
4176 return NULL;
4177 }
4178 if (getattribute_str == NULL) {
4179 getattribute_str =
4180 PyString_InternFromString("__getattribute__");
4181 if (getattribute_str == NULL)
4182 return NULL;
4183 }
4184 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004185 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004186 /* No __getattr__ hook: use a simpler dispatcher */
4187 tp->tp_getattro = slot_tp_getattro;
4188 return slot_tp_getattro(self, name);
4189 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004190 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004191 if (getattribute == NULL ||
4192 (getattribute->ob_type == &PyWrapperDescr_Type &&
4193 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
4194 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004195 res = PyObject_GenericGetAttr(self, name);
4196 else
4197 res = PyObject_CallFunction(getattribute, "OO", self, name);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004198 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004199 PyErr_Clear();
4200 res = PyObject_CallFunction(getattr, "OO", self, name);
4201 }
4202 return res;
4203}
4204
Tim Peters6d6c1a32001-08-02 04:15:00 +00004205static int
4206slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
4207{
4208 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004209 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004210
4211 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004212 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004213 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004214 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004215 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004216 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004217 if (res == NULL)
4218 return -1;
4219 Py_DECREF(res);
4220 return 0;
4221}
4222
4223/* Map rich comparison operators to their __xx__ namesakes */
4224static char *name_op[] = {
4225 "__lt__",
4226 "__le__",
4227 "__eq__",
4228 "__ne__",
4229 "__gt__",
4230 "__ge__",
4231};
4232
4233static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00004234half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004235{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004236 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004237 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00004238
Guido van Rossum60718732001-08-28 17:47:51 +00004239 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004240 if (func == NULL) {
4241 PyErr_Clear();
4242 Py_INCREF(Py_NotImplemented);
4243 return Py_NotImplemented;
4244 }
4245 args = Py_BuildValue("(O)", other);
4246 if (args == NULL)
4247 res = NULL;
4248 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004249 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004250 Py_DECREF(args);
4251 }
4252 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004253 return res;
4254}
4255
Guido van Rossumb8f63662001-08-15 23:57:02 +00004256/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
4257static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
4258
4259static PyObject *
4260slot_tp_richcompare(PyObject *self, PyObject *other, int op)
4261{
4262 PyObject *res;
4263
4264 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
4265 res = half_richcompare(self, other, op);
4266 if (res != Py_NotImplemented)
4267 return res;
4268 Py_DECREF(res);
4269 }
4270 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
4271 res = half_richcompare(other, self, swapped_op[op]);
4272 if (res != Py_NotImplemented) {
4273 return res;
4274 }
4275 Py_DECREF(res);
4276 }
4277 Py_INCREF(Py_NotImplemented);
4278 return Py_NotImplemented;
4279}
4280
4281static PyObject *
4282slot_tp_iter(PyObject *self)
4283{
4284 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004285 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004286
Guido van Rossum60718732001-08-28 17:47:51 +00004287 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004288 if (func != NULL) {
Guido van Rossum84b2bed2002-08-16 17:01:09 +00004289 PyObject *args;
4290 args = res = PyTuple_New(0);
4291 if (args != NULL) {
4292 res = PyObject_Call(func, args, NULL);
4293 Py_DECREF(args);
4294 }
4295 Py_DECREF(func);
4296 return res;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004297 }
4298 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004299 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004300 if (func == NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00004301 PyErr_SetString(PyExc_TypeError,
4302 "iteration over non-sequence");
Guido van Rossumb8f63662001-08-15 23:57:02 +00004303 return NULL;
4304 }
4305 Py_DECREF(func);
4306 return PySeqIter_New(self);
4307}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004308
4309static PyObject *
4310slot_tp_iternext(PyObject *self)
4311{
Guido van Rossum2730b132001-08-28 18:22:14 +00004312 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00004313 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004314}
4315
Guido van Rossum1a493502001-08-17 16:47:50 +00004316static PyObject *
4317slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4318{
4319 PyTypeObject *tp = self->ob_type;
4320 PyObject *get;
4321 static PyObject *get_str = NULL;
4322
4323 if (get_str == NULL) {
4324 get_str = PyString_InternFromString("__get__");
4325 if (get_str == NULL)
4326 return NULL;
4327 }
4328 get = _PyType_Lookup(tp, get_str);
4329 if (get == NULL) {
4330 /* Avoid further slowdowns */
4331 if (tp->tp_descr_get == slot_tp_descr_get)
4332 tp->tp_descr_get = NULL;
4333 Py_INCREF(self);
4334 return self;
4335 }
Guido van Rossum2c252392001-08-24 10:13:31 +00004336 if (obj == NULL)
4337 obj = Py_None;
4338 if (type == NULL)
4339 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00004340 return PyObject_CallFunction(get, "OOO", self, obj, type);
4341}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004342
4343static int
4344slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
4345{
Guido van Rossum2c252392001-08-24 10:13:31 +00004346 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004347 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00004348
4349 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00004350 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004351 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00004352 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004353 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004354 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004355 if (res == NULL)
4356 return -1;
4357 Py_DECREF(res);
4358 return 0;
4359}
4360
4361static int
4362slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
4363{
Guido van Rossum60718732001-08-28 17:47:51 +00004364 static PyObject *init_str;
4365 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004366 PyObject *res;
4367
4368 if (meth == NULL)
4369 return -1;
4370 res = PyObject_Call(meth, args, kwds);
4371 Py_DECREF(meth);
4372 if (res == NULL)
4373 return -1;
4374 Py_DECREF(res);
4375 return 0;
4376}
4377
4378static PyObject *
4379slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4380{
Guido van Rossum7bed2132002-08-08 21:57:53 +00004381 static PyObject *new_str;
4382 PyObject *func;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004383 PyObject *newargs, *x;
4384 int i, n;
4385
Guido van Rossum7bed2132002-08-08 21:57:53 +00004386 if (new_str == NULL) {
4387 new_str = PyString_InternFromString("__new__");
4388 if (new_str == NULL)
4389 return NULL;
4390 }
4391 func = PyObject_GetAttr((PyObject *)type, new_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004392 if (func == NULL)
4393 return NULL;
4394 assert(PyTuple_Check(args));
4395 n = PyTuple_GET_SIZE(args);
4396 newargs = PyTuple_New(n+1);
4397 if (newargs == NULL)
4398 return NULL;
4399 Py_INCREF(type);
4400 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
4401 for (i = 0; i < n; i++) {
4402 x = PyTuple_GET_ITEM(args, i);
4403 Py_INCREF(x);
4404 PyTuple_SET_ITEM(newargs, i+1, x);
4405 }
4406 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00004407 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004408 Py_DECREF(func);
4409 return x;
4410}
4411
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004412static void
4413slot_tp_del(PyObject *self)
4414{
4415 static PyObject *del_str = NULL;
4416 PyObject *del, *res;
4417 PyObject *error_type, *error_value, *error_traceback;
4418
4419 /* Temporarily resurrect the object. */
4420 assert(self->ob_refcnt == 0);
4421 self->ob_refcnt = 1;
4422
4423 /* Save the current exception, if any. */
4424 PyErr_Fetch(&error_type, &error_value, &error_traceback);
4425
4426 /* Execute __del__ method, if any. */
4427 del = lookup_maybe(self, "__del__", &del_str);
4428 if (del != NULL) {
4429 res = PyEval_CallObject(del, NULL);
4430 if (res == NULL)
4431 PyErr_WriteUnraisable(del);
4432 else
4433 Py_DECREF(res);
4434 Py_DECREF(del);
4435 }
4436
4437 /* Restore the saved exception. */
4438 PyErr_Restore(error_type, error_value, error_traceback);
4439
4440 /* Undo the temporary resurrection; can't use DECREF here, it would
4441 * cause a recursive call.
4442 */
4443 assert(self->ob_refcnt > 0);
4444 if (--self->ob_refcnt == 0)
4445 return; /* this is the normal path out */
4446
4447 /* __del__ resurrected it! Make it look like the original Py_DECREF
4448 * never happened.
4449 */
4450 {
4451 int refcnt = self->ob_refcnt;
4452 _Py_NewReference(self);
4453 self->ob_refcnt = refcnt;
4454 }
4455 assert(!PyType_IS_GC(self->ob_type) ||
4456 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
4457 /* If Py_REF_DEBUG, the original decref dropped _Py_RefTotal, but
4458 * _Py_NewReference bumped it again, so that's a wash.
4459 * If Py_TRACE_REFS, _Py_NewReference re-added self to the object
4460 * chain, so no more to do there either.
4461 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
4462 * _Py_NewReference bumped tp_allocs: both of those need to be
4463 * undone.
4464 */
4465#ifdef COUNT_ALLOCS
4466 --self->ob_type->tp_frees;
4467 --self->ob_type->tp_allocs;
4468#endif
4469}
4470
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004471
4472/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
4473 functions. The offsets here are relative to the 'etype' structure, which
4474 incorporates the additional structures used for numbers, sequences and
4475 mappings. Note that multiple names may map to the same slot (e.g. __eq__,
4476 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00004477 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
4478 terminated with an all-zero entry. (This table is further initialized and
4479 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004480
Guido van Rossum6d204072001-10-21 00:44:31 +00004481typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004482
4483#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00004484#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004485#undef ETSLOT
4486#undef SQSLOT
4487#undef MPSLOT
4488#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00004489#undef UNSLOT
4490#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004491#undef BINSLOT
4492#undef RBINSLOT
4493
Guido van Rossum6d204072001-10-21 00:44:31 +00004494#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004495 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
4496 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00004497#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
4498 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004499 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00004500#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004501 {NAME, offsetof(etype, SLOT), (void *)(FUNCTION), WRAPPER, \
4502 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00004503#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4504 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
4505#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4506 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
4507#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4508 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
4509#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4510 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
4511 "x." NAME "() <==> " DOC)
4512#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4513 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
4514 "x." NAME "(y) <==> x" DOC "y")
4515#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
4516 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
4517 "x." NAME "(y) <==> x" DOC "y")
4518#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
4519 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
4520 "x." NAME "(y) <==> y" DOC "x")
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004521
4522static slotdef slotdefs[] = {
Guido van Rossum6d204072001-10-21 00:44:31 +00004523 SQSLOT("__len__", sq_length, slot_sq_length, wrap_inquiry,
4524 "x.__len__() <==> len(x)"),
4525 SQSLOT("__add__", sq_concat, slot_sq_concat, wrap_binaryfunc,
4526 "x.__add__(y) <==> x+y"),
4527 SQSLOT("__mul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
4528 "x.__mul__(n) <==> x*n"),
4529 SQSLOT("__rmul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
4530 "x.__rmul__(n) <==> n*x"),
4531 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
4532 "x.__getitem__(y) <==> x[y]"),
4533 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_intintargfunc,
4534 "x.__getslice__(i, j) <==> x[i:j]"),
4535 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
4536 "x.__setitem__(i, y) <==> x[i]=y"),
4537 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
4538 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004539 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Guido van Rossum6d204072001-10-21 00:44:31 +00004540 wrap_intintobjargproc,
4541 "x.__setslice__(i, j, y) <==> x[i:j]=y"),
4542 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
4543 "x.__delslice__(i, j) <==> del x[i:j]"),
4544 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
4545 "x.__contains__(y) <==> y in x"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004546 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat,
Guido van Rossum6d204072001-10-21 00:44:31 +00004547 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004548 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat,
Guido van Rossum6d204072001-10-21 00:44:31 +00004549 wrap_intargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004550
Guido van Rossum6d204072001-10-21 00:44:31 +00004551 MPSLOT("__len__", mp_length, slot_mp_length, wrap_inquiry,
4552 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00004553 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004554 wrap_binaryfunc,
4555 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004556 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004557 wrap_objobjargproc,
4558 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004559 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004560 wrap_delitem,
4561 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004562
Guido van Rossum6d204072001-10-21 00:44:31 +00004563 BINSLOT("__add__", nb_add, slot_nb_add,
4564 "+"),
4565 RBINSLOT("__radd__", nb_add, slot_nb_add,
4566 "+"),
4567 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
4568 "-"),
4569 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
4570 "-"),
4571 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
4572 "*"),
4573 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
4574 "*"),
4575 BINSLOT("__div__", nb_divide, slot_nb_divide,
4576 "/"),
4577 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
4578 "/"),
4579 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
4580 "%"),
4581 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
4582 "%"),
4583 BINSLOT("__divmod__", nb_divmod, slot_nb_divmod,
4584 "divmod(x, y)"),
4585 RBINSLOT("__rdivmod__", nb_divmod, slot_nb_divmod,
4586 "divmod(y, x)"),
4587 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
4588 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
4589 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
4590 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
4591 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
4592 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
4593 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
4594 "abs(x)"),
Guido van Rossumdfce3bf2002-03-10 14:11:16 +00004595 UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquiry,
Guido van Rossum6d204072001-10-21 00:44:31 +00004596 "x != 0"),
4597 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
4598 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
4599 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
4600 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
4601 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
4602 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
4603 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
4604 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
4605 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
4606 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
4607 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
4608 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
4609 "x.__coerce__(y) <==> coerce(x, y)"),
4610 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
4611 "int(x)"),
4612 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
4613 "long(x)"),
4614 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
4615 "float(x)"),
4616 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
4617 "oct(x)"),
4618 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
4619 "hex(x)"),
4620 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
4621 wrap_binaryfunc, "+"),
4622 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
4623 wrap_binaryfunc, "-"),
4624 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
4625 wrap_binaryfunc, "*"),
4626 IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
4627 wrap_binaryfunc, "/"),
4628 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
4629 wrap_binaryfunc, "%"),
4630 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
Guido van Rossum6e5680f2002-10-15 01:01:53 +00004631 wrap_binaryfunc, "**"),
Guido van Rossum6d204072001-10-21 00:44:31 +00004632 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
4633 wrap_binaryfunc, "<<"),
4634 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
4635 wrap_binaryfunc, ">>"),
4636 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
4637 wrap_binaryfunc, "&"),
4638 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
4639 wrap_binaryfunc, "^"),
4640 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
4641 wrap_binaryfunc, "|"),
4642 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
4643 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
4644 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
4645 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
4646 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
4647 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
4648 IBSLOT("__itruediv__", nb_inplace_true_divide,
4649 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004650
Guido van Rossum6d204072001-10-21 00:44:31 +00004651 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
4652 "x.__str__() <==> str(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00004653 TPSLOT("__str__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00004654 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
4655 "x.__repr__() <==> repr(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00004656 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00004657 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
4658 "x.__cmp__(y) <==> cmp(x,y)"),
4659 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
4660 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00004661 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
4662 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004663 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00004664 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
4665 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
4666 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
4667 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
4668 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
4669 "x.__setattr__('name', value) <==> x.name = value"),
4670 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
4671 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
4672 "x.__delattr__('name') <==> del x.name"),
4673 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
4674 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
4675 "x.__lt__(y) <==> x<y"),
4676 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
4677 "x.__le__(y) <==> x<=y"),
4678 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
4679 "x.__eq__(y) <==> x==y"),
4680 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
4681 "x.__ne__(y) <==> x!=y"),
4682 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
4683 "x.__gt__(y) <==> x>y"),
4684 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
4685 "x.__ge__(y) <==> x>=y"),
4686 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
4687 "x.__iter__() <==> iter(x)"),
4688 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
4689 "x.next() -> the next value, or raise StopIteration"),
4690 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
4691 "descr.__get__(obj[, type]) -> value"),
4692 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
4693 "descr.__set__(obj, value)"),
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004694 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
4695 wrap_descr_delete, "descr.__delete__(obj)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00004696 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00004697 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00004698 "see x.__class__.__doc__ for signature",
4699 PyWrapperFlag_KEYWORDS),
4700 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004701 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004702 {NULL}
4703};
4704
Guido van Rossumc334df52002-04-04 23:44:47 +00004705/* Given a type pointer and an offset gotten from a slotdef entry, return a
4706 pointer to the actual slot. This is not quite the same as simply adding
4707 the offset to the type pointer, since it takes care to indirect through the
4708 proper indirection pointer (as_buffer, etc.); it returns NULL if the
4709 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004710static void **
4711slotptr(PyTypeObject *type, int offset)
4712{
4713 char *ptr;
4714
Guido van Rossum09638c12002-06-13 19:17:46 +00004715 /* Note: this depends on the order of the members of etype! */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004716 assert(offset >= 0);
4717 assert(offset < offsetof(etype, as_buffer));
Guido van Rossum09638c12002-06-13 19:17:46 +00004718 if (offset >= offsetof(etype, as_sequence)) {
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004719 ptr = (void *)type->tp_as_sequence;
4720 offset -= offsetof(etype, as_sequence);
4721 }
Guido van Rossum09638c12002-06-13 19:17:46 +00004722 else if (offset >= offsetof(etype, as_mapping)) {
4723 ptr = (void *)type->tp_as_mapping;
4724 offset -= offsetof(etype, as_mapping);
4725 }
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004726 else if (offset >= offsetof(etype, as_number)) {
4727 ptr = (void *)type->tp_as_number;
4728 offset -= offsetof(etype, as_number);
4729 }
4730 else {
4731 ptr = (void *)type;
4732 }
4733 if (ptr != NULL)
4734 ptr += offset;
4735 return (void **)ptr;
4736}
Guido van Rossumf040ede2001-08-07 16:40:56 +00004737
Guido van Rossumc334df52002-04-04 23:44:47 +00004738/* Length of array of slotdef pointers used to store slots with the
4739 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
4740 the same __name__, for any __name__. Since that's a static property, it is
4741 appropriate to declare fixed-size arrays for this. */
4742#define MAX_EQUIV 10
4743
4744/* Return a slot pointer for a given name, but ONLY if the attribute has
4745 exactly one slot function. The name must be an interned string. */
4746static void **
4747resolve_slotdups(PyTypeObject *type, PyObject *name)
4748{
4749 /* XXX Maybe this could be optimized more -- but is it worth it? */
4750
4751 /* pname and ptrs act as a little cache */
4752 static PyObject *pname;
4753 static slotdef *ptrs[MAX_EQUIV];
4754 slotdef *p, **pp;
4755 void **res, **ptr;
4756
4757 if (pname != name) {
4758 /* Collect all slotdefs that match name into ptrs. */
4759 pname = name;
4760 pp = ptrs;
4761 for (p = slotdefs; p->name_strobj; p++) {
4762 if (p->name_strobj == name)
4763 *pp++ = p;
4764 }
4765 *pp = NULL;
4766 }
4767
4768 /* Look in all matching slots of the type; if exactly one of these has
4769 a filled-in slot, return its value. Otherwise return NULL. */
4770 res = NULL;
4771 for (pp = ptrs; *pp; pp++) {
4772 ptr = slotptr(type, (*pp)->offset);
4773 if (ptr == NULL || *ptr == NULL)
4774 continue;
4775 if (res != NULL)
4776 return NULL;
4777 res = ptr;
4778 }
4779 return res;
4780}
4781
4782/* Common code for update_these_slots() and fixup_slot_dispatchers(). This
4783 does some incredibly complex thinking and then sticks something into the
4784 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
4785 interests, and then stores a generic wrapper or a specific function into
4786 the slot.) Return a pointer to the next slotdef with a different offset,
4787 because that's convenient for fixup_slot_dispatchers(). */
4788static slotdef *
4789update_one_slot(PyTypeObject *type, slotdef *p)
4790{
4791 PyObject *descr;
4792 PyWrapperDescrObject *d;
4793 void *generic = NULL, *specific = NULL;
4794 int use_generic = 0;
4795 int offset = p->offset;
4796 void **ptr = slotptr(type, offset);
4797
4798 if (ptr == NULL) {
4799 do {
4800 ++p;
4801 } while (p->offset == offset);
4802 return p;
4803 }
4804 do {
4805 descr = _PyType_Lookup(type, p->name_strobj);
4806 if (descr == NULL)
4807 continue;
4808 if (descr->ob_type == &PyWrapperDescr_Type) {
4809 void **tptr = resolve_slotdups(type, p->name_strobj);
4810 if (tptr == NULL || tptr == ptr)
4811 generic = p->function;
4812 d = (PyWrapperDescrObject *)descr;
4813 if (d->d_base->wrapper == p->wrapper &&
4814 PyType_IsSubtype(type, d->d_type))
4815 {
4816 if (specific == NULL ||
4817 specific == d->d_wrapped)
4818 specific = d->d_wrapped;
4819 else
4820 use_generic = 1;
4821 }
4822 }
Guido van Rossum721f62e2002-08-09 02:14:34 +00004823 else if (descr->ob_type == &PyCFunction_Type &&
4824 PyCFunction_GET_FUNCTION(descr) ==
4825 (PyCFunction)tp_new_wrapper &&
4826 strcmp(p->name, "__new__") == 0)
4827 {
4828 /* The __new__ wrapper is not a wrapper descriptor,
4829 so must be special-cased differently.
4830 If we don't do this, creating an instance will
4831 always use slot_tp_new which will look up
4832 __new__ in the MRO which will call tp_new_wrapper
4833 which will look through the base classes looking
4834 for a static base and call its tp_new (usually
4835 PyType_GenericNew), after performing various
4836 sanity checks and constructing a new argument
4837 list. Cut all that nonsense short -- this speeds
4838 up instance creation tremendously. */
4839 specific = type->tp_new;
4840 /* XXX I'm not 100% sure that there isn't a hole
4841 in this reasoning that requires additional
4842 sanity checks. I'll buy the first person to
4843 point out a bug in this reasoning a beer. */
4844 }
Guido van Rossumc334df52002-04-04 23:44:47 +00004845 else {
4846 use_generic = 1;
4847 generic = p->function;
4848 }
4849 } while ((++p)->offset == offset);
4850 if (specific && !use_generic)
4851 *ptr = specific;
4852 else
4853 *ptr = generic;
4854 return p;
4855}
4856
Guido van Rossum22b13872002-08-06 21:41:44 +00004857static int recurse_down_subclasses(PyTypeObject *type, slotdef **pp,
Jeremy Hylton938ace62002-07-17 16:30:39 +00004858 PyObject *name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004859
Guido van Rossumc334df52002-04-04 23:44:47 +00004860/* In the type, update the slots whose slotdefs are gathered in the pp0 array,
4861 and then do the same for all this type's subtypes. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004862static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004863update_these_slots(PyTypeObject *type, slotdef **pp0, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004864{
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004865 slotdef **pp;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004866
Guido van Rossumc334df52002-04-04 23:44:47 +00004867 for (pp = pp0; *pp; pp++)
4868 update_one_slot(type, *pp);
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004869 return recurse_down_subclasses(type, pp0, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004870}
4871
Guido van Rossumc334df52002-04-04 23:44:47 +00004872/* Update the slots whose slotdefs are gathered in the pp array in all (direct
4873 or indirect) subclasses of type. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004874static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004875recurse_down_subclasses(PyTypeObject *type, slotdef **pp, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004876{
4877 PyTypeObject *subclass;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004878 PyObject *ref, *subclasses, *dict;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004879 int i, n;
4880
4881 subclasses = type->tp_subclasses;
4882 if (subclasses == NULL)
4883 return 0;
4884 assert(PyList_Check(subclasses));
4885 n = PyList_GET_SIZE(subclasses);
4886 for (i = 0; i < n; i++) {
4887 ref = PyList_GET_ITEM(subclasses, i);
4888 assert(PyWeakref_CheckRef(ref));
4889 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
Guido van Rossum59e6c532002-06-14 02:27:07 +00004890 assert(subclass != NULL);
4891 if ((PyObject *)subclass == Py_None)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004892 continue;
4893 assert(PyType_Check(subclass));
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004894 /* Avoid recursing down into unaffected classes */
4895 dict = subclass->tp_dict;
4896 if (dict != NULL && PyDict_Check(dict) &&
4897 PyDict_GetItem(dict, name) != NULL)
4898 continue;
4899 if (update_these_slots(subclass, pp, name) < 0)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004900 return -1;
4901 }
4902 return 0;
4903}
4904
Guido van Rossumc334df52002-04-04 23:44:47 +00004905/* Comparison function for qsort() to compare slotdefs by their offset, and
4906 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004907static int
4908slotdef_cmp(const void *aa, const void *bb)
4909{
4910 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
4911 int c = a->offset - b->offset;
4912 if (c != 0)
4913 return c;
4914 else
4915 return a - b;
4916}
4917
Guido van Rossumc334df52002-04-04 23:44:47 +00004918/* Initialize the slotdefs table by adding interned string objects for the
4919 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004920static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004921init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004922{
4923 slotdef *p;
4924 static int initialized = 0;
4925
4926 if (initialized)
4927 return;
4928 for (p = slotdefs; p->name; p++) {
4929 p->name_strobj = PyString_InternFromString(p->name);
4930 if (!p->name_strobj)
Guido van Rossumc334df52002-04-04 23:44:47 +00004931 Py_FatalError("Out of memory interning slotdef names");
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004932 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004933 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
4934 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004935 initialized = 1;
4936}
4937
Guido van Rossumc334df52002-04-04 23:44:47 +00004938/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004939static int
4940update_slot(PyTypeObject *type, PyObject *name)
4941{
Guido van Rossumc334df52002-04-04 23:44:47 +00004942 slotdef *ptrs[MAX_EQUIV];
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004943 slotdef *p;
4944 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004945 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004946
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004947 init_slotdefs();
4948 pp = ptrs;
4949 for (p = slotdefs; p->name; p++) {
4950 /* XXX assume name is interned! */
4951 if (p->name_strobj == name)
4952 *pp++ = p;
4953 }
4954 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004955 for (pp = ptrs; *pp; pp++) {
4956 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004957 offset = p->offset;
4958 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004959 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004960 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004961 }
Guido van Rossumc334df52002-04-04 23:44:47 +00004962 if (ptrs[0] == NULL)
4963 return 0; /* Not an attribute that affects any slots */
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004964 return update_these_slots(type, ptrs, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004965}
4966
Guido van Rossumc334df52002-04-04 23:44:47 +00004967/* Store the proper functions in the slot dispatches at class (type)
4968 definition time, based upon which operations the class overrides in its
4969 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004970static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004971fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004972{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004973 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004974
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004975 init_slotdefs();
Guido van Rossumc334df52002-04-04 23:44:47 +00004976 for (p = slotdefs; p->name; )
4977 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004978}
Guido van Rossum705f0f52001-08-24 16:47:00 +00004979
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004980static void
4981update_all_slots(PyTypeObject* type)
4982{
4983 slotdef *p;
4984
4985 init_slotdefs();
4986 for (p = slotdefs; p->name; p++) {
4987 /* update_slot returns int but can't actually fail */
4988 update_slot(type, p->name_strobj);
4989 }
4990}
4991
Guido van Rossum6d204072001-10-21 00:44:31 +00004992/* This function is called by PyType_Ready() to populate the type's
4993 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00004994 function slot (like tp_repr) that's defined in the type, one or more
4995 corresponding descriptors are added in the type's tp_dict dictionary
4996 under the appropriate name (like __repr__). Some function slots
4997 cause more than one descriptor to be added (for example, the nb_add
4998 slot adds both __add__ and __radd__ descriptors) and some function
4999 slots compete for the same descriptor (for example both sq_item and
5000 mp_subscript generate a __getitem__ descriptor).
5001
5002 In the latter case, the first slotdef entry encoutered wins. Since
5003 slotdef entries are sorted by the offset of the slot in the etype
5004 struct, this gives us some control over disambiguating between
5005 competing slots: the members of struct etype are listed from most
5006 general to least general, so the most general slot is preferred. In
5007 particular, because as_mapping comes before as_sequence, for a type
5008 that defines both mp_subscript and sq_item, mp_subscript wins.
5009
5010 This only adds new descriptors and doesn't overwrite entries in
5011 tp_dict that were previously defined. The descriptors contain a
5012 reference to the C function they must call, so that it's safe if they
5013 are copied into a subtype's __dict__ and the subtype has a different
5014 C function in its slot -- calling the method defined by the
5015 descriptor will call the C function that was used to create it,
5016 rather than the C function present in the slot when it is called.
5017 (This is important because a subtype may have a C function in the
5018 slot that calls the method from the dictionary, and we want to avoid
5019 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00005020
5021static int
5022add_operators(PyTypeObject *type)
5023{
5024 PyObject *dict = type->tp_dict;
5025 slotdef *p;
5026 PyObject *descr;
5027 void **ptr;
5028
5029 init_slotdefs();
5030 for (p = slotdefs; p->name; p++) {
5031 if (p->wrapper == NULL)
5032 continue;
5033 ptr = slotptr(type, p->offset);
5034 if (!ptr || !*ptr)
5035 continue;
5036 if (PyDict_GetItem(dict, p->name_strobj))
5037 continue;
5038 descr = PyDescr_NewWrapper(type, p, *ptr);
5039 if (descr == NULL)
5040 return -1;
5041 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
5042 return -1;
5043 Py_DECREF(descr);
5044 }
5045 if (type->tp_new != NULL) {
5046 if (add_tp_new_wrapper(type) < 0)
5047 return -1;
5048 }
5049 return 0;
5050}
5051
Guido van Rossum705f0f52001-08-24 16:47:00 +00005052
5053/* Cooperative 'super' */
5054
5055typedef struct {
5056 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00005057 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005058 PyObject *obj;
5059} superobject;
5060
Guido van Rossum6f799372001-09-20 20:46:19 +00005061static PyMemberDef super_members[] = {
5062 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
5063 "the class invoking super()"},
5064 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
5065 "the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005066 {0}
5067};
5068
Guido van Rossum705f0f52001-08-24 16:47:00 +00005069static void
5070super_dealloc(PyObject *self)
5071{
5072 superobject *su = (superobject *)self;
5073
Guido van Rossum048eb752001-10-02 21:24:57 +00005074 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005075 Py_XDECREF(su->obj);
5076 Py_XDECREF(su->type);
5077 self->ob_type->tp_free(self);
5078}
5079
5080static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005081super_repr(PyObject *self)
5082{
5083 superobject *su = (superobject *)self;
5084
5085 if (su->obj)
5086 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005087 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005088 su->type ? su->type->tp_name : "NULL",
5089 su->obj->ob_type->tp_name);
5090 else
5091 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005092 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005093 su->type ? su->type->tp_name : "NULL");
5094}
5095
5096static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00005097super_getattro(PyObject *self, PyObject *name)
5098{
5099 superobject *su = (superobject *)self;
5100
5101 if (su->obj != NULL) {
Tim Petersa91e9642001-11-14 23:32:33 +00005102 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005103 PyTypeObject *starttype;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005104 descrgetfunc f;
5105 int i, n;
5106
Guido van Rossum155db9a2002-04-02 17:53:47 +00005107 starttype = su->obj->ob_type;
5108 mro = starttype->tp_mro;
5109
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005110 if (mro == NULL)
5111 n = 0;
5112 else {
5113 assert(PyTuple_Check(mro));
5114 n = PyTuple_GET_SIZE(mro);
5115 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005116 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00005117 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00005118 break;
5119 }
Guido van Rossume705ef12001-08-29 15:47:06 +00005120 if (i >= n && PyType_Check(su->obj)) {
Guido van Rossum155db9a2002-04-02 17:53:47 +00005121 starttype = (PyTypeObject *)(su->obj);
5122 mro = starttype->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005123 if (mro == NULL)
5124 n = 0;
5125 else {
5126 assert(PyTuple_Check(mro));
5127 n = PyTuple_GET_SIZE(mro);
5128 }
Guido van Rossume705ef12001-08-29 15:47:06 +00005129 for (i = 0; i < n; i++) {
5130 if ((PyObject *)(su->type) ==
5131 PyTuple_GET_ITEM(mro, i))
5132 break;
5133 }
Guido van Rossume705ef12001-08-29 15:47:06 +00005134 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005135 i++;
5136 res = NULL;
5137 for (; i < n; i++) {
5138 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00005139 if (PyType_Check(tmp))
5140 dict = ((PyTypeObject *)tmp)->tp_dict;
5141 else if (PyClass_Check(tmp))
5142 dict = ((PyClassObject *)tmp)->cl_dict;
5143 else
5144 continue;
5145 res = PyDict_GetItem(dict, name);
Guido van Rossum5b443c62001-12-03 15:38:28 +00005146 if (res != NULL && !PyDescr_IsData(res)) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00005147 Py_INCREF(res);
5148 f = res->ob_type->tp_descr_get;
5149 if (f != NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00005150 tmp = f(res, su->obj,
5151 (PyObject *)starttype);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005152 Py_DECREF(res);
5153 res = tmp;
5154 }
5155 return res;
5156 }
5157 }
5158 }
5159 return PyObject_GenericGetAttr(self, name);
5160}
5161
Guido van Rossum5b443c62001-12-03 15:38:28 +00005162static int
5163supercheck(PyTypeObject *type, PyObject *obj)
5164{
5165 if (!PyType_IsSubtype(obj->ob_type, type) &&
5166 !(PyType_Check(obj) &&
5167 PyType_IsSubtype((PyTypeObject *)obj, type))) {
5168 PyErr_SetString(PyExc_TypeError,
5169 "super(type, obj): "
5170 "obj must be an instance or subtype of type");
5171 return -1;
5172 }
5173 else
5174 return 0;
5175}
5176
Guido van Rossum705f0f52001-08-24 16:47:00 +00005177static PyObject *
5178super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5179{
5180 superobject *su = (superobject *)self;
5181 superobject *new;
5182
5183 if (obj == NULL || obj == Py_None || su->obj != NULL) {
5184 /* Not binding to an object, or already bound */
5185 Py_INCREF(self);
5186 return self;
5187 }
Guido van Rossum5b443c62001-12-03 15:38:28 +00005188 if (su->ob_type != &PySuper_Type)
5189 /* If su is an instance of a subclass of super,
5190 call its type */
5191 return PyObject_CallFunction((PyObject *)su->ob_type,
5192 "OO", su->type, obj);
5193 else {
5194 /* Inline the common case */
5195 if (supercheck(su->type, obj) < 0)
5196 return NULL;
5197 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
5198 NULL, NULL);
5199 if (new == NULL)
5200 return NULL;
5201 Py_INCREF(su->type);
5202 Py_INCREF(obj);
5203 new->type = su->type;
5204 new->obj = obj;
5205 return (PyObject *)new;
5206 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005207}
5208
5209static int
5210super_init(PyObject *self, PyObject *args, PyObject *kwds)
5211{
5212 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00005213 PyTypeObject *type;
5214 PyObject *obj = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005215
5216 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
5217 return -1;
5218 if (obj == Py_None)
5219 obj = NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005220 if (obj != NULL && supercheck(type, obj) < 0)
Guido van Rossum705f0f52001-08-24 16:47:00 +00005221 return -1;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005222 Py_INCREF(type);
5223 Py_XINCREF(obj);
5224 su->type = type;
5225 su->obj = obj;
5226 return 0;
5227}
5228
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005229PyDoc_STRVAR(super_doc,
Guido van Rossum705f0f52001-08-24 16:47:00 +00005230"super(type) -> unbound super object\n"
5231"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00005232"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00005233"Typical use to call a cooperative superclass method:\n"
5234"class C(B):\n"
5235" def meth(self, arg):\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005236" super(C, self).meth(arg)");
Guido van Rossum705f0f52001-08-24 16:47:00 +00005237
Guido van Rossum048eb752001-10-02 21:24:57 +00005238static int
5239super_traverse(PyObject *self, visitproc visit, void *arg)
5240{
5241 superobject *su = (superobject *)self;
5242 int err;
5243
5244#define VISIT(SLOT) \
5245 if (SLOT) { \
5246 err = visit((PyObject *)(SLOT), arg); \
5247 if (err) \
5248 return err; \
5249 }
5250
5251 VISIT(su->obj);
5252 VISIT(su->type);
5253
5254#undef VISIT
5255
5256 return 0;
5257}
5258
Guido van Rossum705f0f52001-08-24 16:47:00 +00005259PyTypeObject PySuper_Type = {
5260 PyObject_HEAD_INIT(&PyType_Type)
5261 0, /* ob_size */
5262 "super", /* tp_name */
5263 sizeof(superobject), /* tp_basicsize */
5264 0, /* tp_itemsize */
5265 /* methods */
5266 super_dealloc, /* tp_dealloc */
5267 0, /* tp_print */
5268 0, /* tp_getattr */
5269 0, /* tp_setattr */
5270 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005271 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005272 0, /* tp_as_number */
5273 0, /* tp_as_sequence */
5274 0, /* tp_as_mapping */
5275 0, /* tp_hash */
5276 0, /* tp_call */
5277 0, /* tp_str */
5278 super_getattro, /* tp_getattro */
5279 0, /* tp_setattro */
5280 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00005281 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
5282 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005283 super_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00005284 super_traverse, /* tp_traverse */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005285 0, /* tp_clear */
5286 0, /* tp_richcompare */
5287 0, /* tp_weaklistoffset */
5288 0, /* tp_iter */
5289 0, /* tp_iternext */
5290 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005291 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005292 0, /* tp_getset */
5293 0, /* tp_base */
5294 0, /* tp_dict */
5295 super_descr_get, /* tp_descr_get */
5296 0, /* tp_descr_set */
5297 0, /* tp_dictoffset */
5298 super_init, /* tp_init */
5299 PyType_GenericAlloc, /* tp_alloc */
5300 PyType_GenericNew, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00005301 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005302};