blob: 45a229a9d9a198607289042a587f1f23dd302044 [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 */
Guido van Rossum0906e072002-08-07 20:42:09 +0000643 PyObject_GC_UnTrack(self);
Guido van Rossum22b13872002-08-06 21:41:44 +0000644 Py_TRASHCAN_SAFE_BEGIN(self);
645 _PyObject_GC_TRACK(self); /* We'll untrack for real later */
646
647 /* Maybe call finalizer; exit early if resurrected */
Guido van Rossumfebd61d2002-08-08 20:55:20 +0000648 if (type->tp_del) {
649 type->tp_del(self);
650 if (self->ob_refcnt > 0)
651 goto endlabel;
652 }
Guido van Rossum7ad2d1e2001-10-29 22:11:00 +0000653
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000654 /* Find the nearest base with a different tp_dealloc
655 and clear slots while we're at it */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000656 base = type;
657 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
658 if (base->ob_size)
659 clear_slots(base, self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000660 base = base->tp_base;
661 assert(base);
Guido van Rossum14227b42001-12-06 02:35:58 +0000662 }
663
Tim Peters6d6c1a32001-08-02 04:15:00 +0000664 /* If we added a dict, DECREF it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000665 if (type->tp_dictoffset && !base->tp_dictoffset) {
666 PyObject **dictptr = _PyObject_GetDictPtr(self);
667 if (dictptr != NULL) {
668 PyObject *dict = *dictptr;
669 if (dict != NULL) {
670 Py_DECREF(dict);
671 *dictptr = NULL;
672 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000673 }
674 }
675
Guido van Rossum9676b222001-08-17 20:32:36 +0000676 /* If we added weaklist, we clear it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000677 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
Guido van Rossum9676b222001-08-17 20:32:36 +0000678 PyObject_ClearWeakRefs(self);
679
Tim Peters6d6c1a32001-08-02 04:15:00 +0000680 /* Finalize GC if the base doesn't do GC and we do */
Guido van Rossum22b13872002-08-06 21:41:44 +0000681 if (!PyType_IS_GC(base))
Guido van Rossum048eb752001-10-02 21:24:57 +0000682 _PyObject_GC_UNTRACK(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000683
684 /* Call the base tp_dealloc() */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000685 assert(basedealloc);
686 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000687
688 /* Can't reference self beyond this point */
Guido van Rossum22b13872002-08-06 21:41:44 +0000689 Py_DECREF(type);
690
Guido van Rossum0906e072002-08-07 20:42:09 +0000691 endlabel:
Guido van Rossum22b13872002-08-06 21:41:44 +0000692 Py_TRASHCAN_SAFE_END(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000693}
694
Jeremy Hylton938ace62002-07-17 16:30:39 +0000695static PyTypeObject *solid_base(PyTypeObject *type);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000696
Tim Peters6d6c1a32001-08-02 04:15:00 +0000697/* type test with subclassing support */
698
699int
700PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
701{
702 PyObject *mro;
703
Guido van Rossum9478d072001-09-07 18:52:13 +0000704 if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
705 return b == a || b == &PyBaseObject_Type;
706
Tim Peters6d6c1a32001-08-02 04:15:00 +0000707 mro = a->tp_mro;
708 if (mro != NULL) {
709 /* Deal with multiple inheritance without recursion
710 by walking the MRO tuple */
711 int i, n;
712 assert(PyTuple_Check(mro));
713 n = PyTuple_GET_SIZE(mro);
714 for (i = 0; i < n; i++) {
715 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
716 return 1;
717 }
718 return 0;
719 }
720 else {
721 /* a is not completely initilized yet; follow tp_base */
722 do {
723 if (a == b)
724 return 1;
725 a = a->tp_base;
726 } while (a != NULL);
727 return b == &PyBaseObject_Type;
728 }
729}
730
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000731/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +0000732 without looking in the instance dictionary
733 (so we can't use PyObject_GetAttr) but still binding
734 it to the instance. The arguments are the object,
735 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000736 static variable used to cache the interned Python string.
737
738 Two variants:
739
740 - lookup_maybe() returns NULL without raising an exception
741 when the _PyType_Lookup() call fails;
742
743 - lookup_method() always raises an exception upon errors.
744*/
Guido van Rossum60718732001-08-28 17:47:51 +0000745
746static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000747lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +0000748{
749 PyObject *res;
750
751 if (*attrobj == NULL) {
752 *attrobj = PyString_InternFromString(attrstr);
753 if (*attrobj == NULL)
754 return NULL;
755 }
756 res = _PyType_Lookup(self->ob_type, *attrobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000757 if (res != NULL) {
Guido van Rossum60718732001-08-28 17:47:51 +0000758 descrgetfunc f;
759 if ((f = res->ob_type->tp_descr_get) == NULL)
760 Py_INCREF(res);
761 else
762 res = f(res, self, (PyObject *)(self->ob_type));
763 }
764 return res;
765}
766
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000767static PyObject *
768lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
769{
770 PyObject *res = lookup_maybe(self, attrstr, attrobj);
771 if (res == NULL && !PyErr_Occurred())
772 PyErr_SetObject(PyExc_AttributeError, *attrobj);
773 return res;
774}
775
Guido van Rossum2730b132001-08-28 18:22:14 +0000776/* A variation of PyObject_CallMethod that uses lookup_method()
777 instead of PyObject_GetAttrString(). This uses the same convention
778 as lookup_method to cache the interned name string object. */
779
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000780static PyObject *
Guido van Rossum2730b132001-08-28 18:22:14 +0000781call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
782{
783 va_list va;
784 PyObject *args, *func = 0, *retval;
Guido van Rossum2730b132001-08-28 18:22:14 +0000785 va_start(va, format);
786
Guido van Rossumda21c012001-10-03 00:50:18 +0000787 func = lookup_maybe(o, name, nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000788 if (func == NULL) {
789 va_end(va);
790 if (!PyErr_Occurred())
Guido van Rossumda21c012001-10-03 00:50:18 +0000791 PyErr_SetObject(PyExc_AttributeError, *nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000792 return NULL;
793 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000794
795 if (format && *format)
796 args = Py_VaBuildValue(format, va);
797 else
798 args = PyTuple_New(0);
799
800 va_end(va);
801
802 if (args == NULL)
803 return NULL;
804
805 assert(PyTuple_Check(args));
806 retval = PyObject_Call(func, args, NULL);
807
808 Py_DECREF(args);
809 Py_DECREF(func);
810
811 return retval;
812}
813
814/* Clone of call_method() that returns NotImplemented when the lookup fails. */
815
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000816static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000817call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
818{
819 va_list va;
820 PyObject *args, *func = 0, *retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000821 va_start(va, format);
822
Guido van Rossumda21c012001-10-03 00:50:18 +0000823 func = lookup_maybe(o, name, nameobj);
Guido van Rossum2730b132001-08-28 18:22:14 +0000824 if (func == NULL) {
825 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000826 if (!PyErr_Occurred()) {
827 Py_INCREF(Py_NotImplemented);
828 return Py_NotImplemented;
829 }
Guido van Rossum717ce002001-09-14 16:58:08 +0000830 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +0000831 }
832
833 if (format && *format)
834 args = Py_VaBuildValue(format, va);
835 else
836 args = PyTuple_New(0);
837
838 va_end(va);
839
Guido van Rossum717ce002001-09-14 16:58:08 +0000840 if (args == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +0000841 return NULL;
842
Guido van Rossum717ce002001-09-14 16:58:08 +0000843 assert(PyTuple_Check(args));
844 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +0000845
846 Py_DECREF(args);
847 Py_DECREF(func);
848
849 return retval;
850}
851
Tim Petersa91e9642001-11-14 23:32:33 +0000852static int
853fill_classic_mro(PyObject *mro, PyObject *cls)
854{
855 PyObject *bases, *base;
856 int i, n;
857
858 assert(PyList_Check(mro));
859 assert(PyClass_Check(cls));
860 i = PySequence_Contains(mro, cls);
861 if (i < 0)
862 return -1;
863 if (!i) {
864 if (PyList_Append(mro, cls) < 0)
865 return -1;
866 }
867 bases = ((PyClassObject *)cls)->cl_bases;
868 assert(bases && PyTuple_Check(bases));
869 n = PyTuple_GET_SIZE(bases);
870 for (i = 0; i < n; i++) {
871 base = PyTuple_GET_ITEM(bases, i);
872 if (fill_classic_mro(mro, base) < 0)
873 return -1;
874 }
875 return 0;
876}
877
878static PyObject *
879classic_mro(PyObject *cls)
880{
881 PyObject *mro;
882
883 assert(PyClass_Check(cls));
884 mro = PyList_New(0);
885 if (mro != NULL) {
886 if (fill_classic_mro(mro, cls) == 0)
887 return mro;
888 Py_DECREF(mro);
889 }
890 return NULL;
891}
892
Tim Petersea7f75d2002-12-07 21:39:16 +0000893/*
Guido van Rossum1f121312002-11-14 19:49:16 +0000894 Method resolution order algorithm C3 described in
895 "A Monotonic Superclass Linearization for Dylan",
896 by Kim Barrett, Bob Cassel, Paul Haahr,
Tim Petersea7f75d2002-12-07 21:39:16 +0000897 David A. Moon, Keith Playford, and P. Tucker Withington.
Guido van Rossum1f121312002-11-14 19:49:16 +0000898 (OOPSLA 1996)
899
Guido van Rossum98f33732002-11-25 21:36:54 +0000900 Some notes about the rules implied by C3:
901
Tim Petersea7f75d2002-12-07 21:39:16 +0000902 No duplicate bases.
Guido van Rossum98f33732002-11-25 21:36:54 +0000903 It isn't legal to repeat a class in a list of base classes.
904
905 The next three properties are the 3 constraints in "C3".
906
Tim Petersea7f75d2002-12-07 21:39:16 +0000907 Local precendece order.
Guido van Rossum98f33732002-11-25 21:36:54 +0000908 If A precedes B in C's MRO, then A will precede B in the MRO of all
909 subclasses of C.
910
911 Monotonicity.
912 The MRO of a class must be an extension without reordering of the
913 MRO of each of its superclasses.
914
915 Extended Precedence Graph (EPG).
916 Linearization is consistent if there is a path in the EPG from
917 each class to all its successors in the linearization. See
918 the paper for definition of EPG.
Guido van Rossum1f121312002-11-14 19:49:16 +0000919 */
920
Tim Petersea7f75d2002-12-07 21:39:16 +0000921static int
Guido van Rossum1f121312002-11-14 19:49:16 +0000922tail_contains(PyObject *list, int whence, PyObject *o) {
923 int j, size;
924 size = PyList_GET_SIZE(list);
925
926 for (j = whence+1; j < size; j++) {
927 if (PyList_GET_ITEM(list, j) == o)
928 return 1;
929 }
930 return 0;
931}
932
Guido van Rossum98f33732002-11-25 21:36:54 +0000933static PyObject *
934class_name(PyObject *cls)
935{
936 PyObject *name = PyObject_GetAttrString(cls, "__name__");
937 if (name == NULL) {
938 PyErr_Clear();
939 Py_XDECREF(name);
940 name = PyObject_Repr(cls);
941 }
942 if (name == NULL)
943 return NULL;
944 if (!PyString_Check(name)) {
945 Py_DECREF(name);
946 return NULL;
947 }
948 return name;
949}
950
951static int
952check_duplicates(PyObject *list)
953{
954 int i, j, n;
955 /* Let's use a quadratic time algorithm,
956 assuming that the bases lists is short.
957 */
958 n = PyList_GET_SIZE(list);
959 for (i = 0; i < n; i++) {
960 PyObject *o = PyList_GET_ITEM(list, i);
961 for (j = i + 1; j < n; j++) {
962 if (PyList_GET_ITEM(list, j) == o) {
963 o = class_name(o);
964 PyErr_Format(PyExc_TypeError,
965 "duplicate base class %s",
966 o ? PyString_AS_STRING(o) : "?");
967 Py_XDECREF(o);
968 return -1;
969 }
970 }
971 }
972 return 0;
973}
974
975/* Raise a TypeError for an MRO order disagreement.
976
977 It's hard to produce a good error message. In the absence of better
978 insight into error reporting, report the classes that were candidates
979 to be put next into the MRO. There is some conflict between the
980 order in which they should be put in the MRO, but it's hard to
981 diagnose what constraint can't be satisfied.
982*/
983
984static void
985set_mro_error(PyObject *to_merge, int *remain)
986{
987 int i, n, off, to_merge_size;
988 char buf[1000];
989 PyObject *k, *v;
990 PyObject *set = PyDict_New();
991
992 to_merge_size = PyList_GET_SIZE(to_merge);
993 for (i = 0; i < to_merge_size; i++) {
994 PyObject *L = PyList_GET_ITEM(to_merge, i);
995 if (remain[i] < PyList_GET_SIZE(L)) {
996 PyObject *c = PyList_GET_ITEM(L, remain[i]);
997 if (PyDict_SetItem(set, c, Py_None) < 0)
998 return;
999 }
1000 }
1001 n = PyDict_Size(set);
1002
1003 off = PyOS_snprintf(buf, sizeof(buf), "MRO conflict among bases");
1004 i = 0;
1005 while (PyDict_Next(set, &i, &k, &v) && off < sizeof(buf)) {
1006 PyObject *name = class_name(k);
1007 off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s",
1008 name ? PyString_AS_STRING(name) : "?");
1009 Py_XDECREF(name);
1010 if (--n && off+1 < sizeof(buf)) {
1011 buf[off++] = ',';
1012 buf[off] = '\0';
1013 }
1014 }
1015 PyErr_SetString(PyExc_TypeError, buf);
1016 Py_DECREF(set);
1017}
1018
Tim Petersea7f75d2002-12-07 21:39:16 +00001019static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001020pmerge(PyObject *acc, PyObject* to_merge) {
1021 int i, j, to_merge_size;
1022 int *remain;
1023 int ok, empty_cnt;
Tim Petersea7f75d2002-12-07 21:39:16 +00001024
Guido van Rossum1f121312002-11-14 19:49:16 +00001025 to_merge_size = PyList_GET_SIZE(to_merge);
1026
Guido van Rossum98f33732002-11-25 21:36:54 +00001027 /* remain stores an index into each sublist of to_merge.
1028 remain[i] is the index of the next base in to_merge[i]
1029 that is not included in acc.
1030 */
Guido van Rossum1f121312002-11-14 19:49:16 +00001031 remain = PyMem_MALLOC(SIZEOF_INT*to_merge_size);
1032 if (remain == NULL)
1033 return -1;
1034 for (i = 0; i < to_merge_size; i++)
1035 remain[i] = 0;
1036
1037 again:
1038 empty_cnt = 0;
1039 for (i = 0; i < to_merge_size; i++) {
1040 PyObject *candidate;
Tim Petersea7f75d2002-12-07 21:39:16 +00001041
Guido van Rossum1f121312002-11-14 19:49:16 +00001042 PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
1043
1044 if (remain[i] >= PyList_GET_SIZE(cur_list)) {
1045 empty_cnt++;
1046 continue;
1047 }
1048
Guido van Rossum98f33732002-11-25 21:36:54 +00001049 /* Choose next candidate for MRO.
1050
1051 The input sequences alone can determine the choice.
1052 If not, choose the class which appears in the MRO
1053 of the earliest direct superclass of the new class.
1054 */
1055
Guido van Rossum1f121312002-11-14 19:49:16 +00001056 candidate = PyList_GET_ITEM(cur_list, remain[i]);
1057 for (j = 0; j < to_merge_size; j++) {
1058 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum98f33732002-11-25 21:36:54 +00001059 if (tail_contains(j_lst, remain[j], candidate)) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001060 goto skip; /* continue outer loop */
Guido van Rossum98f33732002-11-25 21:36:54 +00001061 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001062 }
1063 ok = PyList_Append(acc, candidate);
1064 if (ok < 0) {
1065 PyMem_Free(remain);
1066 return -1;
1067 }
1068 for (j = 0; j < to_merge_size; j++) {
1069 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
1070 if (PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
1071 remain[j]++;
1072 }
1073 }
1074 goto again;
Tim Peters9a6b8d82002-11-14 23:22:33 +00001075 skip: ;
Guido van Rossum1f121312002-11-14 19:49:16 +00001076 }
1077
Guido van Rossum98f33732002-11-25 21:36:54 +00001078 if (empty_cnt == to_merge_size) {
1079 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001080 return 0;
Guido van Rossum98f33732002-11-25 21:36:54 +00001081 }
1082 set_mro_error(to_merge, remain);
1083 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001084 return -1;
1085}
1086
Tim Peters6d6c1a32001-08-02 04:15:00 +00001087static PyObject *
1088mro_implementation(PyTypeObject *type)
1089{
1090 int i, n, ok;
1091 PyObject *bases, *result;
Guido van Rossum1f121312002-11-14 19:49:16 +00001092 PyObject *to_merge, *bases_aslist;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001093
Guido van Rossum63517572002-06-18 16:44:57 +00001094 if(type->tp_dict == NULL) {
1095 if(PyType_Ready(type) < 0)
1096 return NULL;
1097 }
1098
Guido van Rossum98f33732002-11-25 21:36:54 +00001099 /* Find a superclass linearization that honors the constraints
1100 of the explicit lists of bases and the constraints implied by
Tim Petersea7f75d2002-12-07 21:39:16 +00001101 each base class.
Guido van Rossum98f33732002-11-25 21:36:54 +00001102
1103 to_merge is a list of lists, where each list is a superclass
1104 linearization implied by a base class. The last element of
1105 to_merge is the declared list of bases.
1106 */
1107
Tim Peters6d6c1a32001-08-02 04:15:00 +00001108 bases = type->tp_bases;
1109 n = PyTuple_GET_SIZE(bases);
Guido van Rossum1f121312002-11-14 19:49:16 +00001110
1111 to_merge = PyList_New(n+1);
1112 if (to_merge == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001113 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001114
Tim Peters6d6c1a32001-08-02 04:15:00 +00001115 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001116 PyObject *base = PyTuple_GET_ITEM(bases, i);
1117 PyObject *parentMRO;
1118 if (PyType_Check(base))
1119 parentMRO = PySequence_List(
1120 ((PyTypeObject*)base)->tp_mro);
1121 else
1122 parentMRO = classic_mro(base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001123 if (parentMRO == NULL) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001124 Py_DECREF(to_merge);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001125 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001126 }
1127
1128 PyList_SET_ITEM(to_merge, i, parentMRO);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001129 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001130
1131 bases_aslist = PySequence_List(bases);
1132 if (bases_aslist == NULL) {
1133 Py_DECREF(to_merge);
1134 return NULL;
1135 }
Guido van Rossum98f33732002-11-25 21:36:54 +00001136 /* This is just a basic sanity check. */
1137 if (check_duplicates(bases_aslist) < 0) {
1138 Py_DECREF(to_merge);
1139 Py_DECREF(bases_aslist);
1140 return NULL;
1141 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001142 PyList_SET_ITEM(to_merge, n, bases_aslist);
1143
1144 result = Py_BuildValue("[O]", (PyObject *)type);
1145 if (result == NULL) {
1146 Py_DECREF(to_merge);
1147 return NULL;
1148 }
1149
1150 ok = pmerge(result, to_merge);
1151 Py_DECREF(to_merge);
1152 if (ok < 0) {
1153 Py_DECREF(result);
1154 return NULL;
1155 }
1156
Tim Peters6d6c1a32001-08-02 04:15:00 +00001157 return result;
1158}
1159
1160static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001161mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001162{
1163 PyTypeObject *type = (PyTypeObject *)self;
1164
Tim Peters6d6c1a32001-08-02 04:15:00 +00001165 return mro_implementation(type);
1166}
1167
1168static int
1169mro_internal(PyTypeObject *type)
1170{
1171 PyObject *mro, *result, *tuple;
1172
1173 if (type->ob_type == &PyType_Type) {
1174 result = mro_implementation(type);
1175 }
1176 else {
Guido van Rossum60718732001-08-28 17:47:51 +00001177 static PyObject *mro_str;
1178 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001179 if (mro == NULL)
1180 return -1;
1181 result = PyObject_CallObject(mro, NULL);
1182 Py_DECREF(mro);
1183 }
1184 if (result == NULL)
1185 return -1;
1186 tuple = PySequence_Tuple(result);
1187 Py_DECREF(result);
1188 type->tp_mro = tuple;
1189 return 0;
1190}
1191
1192
1193/* Calculate the best base amongst multiple base classes.
1194 This is the first one that's on the path to the "solid base". */
1195
1196static PyTypeObject *
1197best_base(PyObject *bases)
1198{
1199 int i, n;
1200 PyTypeObject *base, *winner, *candidate, *base_i;
Tim Petersa91e9642001-11-14 23:32:33 +00001201 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001202
1203 assert(PyTuple_Check(bases));
1204 n = PyTuple_GET_SIZE(bases);
1205 assert(n > 0);
Tim Petersa91e9642001-11-14 23:32:33 +00001206 base = NULL;
1207 winner = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001208 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001209 base_proto = PyTuple_GET_ITEM(bases, i);
1210 if (PyClass_Check(base_proto))
1211 continue;
1212 if (!PyType_Check(base_proto)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001213 PyErr_SetString(
1214 PyExc_TypeError,
1215 "bases must be types");
1216 return NULL;
1217 }
Tim Petersa91e9642001-11-14 23:32:33 +00001218 base_i = (PyTypeObject *)base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001219 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001220 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001221 return NULL;
1222 }
1223 candidate = solid_base(base_i);
Tim Petersa91e9642001-11-14 23:32:33 +00001224 if (winner == NULL) {
1225 winner = candidate;
1226 base = base_i;
1227 }
1228 else if (PyType_IsSubtype(winner, candidate))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001229 ;
1230 else if (PyType_IsSubtype(candidate, winner)) {
1231 winner = candidate;
1232 base = base_i;
1233 }
1234 else {
1235 PyErr_SetString(
1236 PyExc_TypeError,
1237 "multiple bases have "
1238 "instance lay-out conflict");
1239 return NULL;
1240 }
1241 }
Guido van Rossume54616c2001-12-14 04:19:56 +00001242 if (base == NULL)
1243 PyErr_SetString(PyExc_TypeError,
1244 "a new-style class can't have only classic bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001245 return base;
1246}
1247
1248static int
1249extra_ivars(PyTypeObject *type, PyTypeObject *base)
1250{
Neil Schemenauerc806c882001-08-29 23:54:54 +00001251 size_t t_size = type->tp_basicsize;
1252 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001253
Guido van Rossum9676b222001-08-17 20:32:36 +00001254 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001255 if (type->tp_itemsize || base->tp_itemsize) {
1256 /* If itemsize is involved, stricter rules */
1257 return t_size != b_size ||
1258 type->tp_itemsize != base->tp_itemsize;
1259 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001260 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
1261 type->tp_weaklistoffset + sizeof(PyObject *) == t_size)
1262 t_size -= sizeof(PyObject *);
1263 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
1264 type->tp_dictoffset + sizeof(PyObject *) == t_size)
1265 t_size -= sizeof(PyObject *);
1266
1267 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001268}
1269
1270static PyTypeObject *
1271solid_base(PyTypeObject *type)
1272{
1273 PyTypeObject *base;
1274
1275 if (type->tp_base)
1276 base = solid_base(type->tp_base);
1277 else
1278 base = &PyBaseObject_Type;
1279 if (extra_ivars(type, base))
1280 return type;
1281 else
1282 return base;
1283}
1284
Jeremy Hylton938ace62002-07-17 16:30:39 +00001285static void object_dealloc(PyObject *);
1286static int object_init(PyObject *, PyObject *, PyObject *);
1287static int update_slot(PyTypeObject *, PyObject *);
1288static void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001289
1290static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001291subtype_dict(PyObject *obj, void *context)
1292{
1293 PyObject **dictptr = _PyObject_GetDictPtr(obj);
1294 PyObject *dict;
1295
1296 if (dictptr == NULL) {
1297 PyErr_SetString(PyExc_AttributeError,
1298 "This object has no __dict__");
1299 return NULL;
1300 }
1301 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +00001302 if (dict == NULL)
1303 *dictptr = dict = PyDict_New();
1304 Py_XINCREF(dict);
1305 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001306}
1307
Guido van Rossum6661be32001-10-26 04:26:12 +00001308static int
1309subtype_setdict(PyObject *obj, PyObject *value, void *context)
1310{
1311 PyObject **dictptr = _PyObject_GetDictPtr(obj);
1312 PyObject *dict;
1313
1314 if (dictptr == NULL) {
1315 PyErr_SetString(PyExc_AttributeError,
1316 "This object has no __dict__");
1317 return -1;
1318 }
Guido van Rossumd331cb52001-12-05 19:46:42 +00001319 if (value != NULL && !PyDict_Check(value)) {
Guido van Rossum6661be32001-10-26 04:26:12 +00001320 PyErr_SetString(PyExc_TypeError,
1321 "__dict__ must be set to a dictionary");
1322 return -1;
1323 }
1324 dict = *dictptr;
Guido van Rossumd331cb52001-12-05 19:46:42 +00001325 Py_XINCREF(value);
Guido van Rossum6661be32001-10-26 04:26:12 +00001326 *dictptr = value;
1327 Py_XDECREF(dict);
1328 return 0;
1329}
1330
Guido van Rossumad47da02002-08-12 19:05:44 +00001331static PyObject *
1332subtype_getweakref(PyObject *obj, void *context)
1333{
1334 PyObject **weaklistptr;
1335 PyObject *result;
1336
1337 if (obj->ob_type->tp_weaklistoffset == 0) {
1338 PyErr_SetString(PyExc_AttributeError,
1339 "This object has no __weaklist__");
1340 return NULL;
1341 }
1342 assert(obj->ob_type->tp_weaklistoffset > 0);
1343 assert(obj->ob_type->tp_weaklistoffset + sizeof(PyObject *) <=
Guido van Rossum3747a0f2002-08-12 19:25:08 +00001344 (size_t)(obj->ob_type->tp_basicsize));
Guido van Rossumad47da02002-08-12 19:05:44 +00001345 weaklistptr = (PyObject **)
Guido van Rossum3747a0f2002-08-12 19:25:08 +00001346 ((char *)obj + obj->ob_type->tp_weaklistoffset);
Guido van Rossumad47da02002-08-12 19:05:44 +00001347 if (*weaklistptr == NULL)
1348 result = Py_None;
1349 else
1350 result = *weaklistptr;
1351 Py_INCREF(result);
1352 return result;
1353}
1354
Neil Schemenauerf23473f2001-10-21 22:28:58 +00001355static PyGetSetDef subtype_getsets[] = {
Guido van Rossumad47da02002-08-12 19:05:44 +00001356 /* Not all objects have these attributes!
1357 The descriptor's __get__ method may raise AttributeError. */
1358 {"__dict__", subtype_dict, subtype_setdict,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001359 PyDoc_STR("dictionary for instance variables (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001360 {"__weakref__", subtype_getweakref, NULL,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001361 PyDoc_STR("list of weak references to the object (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001362 {0}
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001363};
1364
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001365/* bozo: __getstate__ that raises TypeError */
1366
1367static PyObject *
1368bozo_func(PyObject *self, PyObject *args)
1369{
1370 PyErr_SetString(PyExc_TypeError,
1371 "a class that defines __slots__ without "
1372 "defining __getstate__ cannot be pickled");
1373 return NULL;
1374}
1375
Neal Norwitz93c1e232002-03-31 16:06:11 +00001376static PyMethodDef bozo_ml = {"__getstate__", bozo_func, METH_VARARGS};
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001377
1378static PyObject *bozo_obj = NULL;
1379
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001380static int
1381valid_identifier(PyObject *s)
1382{
Guido van Rossum03013a02002-07-16 14:30:28 +00001383 unsigned char *p;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001384 int i, n;
1385
1386 if (!PyString_Check(s)) {
1387 PyErr_SetString(PyExc_TypeError,
1388 "__slots__ must be strings");
1389 return 0;
1390 }
Guido van Rossum03013a02002-07-16 14:30:28 +00001391 p = (unsigned char *) PyString_AS_STRING(s);
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001392 n = PyString_GET_SIZE(s);
1393 /* We must reject an empty name. As a hack, we bump the
1394 length to 1 so that the loop will balk on the trailing \0. */
1395 if (n == 0)
1396 n = 1;
1397 for (i = 0; i < n; i++, p++) {
1398 if (!(i == 0 ? isalpha(*p) : isalnum(*p)) && *p != '_') {
1399 PyErr_SetString(PyExc_TypeError,
1400 "__slots__ must be identifiers");
1401 return 0;
1402 }
1403 }
1404 return 1;
1405}
1406
Martin v. Löwisd919a592002-10-14 21:07:28 +00001407#ifdef Py_USING_UNICODE
1408/* Replace Unicode objects in slots. */
1409
1410static PyObject *
1411_unicode_to_string(PyObject *slots, int nslots)
1412{
1413 PyObject *tmp = slots;
1414 PyObject *o, *o1;
1415 int i;
1416 intintargfunc copy = slots->ob_type->tp_as_sequence->sq_slice;
1417 for (i = 0; i < nslots; i++) {
1418 if (PyUnicode_Check(o = PyTuple_GET_ITEM(tmp, i))) {
1419 if (tmp == slots) {
1420 tmp = copy(slots, 0, PyTuple_GET_SIZE(slots));
1421 if (tmp == NULL)
1422 return NULL;
1423 }
1424 o1 = _PyUnicode_AsDefaultEncodedString
1425 (o, NULL);
1426 if (o1 == NULL) {
1427 Py_DECREF(tmp);
1428 return 0;
1429 }
1430 Py_INCREF(o1);
1431 Py_DECREF(o);
1432 PyTuple_SET_ITEM(tmp, i, o1);
1433 }
1434 }
1435 return tmp;
1436}
1437#endif
1438
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001439static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001440type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
1441{
1442 PyObject *name, *bases, *dict;
1443 static char *kwlist[] = {"name", "bases", "dict", 0};
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001444 PyObject *slots, *tmp, *newslots;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001445 PyTypeObject *type, *base, *tmptype, *winner;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001446 etype *et;
Guido van Rossum6f799372001-09-20 20:46:19 +00001447 PyMemberDef *mp;
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001448 int i, nbases, nslots, slotoffset, add_dict, add_weak;
Guido van Rossumad47da02002-08-12 19:05:44 +00001449 int j, may_add_dict, may_add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001450
Tim Peters3abca122001-10-27 19:37:48 +00001451 assert(args != NULL && PyTuple_Check(args));
1452 assert(kwds == NULL || PyDict_Check(kwds));
1453
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001454 /* Special case: type(x) should return x->ob_type */
Tim Peters3abca122001-10-27 19:37:48 +00001455 {
1456 const int nargs = PyTuple_GET_SIZE(args);
1457 const int nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
1458
1459 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
1460 PyObject *x = PyTuple_GET_ITEM(args, 0);
1461 Py_INCREF(x->ob_type);
1462 return (PyObject *) x->ob_type;
1463 }
1464
1465 /* SF bug 475327 -- if that didn't trigger, we need 3
1466 arguments. but PyArg_ParseTupleAndKeywords below may give
1467 a msg saying type() needs exactly 3. */
1468 if (nargs + nkwds != 3) {
1469 PyErr_SetString(PyExc_TypeError,
1470 "type() takes 1 or 3 arguments");
1471 return NULL;
1472 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001473 }
1474
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001475 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001476 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
1477 &name,
1478 &PyTuple_Type, &bases,
1479 &PyDict_Type, &dict))
1480 return NULL;
1481
1482 /* Determine the proper metatype to deal with this,
1483 and check for metatype conflicts while we're at it.
1484 Note that if some other metatype wins to contract,
1485 it's possible that its instances are not types. */
1486 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001487 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001488 for (i = 0; i < nbases; i++) {
1489 tmp = PyTuple_GET_ITEM(bases, i);
1490 tmptype = tmp->ob_type;
Tim Petersa91e9642001-11-14 23:32:33 +00001491 if (tmptype == &PyClass_Type)
1492 continue; /* Special case classic classes */
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001493 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001494 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001495 if (PyType_IsSubtype(tmptype, winner)) {
1496 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001497 continue;
1498 }
1499 PyErr_SetString(PyExc_TypeError,
1500 "metatype conflict among bases");
1501 return NULL;
1502 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001503 if (winner != metatype) {
1504 if (winner->tp_new != type_new) /* Pass it to the winner */
1505 return winner->tp_new(winner, args, kwds);
1506 metatype = winner;
1507 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001508
1509 /* Adjust for empty tuple bases */
1510 if (nbases == 0) {
1511 bases = Py_BuildValue("(O)", &PyBaseObject_Type);
1512 if (bases == NULL)
1513 return NULL;
1514 nbases = 1;
1515 }
1516 else
1517 Py_INCREF(bases);
1518
1519 /* XXX From here until type is allocated, "return NULL" leaks bases! */
1520
1521 /* Calculate best base, and check that all bases are type objects */
1522 base = best_base(bases);
1523 if (base == NULL)
1524 return NULL;
1525 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
1526 PyErr_Format(PyExc_TypeError,
1527 "type '%.100s' is not an acceptable base type",
1528 base->tp_name);
1529 return NULL;
1530 }
1531
Tim Peters6d6c1a32001-08-02 04:15:00 +00001532 /* Check for a __slots__ sequence variable in dict, and count it */
1533 slots = PyDict_GetItemString(dict, "__slots__");
1534 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +00001535 add_dict = 0;
1536 add_weak = 0;
Guido van Rossumad47da02002-08-12 19:05:44 +00001537 may_add_dict = base->tp_dictoffset == 0;
1538 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
1539 if (slots == NULL) {
1540 if (may_add_dict) {
1541 add_dict++;
1542 }
1543 if (may_add_weak) {
1544 add_weak++;
1545 }
1546 }
1547 else {
1548 /* Have slots */
1549
Tim Peters6d6c1a32001-08-02 04:15:00 +00001550 /* Make it into a tuple */
1551 if (PyString_Check(slots))
1552 slots = Py_BuildValue("(O)", slots);
1553 else
1554 slots = PySequence_Tuple(slots);
1555 if (slots == NULL)
1556 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00001557 assert(PyTuple_Check(slots));
1558
1559 /* Are slots allowed? */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001560 nslots = PyTuple_GET_SIZE(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +00001561 if (nslots > 0 && base->tp_itemsize != 0) {
1562 PyErr_Format(PyExc_TypeError,
1563 "nonempty __slots__ "
1564 "not supported for subtype of '%s'",
1565 base->tp_name);
Guido van Rossumad47da02002-08-12 19:05:44 +00001566 bad_slots:
1567 Py_DECREF(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +00001568 return NULL;
1569 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001570
Martin v. Löwisd919a592002-10-14 21:07:28 +00001571#ifdef Py_USING_UNICODE
1572 tmp = _unicode_to_string(slots, nslots);
Martin v. Löwis13b1a5c2002-10-14 21:11:34 +00001573 if (tmp != slots) {
1574 Py_DECREF(slots);
1575 slots = tmp;
1576 }
Martin v. Löwisd919a592002-10-14 21:07:28 +00001577 if (!tmp)
1578 return NULL;
1579#endif
Guido van Rossumad47da02002-08-12 19:05:44 +00001580 /* Check for valid slot names and two special cases */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001581 for (i = 0; i < nslots; i++) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001582 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
1583 char *s;
1584 if (!valid_identifier(tmp))
1585 goto bad_slots;
1586 assert(PyString_Check(tmp));
1587 s = PyString_AS_STRING(tmp);
1588 if (strcmp(s, "__dict__") == 0) {
1589 if (!may_add_dict || add_dict) {
1590 PyErr_SetString(PyExc_TypeError,
1591 "__dict__ slot disallowed: "
1592 "we already got one");
1593 goto bad_slots;
1594 }
1595 add_dict++;
1596 }
1597 if (strcmp(s, "__weakref__") == 0) {
1598 if (!may_add_weak || add_weak) {
1599 PyErr_SetString(PyExc_TypeError,
1600 "__weakref__ slot disallowed: "
1601 "either we already got one, "
1602 "or __itemsize__ != 0");
1603 goto bad_slots;
1604 }
1605 add_weak++;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001606 }
1607 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001608
Guido van Rossumad47da02002-08-12 19:05:44 +00001609 /* Copy slots into yet another tuple, demangling names */
1610 newslots = PyTuple_New(nslots - add_dict - add_weak);
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001611 if (newslots == NULL)
Guido van Rossumad47da02002-08-12 19:05:44 +00001612 goto bad_slots;
1613 for (i = j = 0; i < nslots; i++) {
1614 char *s;
Guido van Rossum8e829202002-08-16 03:47:49 +00001615 char buffer[256];
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001616 tmp = PyTuple_GET_ITEM(slots, i);
Guido van Rossumad47da02002-08-12 19:05:44 +00001617 s = PyString_AS_STRING(tmp);
1618 if ((add_dict && strcmp(s, "__dict__") == 0) ||
1619 (add_weak && strcmp(s, "__weakref__") == 0))
1620 continue;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001621 if (_Py_Mangle(PyString_AS_STRING(name),
Guido van Rossumad47da02002-08-12 19:05:44 +00001622 PyString_AS_STRING(tmp),
1623 buffer, sizeof(buffer)))
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001624 {
1625 tmp = PyString_FromString(buffer);
1626 } else {
1627 Py_INCREF(tmp);
1628 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001629 PyTuple_SET_ITEM(newslots, j, tmp);
1630 j++;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001631 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001632 assert(j == nslots - add_dict - add_weak);
1633 nslots = j;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001634 Py_DECREF(slots);
1635 slots = newslots;
1636
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001637 /* See if *this* class defines __getstate__ */
Guido van Rossumad47da02002-08-12 19:05:44 +00001638 if (PyDict_GetItemString(dict, "__getstate__") == NULL) {
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001639 /* If not, provide a bozo that raises TypeError */
1640 if (bozo_obj == NULL) {
1641 bozo_obj = PyCFunction_New(&bozo_ml, NULL);
Guido van Rossumad47da02002-08-12 19:05:44 +00001642 if (bozo_obj == NULL)
1643 goto bad_slots;
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001644 }
1645 if (PyDict_SetItemString(dict,
1646 "__getstate__",
Guido van Rossumad47da02002-08-12 19:05:44 +00001647 bozo_obj) < 0)
1648 {
1649 Py_DECREF(bozo_obj);
1650 goto bad_slots;
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001651 }
1652 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001653
1654 /* Secondary bases may provide weakrefs or dict */
1655 if (nbases > 1 &&
1656 ((may_add_dict && !add_dict) ||
1657 (may_add_weak && !add_weak))) {
1658 for (i = 0; i < nbases; i++) {
1659 tmp = PyTuple_GET_ITEM(bases, i);
1660 if (tmp == (PyObject *)base)
1661 continue; /* Skip primary base */
1662 if (PyClass_Check(tmp)) {
1663 /* Classic base class provides both */
1664 if (may_add_dict && !add_dict)
1665 add_dict++;
1666 if (may_add_weak && !add_weak)
1667 add_weak++;
1668 break;
1669 }
1670 assert(PyType_Check(tmp));
1671 tmptype = (PyTypeObject *)tmp;
1672 if (may_add_dict && !add_dict &&
1673 tmptype->tp_dictoffset != 0)
1674 add_dict++;
1675 if (may_add_weak && !add_weak &&
1676 tmptype->tp_weaklistoffset != 0)
1677 add_weak++;
1678 if (may_add_dict && !add_dict)
1679 continue;
1680 if (may_add_weak && !add_weak)
1681 continue;
1682 /* Nothing more to check */
1683 break;
1684 }
1685 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001686 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001687
1688 /* XXX From here until type is safely allocated,
1689 "return NULL" may leak slots! */
1690
1691 /* Allocate the type object */
1692 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
Guido van Rossumad47da02002-08-12 19:05:44 +00001693 if (type == NULL) {
1694 Py_XDECREF(slots);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001695 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00001696 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001697
1698 /* Keep name and slots alive in the extended type object */
1699 et = (etype *)type;
1700 Py_INCREF(name);
1701 et->name = name;
1702 et->slots = slots;
1703
Guido van Rossumdc91b992001-08-08 22:26:22 +00001704 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001705 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
1706 Py_TPFLAGS_BASETYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00001707 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
1708 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00001709
1710 /* It's a new-style number unless it specifically inherits any
1711 old-style numeric behavior */
1712 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
1713 (base->tp_as_number == NULL))
1714 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
1715
1716 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001717 type->tp_as_number = &et->as_number;
1718 type->tp_as_sequence = &et->as_sequence;
1719 type->tp_as_mapping = &et->as_mapping;
1720 type->tp_as_buffer = &et->as_buffer;
1721 type->tp_name = PyString_AS_STRING(name);
1722
1723 /* Set tp_base and tp_bases */
1724 type->tp_bases = bases;
1725 Py_INCREF(base);
1726 type->tp_base = base;
1727
Guido van Rossum687ae002001-10-15 22:03:32 +00001728 /* Initialize tp_dict from passed-in dict */
1729 type->tp_dict = dict = PyDict_Copy(dict);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001730 if (dict == NULL) {
1731 Py_DECREF(type);
1732 return NULL;
1733 }
1734
Guido van Rossumc3542212001-08-16 09:18:56 +00001735 /* Set __module__ in the dict */
1736 if (PyDict_GetItemString(dict, "__module__") == NULL) {
1737 tmp = PyEval_GetGlobals();
1738 if (tmp != NULL) {
1739 tmp = PyDict_GetItemString(tmp, "__name__");
1740 if (tmp != NULL) {
1741 if (PyDict_SetItemString(dict, "__module__",
1742 tmp) < 0)
1743 return NULL;
1744 }
1745 }
1746 }
1747
Tim Peters2f93e282001-10-04 05:27:00 +00001748 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
Tim Peters24008312002-03-17 18:56:20 +00001749 and is a string. The __doc__ accessor will first look for tp_doc;
1750 if that fails, it will still look into __dict__.
Tim Peters2f93e282001-10-04 05:27:00 +00001751 */
1752 {
1753 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
1754 if (doc != NULL && PyString_Check(doc)) {
1755 const size_t n = (size_t)PyString_GET_SIZE(doc);
Tim Peters59f809d2001-10-04 05:43:02 +00001756 type->tp_doc = (char *)PyObject_MALLOC(n+1);
Tim Peters2f93e282001-10-04 05:27:00 +00001757 if (type->tp_doc == NULL) {
1758 Py_DECREF(type);
1759 return NULL;
1760 }
1761 memcpy(type->tp_doc, PyString_AS_STRING(doc), n+1);
1762 }
1763 }
1764
Tim Peters6d6c1a32001-08-02 04:15:00 +00001765 /* Special-case __new__: if it's a plain function,
1766 make it a static function */
1767 tmp = PyDict_GetItemString(dict, "__new__");
1768 if (tmp != NULL && PyFunction_Check(tmp)) {
1769 tmp = PyStaticMethod_New(tmp);
1770 if (tmp == NULL) {
1771 Py_DECREF(type);
1772 return NULL;
1773 }
1774 PyDict_SetItemString(dict, "__new__", tmp);
1775 Py_DECREF(tmp);
1776 }
1777
1778 /* Add descriptors for custom slots from __slots__, or for __dict__ */
1779 mp = et->members;
Neil Schemenauerc806c882001-08-29 23:54:54 +00001780 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001781 if (slots != NULL) {
1782 for (i = 0; i < nslots; i++, mp++) {
1783 mp->name = PyString_AS_STRING(
1784 PyTuple_GET_ITEM(slots, i));
Guido van Rossum64b206c2001-12-04 17:13:22 +00001785 mp->type = T_OBJECT_EX;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001786 mp->offset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +00001787 if (base->tp_weaklistoffset == 0 &&
Guido van Rossum64b206c2001-12-04 17:13:22 +00001788 strcmp(mp->name, "__weakref__") == 0) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001789 add_weak++;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001790 mp->type = T_OBJECT;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001791 mp->flags = READONLY;
Guido van Rossum9676b222001-08-17 20:32:36 +00001792 type->tp_weaklistoffset = slotoffset;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001793 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001794 slotoffset += sizeof(PyObject *);
1795 }
1796 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001797 if (add_dict) {
1798 if (base->tp_itemsize)
1799 type->tp_dictoffset = -(long)sizeof(PyObject *);
1800 else
1801 type->tp_dictoffset = slotoffset;
1802 slotoffset += sizeof(PyObject *);
1803 }
1804 if (add_weak) {
1805 assert(!base->tp_itemsize);
1806 type->tp_weaklistoffset = slotoffset;
1807 slotoffset += sizeof(PyObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001808 }
1809 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001810 type->tp_itemsize = base->tp_itemsize;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001811 type->tp_members = et->members;
Guido van Rossumad47da02002-08-12 19:05:44 +00001812 type->tp_getset = subtype_getsets;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001813
1814 /* Special case some slots */
1815 if (type->tp_dictoffset != 0 || nslots > 0) {
1816 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
1817 type->tp_getattro = PyObject_GenericGetAttr;
1818 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
1819 type->tp_setattro = PyObject_GenericSetAttr;
1820 }
1821 type->tp_dealloc = subtype_dealloc;
1822
Guido van Rossum9475a232001-10-05 20:51:39 +00001823 /* Enable GC unless there are really no instance variables possible */
1824 if (!(type->tp_basicsize == sizeof(PyObject) &&
1825 type->tp_itemsize == 0))
1826 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
1827
Tim Peters6d6c1a32001-08-02 04:15:00 +00001828 /* Always override allocation strategy to use regular heap */
1829 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00001830 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001831 type->tp_free = PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00001832 type->tp_traverse = subtype_traverse;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001833 type->tp_clear = subtype_clear;
Guido van Rossum048eb752001-10-02 21:24:57 +00001834 }
1835 else
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001836 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001837
1838 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001839 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001840 Py_DECREF(type);
1841 return NULL;
1842 }
1843
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001844 /* Put the proper slots in place */
1845 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00001846
Tim Peters6d6c1a32001-08-02 04:15:00 +00001847 return (PyObject *)type;
1848}
1849
1850/* Internal API to look for a name through the MRO.
1851 This returns a borrowed reference, and doesn't set an exception! */
1852PyObject *
1853_PyType_Lookup(PyTypeObject *type, PyObject *name)
1854{
1855 int i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00001856 PyObject *mro, *res, *base, *dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001857
Guido van Rossum687ae002001-10-15 22:03:32 +00001858 /* Look in tp_dict of types in MRO */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001859 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00001860
1861 /* If mro is NULL, the type is either not yet initialized
1862 by PyType_Ready(), or already cleared by type_clear().
1863 Either way the safest thing to do is to return NULL. */
1864 if (mro == NULL)
1865 return NULL;
1866
Tim Peters6d6c1a32001-08-02 04:15:00 +00001867 assert(PyTuple_Check(mro));
1868 n = PyTuple_GET_SIZE(mro);
1869 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001870 base = PyTuple_GET_ITEM(mro, i);
1871 if (PyClass_Check(base))
1872 dict = ((PyClassObject *)base)->cl_dict;
1873 else {
1874 assert(PyType_Check(base));
1875 dict = ((PyTypeObject *)base)->tp_dict;
1876 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001877 assert(dict && PyDict_Check(dict));
1878 res = PyDict_GetItem(dict, name);
1879 if (res != NULL)
1880 return res;
1881 }
1882 return NULL;
1883}
1884
1885/* This is similar to PyObject_GenericGetAttr(),
1886 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
1887static PyObject *
1888type_getattro(PyTypeObject *type, PyObject *name)
1889{
1890 PyTypeObject *metatype = type->ob_type;
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001891 PyObject *meta_attribute, *attribute;
1892 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001893
1894 /* Initialize this type (we'll assume the metatype is initialized) */
1895 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001896 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001897 return NULL;
1898 }
1899
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001900 /* No readable descriptor found yet */
1901 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00001902
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001903 /* Look for the attribute in the metatype */
1904 meta_attribute = _PyType_Lookup(metatype, name);
1905
1906 if (meta_attribute != NULL) {
1907 meta_get = meta_attribute->ob_type->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00001908
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001909 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
1910 /* Data descriptors implement tp_descr_set to intercept
1911 * writes. Assume the attribute is not overridden in
1912 * type's tp_dict (and bases): call the descriptor now.
1913 */
1914 return meta_get(meta_attribute, (PyObject *)type,
1915 (PyObject *)metatype);
1916 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001917 }
1918
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001919 /* No data descriptor found on metatype. Look in tp_dict of this
1920 * type and its bases */
1921 attribute = _PyType_Lookup(type, name);
1922 if (attribute != NULL) {
1923 /* Implement descriptor functionality, if any */
1924 descrgetfunc local_get = attribute->ob_type->tp_descr_get;
1925 if (local_get != NULL) {
1926 /* NULL 2nd argument indicates the descriptor was
1927 * found on the target object itself (or a base) */
1928 return local_get(attribute, (PyObject *)NULL,
1929 (PyObject *)type);
1930 }
Tim Peters34592512002-07-11 06:23:50 +00001931
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001932 Py_INCREF(attribute);
1933 return attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001934 }
1935
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001936 /* No attribute found in local __dict__ (or bases): use the
1937 * descriptor from the metatype, if any */
1938 if (meta_get != NULL)
1939 return meta_get(meta_attribute, (PyObject *)type,
1940 (PyObject *)metatype);
1941
1942 /* If an ordinary attribute was found on the metatype, return it now */
1943 if (meta_attribute != NULL) {
1944 Py_INCREF(meta_attribute);
1945 return meta_attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001946 }
1947
1948 /* Give up */
1949 PyErr_Format(PyExc_AttributeError,
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001950 "type object '%.50s' has no attribute '%.400s'",
1951 type->tp_name, PyString_AS_STRING(name));
Tim Peters6d6c1a32001-08-02 04:15:00 +00001952 return NULL;
1953}
1954
1955static int
1956type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
1957{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001958 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
1959 PyErr_Format(
1960 PyExc_TypeError,
1961 "can't set attributes of built-in/extension type '%s'",
1962 type->tp_name);
1963 return -1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001964 }
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001965 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
1966 return -1;
1967 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001968}
1969
1970static void
1971type_dealloc(PyTypeObject *type)
1972{
1973 etype *et;
1974
1975 /* Assert this is a heap-allocated type object */
1976 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00001977 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00001978 PyObject_ClearWeakRefs((PyObject *)type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001979 et = (etype *)type;
1980 Py_XDECREF(type->tp_base);
1981 Py_XDECREF(type->tp_dict);
1982 Py_XDECREF(type->tp_bases);
1983 Py_XDECREF(type->tp_mro);
Guido van Rossum687ae002001-10-15 22:03:32 +00001984 Py_XDECREF(type->tp_cache);
Guido van Rossum1c450732001-10-08 15:18:27 +00001985 Py_XDECREF(type->tp_subclasses);
Neal Norwitzcee5ca02002-07-30 00:42:06 +00001986 PyObject_Free(type->tp_doc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001987 Py_XDECREF(et->name);
1988 Py_XDECREF(et->slots);
1989 type->ob_type->tp_free((PyObject *)type);
1990}
1991
Guido van Rossum1c450732001-10-08 15:18:27 +00001992static PyObject *
1993type_subclasses(PyTypeObject *type, PyObject *args_ignored)
1994{
1995 PyObject *list, *raw, *ref;
1996 int i, n;
1997
1998 list = PyList_New(0);
1999 if (list == NULL)
2000 return NULL;
2001 raw = type->tp_subclasses;
2002 if (raw == NULL)
2003 return list;
2004 assert(PyList_Check(raw));
2005 n = PyList_GET_SIZE(raw);
2006 for (i = 0; i < n; i++) {
2007 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00002008 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00002009 ref = PyWeakref_GET_OBJECT(ref);
2010 if (ref != Py_None) {
2011 if (PyList_Append(list, ref) < 0) {
2012 Py_DECREF(list);
2013 return NULL;
2014 }
2015 }
2016 }
2017 return list;
2018}
2019
Tim Peters6d6c1a32001-08-02 04:15:00 +00002020static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002021 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002022 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
Guido van Rossum1c450732001-10-08 15:18:27 +00002023 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002024 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002025 {0}
2026};
2027
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002028PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002029"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002030"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002031
Guido van Rossum048eb752001-10-02 21:24:57 +00002032static int
2033type_traverse(PyTypeObject *type, visitproc visit, void *arg)
2034{
Guido van Rossum048eb752001-10-02 21:24:57 +00002035 int err;
2036
Guido van Rossuma3862092002-06-10 15:24:42 +00002037 /* Because of type_is_gc(), the collector only calls this
2038 for heaptypes. */
2039 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002040
2041#define VISIT(SLOT) \
2042 if (SLOT) { \
2043 err = visit((PyObject *)(SLOT), arg); \
2044 if (err) \
2045 return err; \
2046 }
2047
2048 VISIT(type->tp_dict);
Guido van Rossum687ae002001-10-15 22:03:32 +00002049 VISIT(type->tp_cache);
Guido van Rossum048eb752001-10-02 21:24:57 +00002050 VISIT(type->tp_mro);
2051 VISIT(type->tp_bases);
2052 VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00002053
2054 /* There's no need to visit type->tp_subclasses or
2055 ((etype *)type)->slots, because they can't be involved
2056 in cycles; tp_subclasses is a list of weak references,
2057 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00002058
2059#undef VISIT
2060
2061 return 0;
2062}
2063
2064static int
2065type_clear(PyTypeObject *type)
2066{
Guido van Rossum048eb752001-10-02 21:24:57 +00002067 PyObject *tmp;
2068
Guido van Rossuma3862092002-06-10 15:24:42 +00002069 /* Because of type_is_gc(), the collector only calls this
2070 for heaptypes. */
2071 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002072
2073#define CLEAR(SLOT) \
2074 if (SLOT) { \
2075 tmp = (PyObject *)(SLOT); \
2076 SLOT = NULL; \
2077 Py_DECREF(tmp); \
2078 }
2079
Guido van Rossuma3862092002-06-10 15:24:42 +00002080 /* The only field we need to clear is tp_mro, which is part of a
2081 hard cycle (its first element is the class itself) that won't
2082 be broken otherwise (it's a tuple and tuples don't have a
2083 tp_clear handler). None of the other fields need to be
2084 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00002085
Guido van Rossuma3862092002-06-10 15:24:42 +00002086 tp_dict:
2087 It is a dict, so the collector will call its tp_clear.
2088
2089 tp_cache:
2090 Not used; if it were, it would be a dict.
2091
2092 tp_bases, tp_base:
2093 If these are involved in a cycle, there must be at least
2094 one other, mutable object in the cycle, e.g. a base
2095 class's dict; the cycle will be broken that way.
2096
2097 tp_subclasses:
2098 A list of weak references can't be part of a cycle; and
2099 lists have their own tp_clear.
2100
2101 slots (in etype):
2102 A tuple of strings can't be part of a cycle.
2103 */
2104
2105 CLEAR(type->tp_mro);
Tim Peters2f93e282001-10-04 05:27:00 +00002106
Guido van Rossum048eb752001-10-02 21:24:57 +00002107#undef CLEAR
2108
2109 return 0;
2110}
2111
2112static int
2113type_is_gc(PyTypeObject *type)
2114{
2115 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
2116}
2117
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002118PyTypeObject PyType_Type = {
2119 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002120 0, /* ob_size */
2121 "type", /* tp_name */
2122 sizeof(etype), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00002123 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002124 (destructor)type_dealloc, /* tp_dealloc */
2125 0, /* tp_print */
2126 0, /* tp_getattr */
2127 0, /* tp_setattr */
2128 type_compare, /* tp_compare */
2129 (reprfunc)type_repr, /* tp_repr */
2130 0, /* tp_as_number */
2131 0, /* tp_as_sequence */
2132 0, /* tp_as_mapping */
2133 (hashfunc)_Py_HashPointer, /* tp_hash */
2134 (ternaryfunc)type_call, /* tp_call */
2135 0, /* tp_str */
2136 (getattrofunc)type_getattro, /* tp_getattro */
2137 (setattrofunc)type_setattro, /* tp_setattro */
2138 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00002139 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2140 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002141 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00002142 (traverseproc)type_traverse, /* tp_traverse */
2143 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002144 0, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00002145 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002146 0, /* tp_iter */
2147 0, /* tp_iternext */
2148 type_methods, /* tp_methods */
2149 type_members, /* tp_members */
2150 type_getsets, /* tp_getset */
2151 0, /* tp_base */
2152 0, /* tp_dict */
2153 0, /* tp_descr_get */
2154 0, /* tp_descr_set */
2155 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
2156 0, /* tp_init */
2157 0, /* tp_alloc */
2158 type_new, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002159 PyObject_GC_Del, /* tp_free */
Guido van Rossum048eb752001-10-02 21:24:57 +00002160 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002161};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002162
2163
2164/* The base type of all types (eventually)... except itself. */
2165
2166static int
2167object_init(PyObject *self, PyObject *args, PyObject *kwds)
2168{
2169 return 0;
2170}
2171
2172static void
2173object_dealloc(PyObject *self)
2174{
2175 self->ob_type->tp_free(self);
2176}
2177
Guido van Rossum8e248182001-08-12 05:17:56 +00002178static PyObject *
2179object_repr(PyObject *self)
2180{
Guido van Rossum76e69632001-08-16 18:52:43 +00002181 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00002182 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002183
Guido van Rossum76e69632001-08-16 18:52:43 +00002184 type = self->ob_type;
2185 mod = type_module(type, NULL);
2186 if (mod == NULL)
2187 PyErr_Clear();
2188 else if (!PyString_Check(mod)) {
2189 Py_DECREF(mod);
2190 mod = NULL;
2191 }
2192 name = type_name(type, NULL);
2193 if (name == NULL)
2194 return NULL;
2195 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002196 rtn = PyString_FromFormat("<%s.%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002197 PyString_AS_STRING(mod),
2198 PyString_AS_STRING(name),
2199 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002200 else
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002201 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002202 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002203 Py_XDECREF(mod);
2204 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00002205 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002206}
2207
Guido van Rossumb8f63662001-08-15 23:57:02 +00002208static PyObject *
2209object_str(PyObject *self)
2210{
2211 unaryfunc f;
2212
2213 f = self->ob_type->tp_repr;
2214 if (f == NULL)
2215 f = object_repr;
2216 return f(self);
2217}
2218
Guido van Rossum8e248182001-08-12 05:17:56 +00002219static long
2220object_hash(PyObject *self)
2221{
2222 return _Py_HashPointer(self);
2223}
Guido van Rossum8e248182001-08-12 05:17:56 +00002224
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002225static PyObject *
2226object_get_class(PyObject *self, void *closure)
2227{
2228 Py_INCREF(self->ob_type);
2229 return (PyObject *)(self->ob_type);
2230}
2231
2232static int
2233equiv_structs(PyTypeObject *a, PyTypeObject *b)
2234{
2235 return a == b ||
2236 (a != NULL &&
2237 b != NULL &&
2238 a->tp_basicsize == b->tp_basicsize &&
2239 a->tp_itemsize == b->tp_itemsize &&
2240 a->tp_dictoffset == b->tp_dictoffset &&
2241 a->tp_weaklistoffset == b->tp_weaklistoffset &&
2242 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
2243 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
2244}
2245
2246static int
2247same_slots_added(PyTypeObject *a, PyTypeObject *b)
2248{
2249 PyTypeObject *base = a->tp_base;
2250 int size;
2251
2252 if (base != b->tp_base)
2253 return 0;
2254 if (equiv_structs(a, base) && equiv_structs(b, base))
2255 return 1;
2256 size = base->tp_basicsize;
2257 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
2258 size += sizeof(PyObject *);
2259 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
2260 size += sizeof(PyObject *);
2261 return size == a->tp_basicsize && size == b->tp_basicsize;
2262}
2263
2264static int
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002265compatible_for_assignment(PyTypeObject* old, PyTypeObject* new, char* attr)
2266{
2267 PyTypeObject *newbase, *oldbase;
2268
2269 if (new->tp_dealloc != old->tp_dealloc ||
2270 new->tp_free != old->tp_free)
2271 {
2272 PyErr_Format(PyExc_TypeError,
2273 "%s assignment: "
2274 "'%s' deallocator differs from '%s'",
2275 attr,
2276 new->tp_name,
2277 old->tp_name);
2278 return 0;
2279 }
2280 newbase = new;
2281 oldbase = old;
2282 while (equiv_structs(newbase, newbase->tp_base))
2283 newbase = newbase->tp_base;
2284 while (equiv_structs(oldbase, oldbase->tp_base))
2285 oldbase = oldbase->tp_base;
2286 if (newbase != oldbase &&
2287 (newbase->tp_base != oldbase->tp_base ||
2288 !same_slots_added(newbase, oldbase))) {
2289 PyErr_Format(PyExc_TypeError,
2290 "%s assignment: "
2291 "'%s' object layout differs from '%s'",
2292 attr,
2293 new->tp_name,
2294 old->tp_name);
2295 return 0;
2296 }
Tim Petersea7f75d2002-12-07 21:39:16 +00002297
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002298 return 1;
2299}
2300
2301static int
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002302object_set_class(PyObject *self, PyObject *value, void *closure)
2303{
2304 PyTypeObject *old = self->ob_type;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002305 PyTypeObject *new;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002306
Guido van Rossumb6b89422002-04-15 01:03:30 +00002307 if (value == NULL) {
2308 PyErr_SetString(PyExc_TypeError,
2309 "can't delete __class__ attribute");
2310 return -1;
2311 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002312 if (!PyType_Check(value)) {
2313 PyErr_Format(PyExc_TypeError,
2314 "__class__ must be set to new-style class, not '%s' object",
2315 value->ob_type->tp_name);
2316 return -1;
2317 }
2318 new = (PyTypeObject *)value;
Guido van Rossum40af8892002-08-10 05:42:07 +00002319 if (!(new->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
2320 !(old->tp_flags & Py_TPFLAGS_HEAPTYPE))
2321 {
2322 PyErr_Format(PyExc_TypeError,
2323 "__class__ assignment: only for heap types");
2324 return -1;
2325 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002326 if (compatible_for_assignment(new, old, "__class__")) {
2327 Py_INCREF(new);
2328 self->ob_type = new;
2329 Py_DECREF(old);
2330 return 0;
2331 }
2332 else {
Guido van Rossum9ee4b942002-05-24 18:47:47 +00002333 return -1;
2334 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002335}
2336
2337static PyGetSetDef object_getsets[] = {
2338 {"__class__", object_get_class, object_set_class,
Neal Norwitz858e34f2002-08-13 17:18:45 +00002339 PyDoc_STR("the object's class")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002340 {0}
2341};
2342
Guido van Rossum3926a632001-09-25 16:25:58 +00002343static PyObject *
2344object_reduce(PyObject *self, PyObject *args)
2345{
2346 /* Call copy_reg._reduce(self) */
2347 static PyObject *copy_reg_str;
2348 PyObject *copy_reg, *res;
2349
2350 if (!copy_reg_str) {
2351 copy_reg_str = PyString_InternFromString("copy_reg");
2352 if (copy_reg_str == NULL)
2353 return NULL;
2354 }
2355 copy_reg = PyImport_Import(copy_reg_str);
2356 if (!copy_reg)
2357 return NULL;
2358 res = PyEval_CallMethod(copy_reg, "_reduce", "(O)", self);
2359 Py_DECREF(copy_reg);
2360 return res;
2361}
2362
2363static PyMethodDef object_methods[] = {
Tim Petersea7f75d2002-12-07 21:39:16 +00002364 {"__reduce__", object_reduce, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002365 PyDoc_STR("helper for pickle")},
Guido van Rossum3926a632001-09-25 16:25:58 +00002366 {0}
2367};
2368
Tim Peters6d6c1a32001-08-02 04:15:00 +00002369PyTypeObject PyBaseObject_Type = {
2370 PyObject_HEAD_INIT(&PyType_Type)
2371 0, /* ob_size */
2372 "object", /* tp_name */
2373 sizeof(PyObject), /* tp_basicsize */
2374 0, /* tp_itemsize */
2375 (destructor)object_dealloc, /* tp_dealloc */
2376 0, /* tp_print */
2377 0, /* tp_getattr */
2378 0, /* tp_setattr */
2379 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002380 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002381 0, /* tp_as_number */
2382 0, /* tp_as_sequence */
2383 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002384 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002385 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002386 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002387 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002388 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002389 0, /* tp_as_buffer */
2390 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002391 PyDoc_STR("The most base type"), /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002392 0, /* tp_traverse */
2393 0, /* tp_clear */
2394 0, /* tp_richcompare */
2395 0, /* tp_weaklistoffset */
2396 0, /* tp_iter */
2397 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00002398 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002399 0, /* tp_members */
2400 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002401 0, /* tp_base */
2402 0, /* tp_dict */
2403 0, /* tp_descr_get */
2404 0, /* tp_descr_set */
2405 0, /* tp_dictoffset */
2406 object_init, /* tp_init */
2407 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossumc11e1922001-08-09 19:38:15 +00002408 PyType_GenericNew, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002409 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002410};
2411
2412
2413/* Initialize the __dict__ in a type object */
2414
Fred Drake7bf97152002-03-28 05:33:33 +00002415static PyObject *
2416create_specialmethod(PyMethodDef *meth, PyObject *(*func)(PyObject *))
2417{
2418 PyObject *cfunc;
2419 PyObject *result;
2420
2421 cfunc = PyCFunction_New(meth, NULL);
2422 if (cfunc == NULL)
2423 return NULL;
2424 result = func(cfunc);
2425 Py_DECREF(cfunc);
2426 return result;
2427}
2428
Tim Peters6d6c1a32001-08-02 04:15:00 +00002429static int
2430add_methods(PyTypeObject *type, PyMethodDef *meth)
2431{
Guido van Rossum687ae002001-10-15 22:03:32 +00002432 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002433
2434 for (; meth->ml_name != NULL; meth++) {
2435 PyObject *descr;
2436 if (PyDict_GetItemString(dict, meth->ml_name))
2437 continue;
Fred Drake7bf97152002-03-28 05:33:33 +00002438 if (meth->ml_flags & METH_CLASS) {
2439 if (meth->ml_flags & METH_STATIC) {
2440 PyErr_SetString(PyExc_ValueError,
2441 "method cannot be both class and static");
2442 return -1;
2443 }
Tim Petersbca1cbc2002-12-09 22:56:13 +00002444 descr = PyDescr_NewClassMethod(type, meth);
Fred Drake7bf97152002-03-28 05:33:33 +00002445 }
2446 else if (meth->ml_flags & METH_STATIC) {
2447 descr = create_specialmethod(meth, PyStaticMethod_New);
2448 }
2449 else {
2450 descr = PyDescr_NewMethod(type, meth);
2451 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002452 if (descr == NULL)
2453 return -1;
Fred Drake7bf97152002-03-28 05:33:33 +00002454 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002455 return -1;
2456 Py_DECREF(descr);
2457 }
2458 return 0;
2459}
2460
2461static int
Guido van Rossum6f799372001-09-20 20:46:19 +00002462add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002463{
Guido van Rossum687ae002001-10-15 22:03:32 +00002464 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002465
2466 for (; memb->name != NULL; memb++) {
2467 PyObject *descr;
2468 if (PyDict_GetItemString(dict, memb->name))
2469 continue;
2470 descr = PyDescr_NewMember(type, memb);
2471 if (descr == NULL)
2472 return -1;
2473 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
2474 return -1;
2475 Py_DECREF(descr);
2476 }
2477 return 0;
2478}
2479
2480static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00002481add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002482{
Guido van Rossum687ae002001-10-15 22:03:32 +00002483 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002484
2485 for (; gsp->name != NULL; gsp++) {
2486 PyObject *descr;
2487 if (PyDict_GetItemString(dict, gsp->name))
2488 continue;
2489 descr = PyDescr_NewGetSet(type, gsp);
2490
2491 if (descr == NULL)
2492 return -1;
2493 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
2494 return -1;
2495 Py_DECREF(descr);
2496 }
2497 return 0;
2498}
2499
Guido van Rossum13d52f02001-08-10 21:24:08 +00002500static void
2501inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002502{
2503 int oldsize, newsize;
2504
Guido van Rossum13d52f02001-08-10 21:24:08 +00002505 /* Special flag magic */
2506 if (!type->tp_as_buffer && base->tp_as_buffer) {
2507 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
2508 type->tp_flags |=
2509 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
2510 }
2511 if (!type->tp_as_sequence && base->tp_as_sequence) {
2512 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
2513 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
2514 }
2515 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
2516 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
2517 if ((!type->tp_as_number && base->tp_as_number) ||
2518 (!type->tp_as_sequence && base->tp_as_sequence)) {
2519 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
2520 if (!type->tp_as_number && !type->tp_as_sequence) {
2521 type->tp_flags |= base->tp_flags &
2522 Py_TPFLAGS_HAVE_INPLACEOPS;
2523 }
2524 }
2525 /* Wow */
2526 }
2527 if (!type->tp_as_number && base->tp_as_number) {
2528 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
2529 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
2530 }
2531
2532 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00002533 oldsize = base->tp_basicsize;
2534 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
2535 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
2536 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00002537 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
2538 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00002539 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00002540 if (type->tp_traverse == NULL)
2541 type->tp_traverse = base->tp_traverse;
2542 if (type->tp_clear == NULL)
2543 type->tp_clear = base->tp_clear;
2544 }
2545 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
Guido van Rossumf884b742001-12-17 17:14:22 +00002546 /* The condition below could use some explanation.
2547 It appears that tp_new is not inherited for static types
2548 whose base class is 'object'; this seems to be a precaution
2549 so that old extension types don't suddenly become
2550 callable (object.__new__ wouldn't insure the invariants
2551 that the extension type's own factory function ensures).
2552 Heap types, of course, are under our control, so they do
2553 inherit tp_new; static extension types that specify some
2554 other built-in type as the default are considered
2555 new-style-aware so they also inherit object.__new__. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002556 if (base != &PyBaseObject_Type ||
2557 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2558 if (type->tp_new == NULL)
2559 type->tp_new = base->tp_new;
2560 }
2561 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00002562 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00002563
2564 /* Copy other non-function slots */
2565
2566#undef COPYVAL
2567#define COPYVAL(SLOT) \
2568 if (type->SLOT == 0) type->SLOT = base->SLOT
2569
2570 COPYVAL(tp_itemsize);
2571 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
2572 COPYVAL(tp_weaklistoffset);
2573 }
2574 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2575 COPYVAL(tp_dictoffset);
2576 }
Guido van Rossum13d52f02001-08-10 21:24:08 +00002577}
2578
2579static void
2580inherit_slots(PyTypeObject *type, PyTypeObject *base)
2581{
2582 PyTypeObject *basebase;
2583
2584#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00002585#undef COPYSLOT
2586#undef COPYNUM
2587#undef COPYSEQ
2588#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00002589#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00002590
2591#define SLOTDEFINED(SLOT) \
2592 (base->SLOT != 0 && \
2593 (basebase == NULL || base->SLOT != basebase->SLOT))
2594
Tim Peters6d6c1a32001-08-02 04:15:00 +00002595#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00002596 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00002597
2598#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
2599#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
2600#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00002601#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002602
Guido van Rossum13d52f02001-08-10 21:24:08 +00002603 /* This won't inherit indirect slots (from tp_as_number etc.)
2604 if type doesn't provide the space. */
2605
2606 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
2607 basebase = base->tp_base;
2608 if (basebase->tp_as_number == NULL)
2609 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002610 COPYNUM(nb_add);
2611 COPYNUM(nb_subtract);
2612 COPYNUM(nb_multiply);
2613 COPYNUM(nb_divide);
2614 COPYNUM(nb_remainder);
2615 COPYNUM(nb_divmod);
2616 COPYNUM(nb_power);
2617 COPYNUM(nb_negative);
2618 COPYNUM(nb_positive);
2619 COPYNUM(nb_absolute);
2620 COPYNUM(nb_nonzero);
2621 COPYNUM(nb_invert);
2622 COPYNUM(nb_lshift);
2623 COPYNUM(nb_rshift);
2624 COPYNUM(nb_and);
2625 COPYNUM(nb_xor);
2626 COPYNUM(nb_or);
2627 COPYNUM(nb_coerce);
2628 COPYNUM(nb_int);
2629 COPYNUM(nb_long);
2630 COPYNUM(nb_float);
2631 COPYNUM(nb_oct);
2632 COPYNUM(nb_hex);
2633 COPYNUM(nb_inplace_add);
2634 COPYNUM(nb_inplace_subtract);
2635 COPYNUM(nb_inplace_multiply);
2636 COPYNUM(nb_inplace_divide);
2637 COPYNUM(nb_inplace_remainder);
2638 COPYNUM(nb_inplace_power);
2639 COPYNUM(nb_inplace_lshift);
2640 COPYNUM(nb_inplace_rshift);
2641 COPYNUM(nb_inplace_and);
2642 COPYNUM(nb_inplace_xor);
2643 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00002644 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
2645 COPYNUM(nb_true_divide);
2646 COPYNUM(nb_floor_divide);
2647 COPYNUM(nb_inplace_true_divide);
2648 COPYNUM(nb_inplace_floor_divide);
2649 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002650 }
2651
Guido van Rossum13d52f02001-08-10 21:24:08 +00002652 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
2653 basebase = base->tp_base;
2654 if (basebase->tp_as_sequence == NULL)
2655 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002656 COPYSEQ(sq_length);
2657 COPYSEQ(sq_concat);
2658 COPYSEQ(sq_repeat);
2659 COPYSEQ(sq_item);
2660 COPYSEQ(sq_slice);
2661 COPYSEQ(sq_ass_item);
2662 COPYSEQ(sq_ass_slice);
2663 COPYSEQ(sq_contains);
2664 COPYSEQ(sq_inplace_concat);
2665 COPYSEQ(sq_inplace_repeat);
2666 }
2667
Guido van Rossum13d52f02001-08-10 21:24:08 +00002668 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
2669 basebase = base->tp_base;
2670 if (basebase->tp_as_mapping == NULL)
2671 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002672 COPYMAP(mp_length);
2673 COPYMAP(mp_subscript);
2674 COPYMAP(mp_ass_subscript);
2675 }
2676
Tim Petersfc57ccb2001-10-12 02:38:24 +00002677 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
2678 basebase = base->tp_base;
2679 if (basebase->tp_as_buffer == NULL)
2680 basebase = NULL;
2681 COPYBUF(bf_getreadbuffer);
2682 COPYBUF(bf_getwritebuffer);
2683 COPYBUF(bf_getsegcount);
2684 COPYBUF(bf_getcharbuffer);
2685 }
2686
Guido van Rossum13d52f02001-08-10 21:24:08 +00002687 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002688
Tim Peters6d6c1a32001-08-02 04:15:00 +00002689 COPYSLOT(tp_dealloc);
2690 COPYSLOT(tp_print);
2691 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
2692 type->tp_getattr = base->tp_getattr;
2693 type->tp_getattro = base->tp_getattro;
2694 }
2695 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
2696 type->tp_setattr = base->tp_setattr;
2697 type->tp_setattro = base->tp_setattro;
2698 }
2699 /* tp_compare see tp_richcompare */
2700 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002701 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002702 COPYSLOT(tp_call);
2703 COPYSLOT(tp_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002704 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00002705 if (type->tp_compare == NULL &&
2706 type->tp_richcompare == NULL &&
2707 type->tp_hash == NULL)
2708 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00002709 type->tp_compare = base->tp_compare;
2710 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002711 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002712 }
2713 }
2714 else {
2715 COPYSLOT(tp_compare);
2716 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002717 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
2718 COPYSLOT(tp_iter);
2719 COPYSLOT(tp_iternext);
2720 }
2721 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2722 COPYSLOT(tp_descr_get);
2723 COPYSLOT(tp_descr_set);
2724 COPYSLOT(tp_dictoffset);
2725 COPYSLOT(tp_init);
2726 COPYSLOT(tp_alloc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002727 COPYSLOT(tp_free);
Guido van Rossumcc8fe042002-04-05 17:10:16 +00002728 COPYSLOT(tp_is_gc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002729 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002730}
2731
Jeremy Hylton938ace62002-07-17 16:30:39 +00002732static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00002733
Tim Peters6d6c1a32001-08-02 04:15:00 +00002734int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002735PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002736{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002737 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002738 PyTypeObject *base;
2739 int i, n;
2740
Guido van Rossumcab05802002-06-10 15:29:03 +00002741 if (type->tp_flags & Py_TPFLAGS_READY) {
2742 assert(type->tp_dict != NULL);
Guido van Rossumd614f972001-08-10 17:39:49 +00002743 return 0;
Guido van Rossumcab05802002-06-10 15:29:03 +00002744 }
Guido van Rossumd614f972001-08-10 17:39:49 +00002745 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00002746
2747 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002748
2749 /* Initialize tp_base (defaults to BaseObject unless that's us) */
2750 base = type->tp_base;
2751 if (base == NULL && type != &PyBaseObject_Type)
2752 base = type->tp_base = &PyBaseObject_Type;
2753
Guido van Rossum323a9cf2002-08-14 17:26:30 +00002754 /* Initialize the base class */
2755 if (base && base->tp_dict == NULL) {
2756 if (PyType_Ready(base) < 0)
2757 goto error;
2758 }
2759
Guido van Rossum0986d822002-04-08 01:38:42 +00002760 /* Initialize ob_type if NULL. This means extensions that want to be
2761 compilable separately on Windows can call PyType_Ready() instead of
2762 initializing the ob_type field of their type objects. */
2763 if (type->ob_type == NULL)
2764 type->ob_type = base->ob_type;
2765
Tim Peters6d6c1a32001-08-02 04:15:00 +00002766 /* Initialize tp_bases */
2767 bases = type->tp_bases;
2768 if (bases == NULL) {
2769 if (base == NULL)
2770 bases = PyTuple_New(0);
2771 else
2772 bases = Py_BuildValue("(O)", base);
2773 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00002774 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002775 type->tp_bases = bases;
2776 }
2777
Guido van Rossum687ae002001-10-15 22:03:32 +00002778 /* Initialize tp_dict */
2779 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002780 if (dict == NULL) {
2781 dict = PyDict_New();
2782 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00002783 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00002784 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002785 }
2786
Guido van Rossum687ae002001-10-15 22:03:32 +00002787 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002788 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002789 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002790 if (type->tp_methods != NULL) {
2791 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002792 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002793 }
2794 if (type->tp_members != NULL) {
2795 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002796 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002797 }
2798 if (type->tp_getset != NULL) {
2799 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002800 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002801 }
2802
Tim Peters6d6c1a32001-08-02 04:15:00 +00002803 /* Calculate method resolution order */
2804 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00002805 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002806 }
2807
Guido van Rossum13d52f02001-08-10 21:24:08 +00002808 /* Inherit special flags from dominant base */
2809 if (type->tp_base != NULL)
2810 inherit_special(type, type->tp_base);
2811
Tim Peters6d6c1a32001-08-02 04:15:00 +00002812 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002813 bases = type->tp_mro;
2814 assert(bases != NULL);
2815 assert(PyTuple_Check(bases));
2816 n = PyTuple_GET_SIZE(bases);
2817 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002818 PyObject *b = PyTuple_GET_ITEM(bases, i);
2819 if (PyType_Check(b))
2820 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002821 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002822
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00002823 /* if the type dictionary doesn't contain a __doc__, set it from
2824 the tp_doc slot.
2825 */
2826 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
2827 if (type->tp_doc != NULL) {
2828 PyObject *doc = PyString_FromString(type->tp_doc);
2829 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
2830 Py_DECREF(doc);
2831 } else {
Guido van Rossumd4641072002-04-03 02:13:37 +00002832 PyDict_SetItemString(type->tp_dict,
2833 "__doc__", Py_None);
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00002834 }
2835 }
2836
Guido van Rossum13d52f02001-08-10 21:24:08 +00002837 /* Some more special stuff */
2838 base = type->tp_base;
2839 if (base != NULL) {
2840 if (type->tp_as_number == NULL)
2841 type->tp_as_number = base->tp_as_number;
2842 if (type->tp_as_sequence == NULL)
2843 type->tp_as_sequence = base->tp_as_sequence;
2844 if (type->tp_as_mapping == NULL)
2845 type->tp_as_mapping = base->tp_as_mapping;
2846 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002847
Guido van Rossum1c450732001-10-08 15:18:27 +00002848 /* Link into each base class's list of subclasses */
2849 bases = type->tp_bases;
2850 n = PyTuple_GET_SIZE(bases);
2851 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002852 PyObject *b = PyTuple_GET_ITEM(bases, i);
2853 if (PyType_Check(b) &&
2854 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00002855 goto error;
2856 }
2857
Guido van Rossum13d52f02001-08-10 21:24:08 +00002858 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00002859 assert(type->tp_dict != NULL);
2860 type->tp_flags =
2861 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002862 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00002863
2864 error:
2865 type->tp_flags &= ~Py_TPFLAGS_READYING;
2866 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002867}
2868
Guido van Rossum1c450732001-10-08 15:18:27 +00002869static int
2870add_subclass(PyTypeObject *base, PyTypeObject *type)
2871{
2872 int i;
2873 PyObject *list, *ref, *new;
2874
2875 list = base->tp_subclasses;
2876 if (list == NULL) {
2877 base->tp_subclasses = list = PyList_New(0);
2878 if (list == NULL)
2879 return -1;
2880 }
2881 assert(PyList_Check(list));
2882 new = PyWeakref_NewRef((PyObject *)type, NULL);
2883 i = PyList_GET_SIZE(list);
2884 while (--i >= 0) {
2885 ref = PyList_GET_ITEM(list, i);
2886 assert(PyWeakref_CheckRef(ref));
Guido van Rossum3930bc32002-10-18 13:51:49 +00002887 if (PyWeakref_GET_OBJECT(ref) == Py_None)
2888 return PyList_SetItem(list, i, new);
Guido van Rossum1c450732001-10-08 15:18:27 +00002889 }
2890 i = PyList_Append(list, new);
2891 Py_DECREF(new);
2892 return i;
2893}
2894
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002895static void
2896remove_subclass(PyTypeObject *base, PyTypeObject *type)
2897{
2898 int i;
2899 PyObject *list, *ref;
2900
2901 list = base->tp_subclasses;
2902 if (list == NULL) {
2903 return;
2904 }
2905 assert(PyList_Check(list));
2906 i = PyList_GET_SIZE(list);
2907 while (--i >= 0) {
2908 ref = PyList_GET_ITEM(list, i);
2909 assert(PyWeakref_CheckRef(ref));
2910 if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
2911 /* this can't fail, right? */
2912 PySequence_DelItem(list, i);
2913 return;
2914 }
2915 }
2916}
Tim Peters6d6c1a32001-08-02 04:15:00 +00002917
2918/* Generic wrappers for overloadable 'operators' such as __getitem__ */
2919
2920/* There's a wrapper *function* for each distinct function typedef used
2921 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
2922 wrapper *table* for each distinct operation (e.g. __len__, __add__).
2923 Most tables have only one entry; the tables for binary operators have two
2924 entries, one regular and one with reversed arguments. */
2925
2926static PyObject *
2927wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
2928{
2929 inquiry func = (inquiry)wrapped;
2930 int res;
2931
2932 if (!PyArg_ParseTuple(args, ""))
2933 return NULL;
2934 res = (*func)(self);
2935 if (res == -1 && PyErr_Occurred())
2936 return NULL;
2937 return PyInt_FromLong((long)res);
2938}
2939
Tim Peters6d6c1a32001-08-02 04:15:00 +00002940static PyObject *
2941wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
2942{
2943 binaryfunc func = (binaryfunc)wrapped;
2944 PyObject *other;
2945
2946 if (!PyArg_ParseTuple(args, "O", &other))
2947 return NULL;
2948 return (*func)(self, other);
2949}
2950
2951static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002952wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
2953{
2954 binaryfunc func = (binaryfunc)wrapped;
2955 PyObject *other;
2956
2957 if (!PyArg_ParseTuple(args, "O", &other))
2958 return NULL;
2959 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002960 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002961 Py_INCREF(Py_NotImplemented);
2962 return Py_NotImplemented;
2963 }
2964 return (*func)(self, other);
2965}
2966
2967static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00002968wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2969{
2970 binaryfunc func = (binaryfunc)wrapped;
2971 PyObject *other;
2972
2973 if (!PyArg_ParseTuple(args, "O", &other))
2974 return NULL;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002975 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002976 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002977 Py_INCREF(Py_NotImplemented);
2978 return Py_NotImplemented;
2979 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002980 return (*func)(other, self);
2981}
2982
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002983static PyObject *
2984wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
2985{
2986 coercion func = (coercion)wrapped;
2987 PyObject *other, *res;
2988 int ok;
2989
2990 if (!PyArg_ParseTuple(args, "O", &other))
2991 return NULL;
2992 ok = func(&self, &other);
2993 if (ok < 0)
2994 return NULL;
2995 if (ok > 0) {
2996 Py_INCREF(Py_NotImplemented);
2997 return Py_NotImplemented;
2998 }
2999 res = PyTuple_New(2);
3000 if (res == NULL) {
3001 Py_DECREF(self);
3002 Py_DECREF(other);
3003 return NULL;
3004 }
3005 PyTuple_SET_ITEM(res, 0, self);
3006 PyTuple_SET_ITEM(res, 1, other);
3007 return res;
3008}
3009
Tim Peters6d6c1a32001-08-02 04:15:00 +00003010static PyObject *
3011wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
3012{
3013 ternaryfunc func = (ternaryfunc)wrapped;
3014 PyObject *other;
3015 PyObject *third = Py_None;
3016
3017 /* Note: This wrapper only works for __pow__() */
3018
3019 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
3020 return NULL;
3021 return (*func)(self, other, third);
3022}
3023
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00003024static PyObject *
3025wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3026{
3027 ternaryfunc func = (ternaryfunc)wrapped;
3028 PyObject *other;
3029 PyObject *third = Py_None;
3030
3031 /* Note: This wrapper only works for __pow__() */
3032
3033 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
3034 return NULL;
3035 return (*func)(other, self, third);
3036}
3037
Tim Peters6d6c1a32001-08-02 04:15:00 +00003038static PyObject *
3039wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
3040{
3041 unaryfunc func = (unaryfunc)wrapped;
3042
3043 if (!PyArg_ParseTuple(args, ""))
3044 return NULL;
3045 return (*func)(self);
3046}
3047
Tim Peters6d6c1a32001-08-02 04:15:00 +00003048static PyObject *
3049wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
3050{
3051 intargfunc func = (intargfunc)wrapped;
3052 int i;
3053
3054 if (!PyArg_ParseTuple(args, "i", &i))
3055 return NULL;
3056 return (*func)(self, i);
3057}
3058
Guido van Rossum5d815f32001-08-17 21:57:47 +00003059static int
3060getindex(PyObject *self, PyObject *arg)
3061{
3062 int i;
3063
3064 i = PyInt_AsLong(arg);
3065 if (i == -1 && PyErr_Occurred())
3066 return -1;
3067 if (i < 0) {
3068 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
3069 if (sq && sq->sq_length) {
3070 int n = (*sq->sq_length)(self);
3071 if (n < 0)
3072 return -1;
3073 i += n;
3074 }
3075 }
3076 return i;
3077}
3078
3079static PyObject *
3080wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
3081{
3082 intargfunc func = (intargfunc)wrapped;
3083 PyObject *arg;
3084 int i;
3085
Guido van Rossumf4593e02001-10-03 12:09:30 +00003086 if (PyTuple_GET_SIZE(args) == 1) {
3087 arg = PyTuple_GET_ITEM(args, 0);
3088 i = getindex(self, arg);
3089 if (i == -1 && PyErr_Occurred())
3090 return NULL;
3091 return (*func)(self, i);
3092 }
3093 PyArg_ParseTuple(args, "O", &arg);
3094 assert(PyErr_Occurred());
3095 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003096}
3097
Tim Peters6d6c1a32001-08-02 04:15:00 +00003098static PyObject *
3099wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
3100{
3101 intintargfunc func = (intintargfunc)wrapped;
3102 int i, j;
3103
3104 if (!PyArg_ParseTuple(args, "ii", &i, &j))
3105 return NULL;
3106 return (*func)(self, i, j);
3107}
3108
Tim Peters6d6c1a32001-08-02 04:15:00 +00003109static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003110wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003111{
3112 intobjargproc func = (intobjargproc)wrapped;
3113 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003114 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003115
Guido van Rossum5d815f32001-08-17 21:57:47 +00003116 if (!PyArg_ParseTuple(args, "OO", &arg, &value))
3117 return NULL;
3118 i = getindex(self, arg);
3119 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00003120 return NULL;
3121 res = (*func)(self, i, value);
3122 if (res == -1 && PyErr_Occurred())
3123 return NULL;
3124 Py_INCREF(Py_None);
3125 return Py_None;
3126}
3127
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003128static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003129wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003130{
3131 intobjargproc func = (intobjargproc)wrapped;
3132 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003133 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003134
Guido van Rossum5d815f32001-08-17 21:57:47 +00003135 if (!PyArg_ParseTuple(args, "O", &arg))
3136 return NULL;
3137 i = getindex(self, arg);
3138 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003139 return NULL;
3140 res = (*func)(self, i, NULL);
3141 if (res == -1 && PyErr_Occurred())
3142 return NULL;
3143 Py_INCREF(Py_None);
3144 return Py_None;
3145}
3146
Tim Peters6d6c1a32001-08-02 04:15:00 +00003147static PyObject *
3148wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
3149{
3150 intintobjargproc func = (intintobjargproc)wrapped;
3151 int i, j, res;
3152 PyObject *value;
3153
3154 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
3155 return NULL;
3156 res = (*func)(self, i, j, value);
3157 if (res == -1 && PyErr_Occurred())
3158 return NULL;
3159 Py_INCREF(Py_None);
3160 return Py_None;
3161}
3162
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003163static PyObject *
3164wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
3165{
3166 intintobjargproc func = (intintobjargproc)wrapped;
3167 int i, j, res;
3168
3169 if (!PyArg_ParseTuple(args, "ii", &i, &j))
3170 return NULL;
3171 res = (*func)(self, i, j, NULL);
3172 if (res == -1 && PyErr_Occurred())
3173 return NULL;
3174 Py_INCREF(Py_None);
3175 return Py_None;
3176}
3177
Tim Peters6d6c1a32001-08-02 04:15:00 +00003178/* XXX objobjproc is a misnomer; should be objargpred */
3179static PyObject *
3180wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
3181{
3182 objobjproc func = (objobjproc)wrapped;
3183 int res;
3184 PyObject *value;
3185
3186 if (!PyArg_ParseTuple(args, "O", &value))
3187 return NULL;
3188 res = (*func)(self, value);
3189 if (res == -1 && PyErr_Occurred())
3190 return NULL;
3191 return PyInt_FromLong((long)res);
3192}
3193
Tim Peters6d6c1a32001-08-02 04:15:00 +00003194static PyObject *
3195wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
3196{
3197 objobjargproc func = (objobjargproc)wrapped;
3198 int res;
3199 PyObject *key, *value;
3200
3201 if (!PyArg_ParseTuple(args, "OO", &key, &value))
3202 return NULL;
3203 res = (*func)(self, key, value);
3204 if (res == -1 && PyErr_Occurred())
3205 return NULL;
3206 Py_INCREF(Py_None);
3207 return Py_None;
3208}
3209
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003210static PyObject *
3211wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
3212{
3213 objobjargproc func = (objobjargproc)wrapped;
3214 int res;
3215 PyObject *key;
3216
3217 if (!PyArg_ParseTuple(args, "O", &key))
3218 return NULL;
3219 res = (*func)(self, key, NULL);
3220 if (res == -1 && PyErr_Occurred())
3221 return NULL;
3222 Py_INCREF(Py_None);
3223 return Py_None;
3224}
3225
Tim Peters6d6c1a32001-08-02 04:15:00 +00003226static PyObject *
3227wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
3228{
3229 cmpfunc func = (cmpfunc)wrapped;
3230 int res;
3231 PyObject *other;
3232
3233 if (!PyArg_ParseTuple(args, "O", &other))
3234 return NULL;
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00003235 if (other->ob_type->tp_compare != func &&
3236 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00003237 PyErr_Format(
3238 PyExc_TypeError,
3239 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
3240 self->ob_type->tp_name,
3241 self->ob_type->tp_name,
3242 other->ob_type->tp_name);
3243 return NULL;
3244 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003245 res = (*func)(self, other);
3246 if (PyErr_Occurred())
3247 return NULL;
3248 return PyInt_FromLong((long)res);
3249}
3250
Tim Peters6d6c1a32001-08-02 04:15:00 +00003251static PyObject *
3252wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
3253{
3254 setattrofunc func = (setattrofunc)wrapped;
3255 int res;
3256 PyObject *name, *value;
3257
3258 if (!PyArg_ParseTuple(args, "OO", &name, &value))
3259 return NULL;
3260 res = (*func)(self, name, value);
3261 if (res < 0)
3262 return NULL;
3263 Py_INCREF(Py_None);
3264 return Py_None;
3265}
3266
3267static PyObject *
3268wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
3269{
3270 setattrofunc func = (setattrofunc)wrapped;
3271 int res;
3272 PyObject *name;
3273
3274 if (!PyArg_ParseTuple(args, "O", &name))
3275 return NULL;
3276 res = (*func)(self, name, NULL);
3277 if (res < 0)
3278 return NULL;
3279 Py_INCREF(Py_None);
3280 return Py_None;
3281}
3282
Tim Peters6d6c1a32001-08-02 04:15:00 +00003283static PyObject *
3284wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
3285{
3286 hashfunc func = (hashfunc)wrapped;
3287 long res;
3288
3289 if (!PyArg_ParseTuple(args, ""))
3290 return NULL;
3291 res = (*func)(self);
3292 if (res == -1 && PyErr_Occurred())
3293 return NULL;
3294 return PyInt_FromLong(res);
3295}
3296
Tim Peters6d6c1a32001-08-02 04:15:00 +00003297static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00003298wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003299{
3300 ternaryfunc func = (ternaryfunc)wrapped;
3301
Guido van Rossumc8e56452001-10-22 00:43:43 +00003302 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003303}
3304
Tim Peters6d6c1a32001-08-02 04:15:00 +00003305static PyObject *
3306wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
3307{
3308 richcmpfunc func = (richcmpfunc)wrapped;
3309 PyObject *other;
3310
3311 if (!PyArg_ParseTuple(args, "O", &other))
3312 return NULL;
3313 return (*func)(self, other, op);
3314}
3315
3316#undef RICHCMP_WRAPPER
3317#define RICHCMP_WRAPPER(NAME, OP) \
3318static PyObject * \
3319richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
3320{ \
3321 return wrap_richcmpfunc(self, args, wrapped, OP); \
3322}
3323
Jack Jansen8e938b42001-08-08 15:29:49 +00003324RICHCMP_WRAPPER(lt, Py_LT)
3325RICHCMP_WRAPPER(le, Py_LE)
3326RICHCMP_WRAPPER(eq, Py_EQ)
3327RICHCMP_WRAPPER(ne, Py_NE)
3328RICHCMP_WRAPPER(gt, Py_GT)
3329RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003330
Tim Peters6d6c1a32001-08-02 04:15:00 +00003331static PyObject *
3332wrap_next(PyObject *self, PyObject *args, void *wrapped)
3333{
3334 unaryfunc func = (unaryfunc)wrapped;
3335 PyObject *res;
3336
3337 if (!PyArg_ParseTuple(args, ""))
3338 return NULL;
3339 res = (*func)(self);
3340 if (res == NULL && !PyErr_Occurred())
3341 PyErr_SetNone(PyExc_StopIteration);
3342 return res;
3343}
3344
Tim Peters6d6c1a32001-08-02 04:15:00 +00003345static PyObject *
3346wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
3347{
3348 descrgetfunc func = (descrgetfunc)wrapped;
3349 PyObject *obj;
3350 PyObject *type = NULL;
3351
3352 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
3353 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003354 return (*func)(self, obj, type);
3355}
3356
Tim Peters6d6c1a32001-08-02 04:15:00 +00003357static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003358wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003359{
3360 descrsetfunc func = (descrsetfunc)wrapped;
3361 PyObject *obj, *value;
3362 int ret;
3363
3364 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
3365 return NULL;
3366 ret = (*func)(self, obj, value);
3367 if (ret < 0)
3368 return NULL;
3369 Py_INCREF(Py_None);
3370 return Py_None;
3371}
Guido van Rossum22b13872002-08-06 21:41:44 +00003372
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00003373static PyObject *
3374wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
3375{
3376 descrsetfunc func = (descrsetfunc)wrapped;
3377 PyObject *obj;
3378 int ret;
3379
3380 if (!PyArg_ParseTuple(args, "O", &obj))
3381 return NULL;
3382 ret = (*func)(self, obj, NULL);
3383 if (ret < 0)
3384 return NULL;
3385 Py_INCREF(Py_None);
3386 return Py_None;
3387}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003388
Tim Peters6d6c1a32001-08-02 04:15:00 +00003389static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00003390wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003391{
3392 initproc func = (initproc)wrapped;
3393
Guido van Rossumc8e56452001-10-22 00:43:43 +00003394 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003395 return NULL;
3396 Py_INCREF(Py_None);
3397 return Py_None;
3398}
3399
Tim Peters6d6c1a32001-08-02 04:15:00 +00003400static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003401tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003402{
Barry Warsaw60f01882001-08-22 19:24:42 +00003403 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003404 PyObject *arg0, *res;
3405
3406 if (self == NULL || !PyType_Check(self))
3407 Py_FatalError("__new__() called with non-type 'self'");
3408 type = (PyTypeObject *)self;
3409 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003410 PyErr_Format(PyExc_TypeError,
3411 "%s.__new__(): not enough arguments",
3412 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003413 return NULL;
3414 }
3415 arg0 = PyTuple_GET_ITEM(args, 0);
3416 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003417 PyErr_Format(PyExc_TypeError,
3418 "%s.__new__(X): X is not a type object (%s)",
3419 type->tp_name,
3420 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003421 return NULL;
3422 }
3423 subtype = (PyTypeObject *)arg0;
3424 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003425 PyErr_Format(PyExc_TypeError,
3426 "%s.__new__(%s): %s is not a subtype of %s",
3427 type->tp_name,
3428 subtype->tp_name,
3429 subtype->tp_name,
3430 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003431 return NULL;
3432 }
Barry Warsaw60f01882001-08-22 19:24:42 +00003433
3434 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00003435 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00003436 most derived base that's not a heap type is this type. */
3437 staticbase = subtype;
3438 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
3439 staticbase = staticbase->tp_base;
Guido van Rossuma8c60f42001-09-14 19:43:36 +00003440 if (staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003441 PyErr_Format(PyExc_TypeError,
3442 "%s.__new__(%s) is not safe, use %s.__new__()",
3443 type->tp_name,
3444 subtype->tp_name,
3445 staticbase == NULL ? "?" : staticbase->tp_name);
3446 return NULL;
3447 }
3448
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003449 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
3450 if (args == NULL)
3451 return NULL;
3452 res = type->tp_new(subtype, args, kwds);
3453 Py_DECREF(args);
3454 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003455}
3456
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003457static struct PyMethodDef tp_new_methoddef[] = {
3458 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00003459 PyDoc_STR("T.__new__(S, ...) -> "
3460 "a new object with type S, a subtype of T")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00003461 {0}
3462};
3463
3464static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003465add_tp_new_wrapper(PyTypeObject *type)
3466{
Guido van Rossumf040ede2001-08-07 16:40:56 +00003467 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003468
Guido van Rossum687ae002001-10-15 22:03:32 +00003469 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00003470 return 0;
3471 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003472 if (func == NULL)
3473 return -1;
Guido van Rossum687ae002001-10-15 22:03:32 +00003474 return PyDict_SetItemString(type->tp_dict, "__new__", func);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003475}
3476
Guido van Rossumf040ede2001-08-07 16:40:56 +00003477/* Slot wrappers that call the corresponding __foo__ slot. See comments
3478 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003479
Guido van Rossumdc91b992001-08-08 22:26:22 +00003480#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003481static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003482FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003483{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00003484 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003485 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003486}
3487
Guido van Rossumdc91b992001-08-08 22:26:22 +00003488#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003489static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003490FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003491{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003492 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003493 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003494}
3495
Guido van Rossumdc91b992001-08-08 22:26:22 +00003496
3497#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003498static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003499FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003500{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003501 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00003502 int do_other = self->ob_type != other->ob_type && \
3503 other->ob_type->tp_as_number != NULL && \
3504 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003505 if (self->ob_type->tp_as_number != NULL && \
3506 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
3507 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00003508 if (do_other && \
3509 PyType_IsSubtype(other->ob_type, self->ob_type)) { \
3510 r = call_maybe( \
3511 other, ROPSTR, &rcache_str, "(O)", self); \
3512 if (r != Py_NotImplemented) \
3513 return r; \
3514 Py_DECREF(r); \
3515 do_other = 0; \
3516 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00003517 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00003518 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003519 if (r != Py_NotImplemented || \
3520 other->ob_type == self->ob_type) \
3521 return r; \
3522 Py_DECREF(r); \
3523 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00003524 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00003525 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00003526 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003527 } \
3528 Py_INCREF(Py_NotImplemented); \
3529 return Py_NotImplemented; \
3530}
3531
3532#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
3533 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
3534
3535#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
3536static PyObject * \
3537FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
3538{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003539 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003540 return call_method(self, OPSTR, &cache_str, \
3541 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003542}
3543
3544static int
3545slot_sq_length(PyObject *self)
3546{
Guido van Rossum2730b132001-08-28 18:22:14 +00003547 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00003548 PyObject *res = call_method(self, "__len__", &len_str, "()");
Guido van Rossum26111622001-10-01 16:42:49 +00003549 int len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003550
3551 if (res == NULL)
3552 return -1;
Guido van Rossum26111622001-10-01 16:42:49 +00003553 len = (int)PyInt_AsLong(res);
3554 Py_DECREF(res);
Jeremy Hylton73a088e2002-07-25 16:43:29 +00003555 if (len == -1 && PyErr_Occurred())
3556 return -1;
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00003557 if (len < 0) {
Guido van Rossum22b13872002-08-06 21:41:44 +00003558 PyErr_SetString(PyExc_ValueError,
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00003559 "__len__() should return >= 0");
3560 return -1;
3561 }
Guido van Rossum26111622001-10-01 16:42:49 +00003562 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003563}
3564
Guido van Rossumdc91b992001-08-08 22:26:22 +00003565SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
3566SLOT1(slot_sq_repeat, "__mul__", int, "i")
Guido van Rossumf4593e02001-10-03 12:09:30 +00003567
3568/* Super-optimized version of slot_sq_item.
3569 Other slots could do the same... */
3570static PyObject *
3571slot_sq_item(PyObject *self, int i)
3572{
3573 static PyObject *getitem_str;
3574 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
3575 descrgetfunc f;
3576
3577 if (getitem_str == NULL) {
3578 getitem_str = PyString_InternFromString("__getitem__");
3579 if (getitem_str == NULL)
3580 return NULL;
3581 }
3582 func = _PyType_Lookup(self->ob_type, getitem_str);
3583 if (func != NULL) {
Guido van Rossumf4593e02001-10-03 12:09:30 +00003584 if ((f = func->ob_type->tp_descr_get) == NULL)
3585 Py_INCREF(func);
Neal Norwitz673cd822002-10-18 16:33:13 +00003586 else {
Guido van Rossumf4593e02001-10-03 12:09:30 +00003587 func = f(func, self, (PyObject *)(self->ob_type));
Neal Norwitz673cd822002-10-18 16:33:13 +00003588 if (func == NULL) {
3589 return NULL;
3590 }
3591 }
Guido van Rossumf4593e02001-10-03 12:09:30 +00003592 ival = PyInt_FromLong(i);
3593 if (ival != NULL) {
3594 args = PyTuple_New(1);
3595 if (args != NULL) {
3596 PyTuple_SET_ITEM(args, 0, ival);
3597 retval = PyObject_Call(func, args, NULL);
3598 Py_XDECREF(args);
3599 Py_XDECREF(func);
3600 return retval;
3601 }
3602 }
3603 }
3604 else {
3605 PyErr_SetObject(PyExc_AttributeError, getitem_str);
3606 }
3607 Py_XDECREF(args);
3608 Py_XDECREF(ival);
3609 Py_XDECREF(func);
3610 return NULL;
3611}
3612
Guido van Rossumdc91b992001-08-08 22:26:22 +00003613SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003614
3615static int
3616slot_sq_ass_item(PyObject *self, int index, PyObject *value)
3617{
3618 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003619 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003620
3621 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003622 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003623 "(i)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003624 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003625 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003626 "(iO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003627 if (res == NULL)
3628 return -1;
3629 Py_DECREF(res);
3630 return 0;
3631}
3632
3633static int
3634slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
3635{
3636 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003637 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003638
3639 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003640 res = call_method(self, "__delslice__", &delslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003641 "(ii)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003642 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003643 res = call_method(self, "__setslice__", &setslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003644 "(iiO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003645 if (res == NULL)
3646 return -1;
3647 Py_DECREF(res);
3648 return 0;
3649}
3650
3651static int
3652slot_sq_contains(PyObject *self, PyObject *value)
3653{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003654 PyObject *func, *res, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00003655 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003656
Guido van Rossum55f20992001-10-01 17:18:22 +00003657 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003658
3659 if (func != NULL) {
3660 args = Py_BuildValue("(O)", value);
3661 if (args == NULL)
3662 res = NULL;
3663 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003664 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003665 Py_DECREF(args);
3666 }
3667 Py_DECREF(func);
3668 if (res == NULL)
3669 return -1;
3670 return PyObject_IsTrue(res);
3671 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003672 else if (PyErr_Occurred())
3673 return -1;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003674 else {
Tim Peters16a77ad2001-09-08 04:00:12 +00003675 return _PySequence_IterSearch(self, value,
3676 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003677 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003678}
3679
Guido van Rossumdc91b992001-08-08 22:26:22 +00003680SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
3681SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003682
3683#define slot_mp_length slot_sq_length
3684
Guido van Rossumdc91b992001-08-08 22:26:22 +00003685SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003686
3687static int
3688slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
3689{
3690 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003691 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003692
3693 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003694 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003695 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003696 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003697 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003698 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003699 if (res == NULL)
3700 return -1;
3701 Py_DECREF(res);
3702 return 0;
3703}
3704
Guido van Rossumdc91b992001-08-08 22:26:22 +00003705SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
3706SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
3707SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
3708SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
3709SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
3710SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
3711
Jeremy Hylton938ace62002-07-17 16:30:39 +00003712static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003713
3714SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
3715 nb_power, "__pow__", "__rpow__")
3716
3717static PyObject *
3718slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
3719{
Guido van Rossum2730b132001-08-28 18:22:14 +00003720 static PyObject *pow_str;
3721
Guido van Rossumdc91b992001-08-08 22:26:22 +00003722 if (modulus == Py_None)
3723 return slot_nb_power_binary(self, other);
Guido van Rossum23094982002-06-10 14:30:43 +00003724 /* Three-arg power doesn't use __rpow__. But ternary_op
3725 can call this when the second argument's type uses
3726 slot_nb_power, so check before calling self.__pow__. */
3727 if (self->ob_type->tp_as_number != NULL &&
3728 self->ob_type->tp_as_number->nb_power == slot_nb_power) {
3729 return call_method(self, "__pow__", &pow_str,
3730 "(OO)", other, modulus);
3731 }
3732 Py_INCREF(Py_NotImplemented);
3733 return Py_NotImplemented;
Guido van Rossumdc91b992001-08-08 22:26:22 +00003734}
3735
3736SLOT0(slot_nb_negative, "__neg__")
3737SLOT0(slot_nb_positive, "__pos__")
3738SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003739
3740static int
3741slot_nb_nonzero(PyObject *self)
3742{
Tim Petersea7f75d2002-12-07 21:39:16 +00003743 PyObject *func, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00003744 static PyObject *nonzero_str, *len_str;
Tim Petersea7f75d2002-12-07 21:39:16 +00003745 int result = -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003746
Guido van Rossum55f20992001-10-01 17:18:22 +00003747 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003748 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00003749 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00003750 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00003751 func = lookup_maybe(self, "__len__", &len_str);
Tim Petersea7f75d2002-12-07 21:39:16 +00003752 if (func == NULL)
3753 return PyErr_Occurred() ? -1 : 1;
3754 }
3755 args = PyTuple_New(0);
3756 if (args != NULL) {
3757 PyObject *temp = PyObject_Call(func, args, NULL);
3758 Py_DECREF(args);
3759 if (temp != NULL) {
3760 result = PyObject_IsTrue(temp);
3761 Py_DECREF(temp);
Guido van Rossum55f20992001-10-01 17:18:22 +00003762 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00003763 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003764 Py_DECREF(func);
Tim Petersea7f75d2002-12-07 21:39:16 +00003765 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003766}
3767
Guido van Rossumdc91b992001-08-08 22:26:22 +00003768SLOT0(slot_nb_invert, "__invert__")
3769SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
3770SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
3771SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
3772SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
3773SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003774
3775static int
3776slot_nb_coerce(PyObject **a, PyObject **b)
3777{
3778 static PyObject *coerce_str;
3779 PyObject *self = *a, *other = *b;
3780
3781 if (self->ob_type->tp_as_number != NULL &&
3782 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3783 PyObject *r;
3784 r = call_maybe(
3785 self, "__coerce__", &coerce_str, "(O)", other);
3786 if (r == NULL)
3787 return -1;
3788 if (r == Py_NotImplemented) {
3789 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003790 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003791 else {
3792 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3793 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003794 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00003795 Py_DECREF(r);
3796 return -1;
3797 }
3798 *a = PyTuple_GET_ITEM(r, 0);
3799 Py_INCREF(*a);
3800 *b = PyTuple_GET_ITEM(r, 1);
3801 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003802 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00003803 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003804 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003805 }
3806 if (other->ob_type->tp_as_number != NULL &&
3807 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3808 PyObject *r;
3809 r = call_maybe(
3810 other, "__coerce__", &coerce_str, "(O)", self);
3811 if (r == NULL)
3812 return -1;
3813 if (r == Py_NotImplemented) {
3814 Py_DECREF(r);
3815 return 1;
3816 }
3817 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3818 PyErr_SetString(PyExc_TypeError,
3819 "__coerce__ didn't return a 2-tuple");
3820 Py_DECREF(r);
3821 return -1;
3822 }
3823 *a = PyTuple_GET_ITEM(r, 1);
3824 Py_INCREF(*a);
3825 *b = PyTuple_GET_ITEM(r, 0);
3826 Py_INCREF(*b);
3827 Py_DECREF(r);
3828 return 0;
3829 }
3830 return 1;
3831}
3832
Guido van Rossumdc91b992001-08-08 22:26:22 +00003833SLOT0(slot_nb_int, "__int__")
3834SLOT0(slot_nb_long, "__long__")
3835SLOT0(slot_nb_float, "__float__")
3836SLOT0(slot_nb_oct, "__oct__")
3837SLOT0(slot_nb_hex, "__hex__")
3838SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
3839SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
3840SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
3841SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
3842SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003843SLOT1(slot_nb_inplace_power, "__ipow__", PyObject *, "O")
Guido van Rossumdc91b992001-08-08 22:26:22 +00003844SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
3845SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
3846SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
3847SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
3848SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
3849SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
3850 "__floordiv__", "__rfloordiv__")
3851SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
3852SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
3853SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003854
3855static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00003856half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003857{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003858 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003859 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003860 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003861
Guido van Rossum60718732001-08-28 17:47:51 +00003862 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003863 if (func == NULL) {
3864 PyErr_Clear();
3865 }
3866 else {
3867 args = Py_BuildValue("(O)", other);
3868 if (args == NULL)
3869 res = NULL;
3870 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003871 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003872 Py_DECREF(args);
3873 }
Raymond Hettingerab5dae32002-06-24 13:08:16 +00003874 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003875 if (res != Py_NotImplemented) {
3876 if (res == NULL)
3877 return -2;
3878 c = PyInt_AsLong(res);
3879 Py_DECREF(res);
3880 if (c == -1 && PyErr_Occurred())
3881 return -2;
3882 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
3883 }
3884 Py_DECREF(res);
3885 }
3886 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003887}
3888
Guido van Rossumab3b0342001-09-18 20:38:53 +00003889/* This slot is published for the benefit of try_3way_compare in object.c */
3890int
3891_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00003892{
3893 int c;
3894
Guido van Rossumab3b0342001-09-18 20:38:53 +00003895 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003896 c = half_compare(self, other);
3897 if (c <= 1)
3898 return c;
3899 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00003900 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003901 c = half_compare(other, self);
3902 if (c < -1)
3903 return -2;
3904 if (c <= 1)
3905 return -c;
3906 }
3907 return (void *)self < (void *)other ? -1 :
3908 (void *)self > (void *)other ? 1 : 0;
3909}
3910
3911static PyObject *
3912slot_tp_repr(PyObject *self)
3913{
3914 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003915 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003916
Guido van Rossum60718732001-08-28 17:47:51 +00003917 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003918 if (func != NULL) {
3919 res = PyEval_CallObject(func, NULL);
3920 Py_DECREF(func);
3921 return res;
3922 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00003923 PyErr_Clear();
3924 return PyString_FromFormat("<%s object at %p>",
3925 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003926}
3927
3928static PyObject *
3929slot_tp_str(PyObject *self)
3930{
3931 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003932 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003933
Guido van Rossum60718732001-08-28 17:47:51 +00003934 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003935 if (func != NULL) {
3936 res = PyEval_CallObject(func, NULL);
3937 Py_DECREF(func);
3938 return res;
3939 }
3940 else {
3941 PyErr_Clear();
3942 return slot_tp_repr(self);
3943 }
3944}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003945
3946static long
3947slot_tp_hash(PyObject *self)
3948{
Tim Peters61ce0a92002-12-06 23:38:02 +00003949 PyObject *func;
Guido van Rossum60718732001-08-28 17:47:51 +00003950 static PyObject *hash_str, *eq_str, *cmp_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003951 long h;
3952
Guido van Rossum60718732001-08-28 17:47:51 +00003953 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003954
3955 if (func != NULL) {
Tim Peters61ce0a92002-12-06 23:38:02 +00003956 PyObject *res = PyEval_CallObject(func, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003957 Py_DECREF(func);
3958 if (res == NULL)
3959 return -1;
3960 h = PyInt_AsLong(res);
Tim Peters61ce0a92002-12-06 23:38:02 +00003961 Py_DECREF(res);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003962 }
3963 else {
3964 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003965 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003966 if (func == NULL) {
3967 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003968 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003969 }
3970 if (func != NULL) {
3971 Py_DECREF(func);
3972 PyErr_SetString(PyExc_TypeError, "unhashable type");
3973 return -1;
3974 }
3975 PyErr_Clear();
3976 h = _Py_HashPointer((void *)self);
3977 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003978 if (h == -1 && !PyErr_Occurred())
3979 h = -2;
3980 return h;
3981}
3982
3983static PyObject *
3984slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
3985{
Guido van Rossum60718732001-08-28 17:47:51 +00003986 static PyObject *call_str;
3987 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003988 PyObject *res;
3989
3990 if (meth == NULL)
3991 return NULL;
3992 res = PyObject_Call(meth, args, kwds);
3993 Py_DECREF(meth);
3994 return res;
3995}
3996
Guido van Rossum14a6f832001-10-17 13:59:09 +00003997/* There are two slot dispatch functions for tp_getattro.
3998
3999 - slot_tp_getattro() is used when __getattribute__ is overridden
4000 but no __getattr__ hook is present;
4001
4002 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
4003
Guido van Rossumc334df52002-04-04 23:44:47 +00004004 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
4005 detects the absence of __getattr__ and then installs the simpler slot if
4006 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00004007
Tim Peters6d6c1a32001-08-02 04:15:00 +00004008static PyObject *
4009slot_tp_getattro(PyObject *self, PyObject *name)
4010{
Guido van Rossum14a6f832001-10-17 13:59:09 +00004011 static PyObject *getattribute_str = NULL;
4012 return call_method(self, "__getattribute__", &getattribute_str,
4013 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004014}
4015
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004016static PyObject *
4017slot_tp_getattr_hook(PyObject *self, PyObject *name)
4018{
4019 PyTypeObject *tp = self->ob_type;
4020 PyObject *getattr, *getattribute, *res;
4021 static PyObject *getattribute_str = NULL;
4022 static PyObject *getattr_str = NULL;
4023
4024 if (getattr_str == NULL) {
4025 getattr_str = PyString_InternFromString("__getattr__");
4026 if (getattr_str == NULL)
4027 return NULL;
4028 }
4029 if (getattribute_str == NULL) {
4030 getattribute_str =
4031 PyString_InternFromString("__getattribute__");
4032 if (getattribute_str == NULL)
4033 return NULL;
4034 }
4035 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004036 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004037 /* No __getattr__ hook: use a simpler dispatcher */
4038 tp->tp_getattro = slot_tp_getattro;
4039 return slot_tp_getattro(self, name);
4040 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004041 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004042 if (getattribute == NULL ||
4043 (getattribute->ob_type == &PyWrapperDescr_Type &&
4044 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
4045 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004046 res = PyObject_GenericGetAttr(self, name);
4047 else
4048 res = PyObject_CallFunction(getattribute, "OO", self, name);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004049 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004050 PyErr_Clear();
4051 res = PyObject_CallFunction(getattr, "OO", self, name);
4052 }
4053 return res;
4054}
4055
Tim Peters6d6c1a32001-08-02 04:15:00 +00004056static int
4057slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
4058{
4059 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004060 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004061
4062 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004063 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004064 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004065 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004066 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004067 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004068 if (res == NULL)
4069 return -1;
4070 Py_DECREF(res);
4071 return 0;
4072}
4073
4074/* Map rich comparison operators to their __xx__ namesakes */
4075static char *name_op[] = {
4076 "__lt__",
4077 "__le__",
4078 "__eq__",
4079 "__ne__",
4080 "__gt__",
4081 "__ge__",
4082};
4083
4084static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00004085half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004086{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004087 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004088 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00004089
Guido van Rossum60718732001-08-28 17:47:51 +00004090 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004091 if (func == NULL) {
4092 PyErr_Clear();
4093 Py_INCREF(Py_NotImplemented);
4094 return Py_NotImplemented;
4095 }
4096 args = Py_BuildValue("(O)", other);
4097 if (args == NULL)
4098 res = NULL;
4099 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004100 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004101 Py_DECREF(args);
4102 }
4103 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004104 return res;
4105}
4106
Guido van Rossumb8f63662001-08-15 23:57:02 +00004107/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
4108static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
4109
4110static PyObject *
4111slot_tp_richcompare(PyObject *self, PyObject *other, int op)
4112{
4113 PyObject *res;
4114
4115 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
4116 res = half_richcompare(self, other, op);
4117 if (res != Py_NotImplemented)
4118 return res;
4119 Py_DECREF(res);
4120 }
4121 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
4122 res = half_richcompare(other, self, swapped_op[op]);
4123 if (res != Py_NotImplemented) {
4124 return res;
4125 }
4126 Py_DECREF(res);
4127 }
4128 Py_INCREF(Py_NotImplemented);
4129 return Py_NotImplemented;
4130}
4131
4132static PyObject *
4133slot_tp_iter(PyObject *self)
4134{
4135 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004136 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004137
Guido van Rossum60718732001-08-28 17:47:51 +00004138 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004139 if (func != NULL) {
Guido van Rossum84b2bed2002-08-16 17:01:09 +00004140 PyObject *args;
4141 args = res = PyTuple_New(0);
4142 if (args != NULL) {
4143 res = PyObject_Call(func, args, NULL);
4144 Py_DECREF(args);
4145 }
4146 Py_DECREF(func);
4147 return res;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004148 }
4149 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004150 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004151 if (func == NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00004152 PyErr_SetString(PyExc_TypeError,
4153 "iteration over non-sequence");
Guido van Rossumb8f63662001-08-15 23:57:02 +00004154 return NULL;
4155 }
4156 Py_DECREF(func);
4157 return PySeqIter_New(self);
4158}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004159
4160static PyObject *
4161slot_tp_iternext(PyObject *self)
4162{
Guido van Rossum2730b132001-08-28 18:22:14 +00004163 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00004164 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004165}
4166
Guido van Rossum1a493502001-08-17 16:47:50 +00004167static PyObject *
4168slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4169{
4170 PyTypeObject *tp = self->ob_type;
4171 PyObject *get;
4172 static PyObject *get_str = NULL;
4173
4174 if (get_str == NULL) {
4175 get_str = PyString_InternFromString("__get__");
4176 if (get_str == NULL)
4177 return NULL;
4178 }
4179 get = _PyType_Lookup(tp, get_str);
4180 if (get == NULL) {
4181 /* Avoid further slowdowns */
4182 if (tp->tp_descr_get == slot_tp_descr_get)
4183 tp->tp_descr_get = NULL;
4184 Py_INCREF(self);
4185 return self;
4186 }
Guido van Rossum2c252392001-08-24 10:13:31 +00004187 if (obj == NULL)
4188 obj = Py_None;
4189 if (type == NULL)
4190 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00004191 return PyObject_CallFunction(get, "OOO", self, obj, type);
4192}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004193
4194static int
4195slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
4196{
Guido van Rossum2c252392001-08-24 10:13:31 +00004197 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004198 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00004199
4200 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00004201 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004202 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00004203 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004204 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004205 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004206 if (res == NULL)
4207 return -1;
4208 Py_DECREF(res);
4209 return 0;
4210}
4211
4212static int
4213slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
4214{
Guido van Rossum60718732001-08-28 17:47:51 +00004215 static PyObject *init_str;
4216 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004217 PyObject *res;
4218
4219 if (meth == NULL)
4220 return -1;
4221 res = PyObject_Call(meth, args, kwds);
4222 Py_DECREF(meth);
4223 if (res == NULL)
4224 return -1;
4225 Py_DECREF(res);
4226 return 0;
4227}
4228
4229static PyObject *
4230slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4231{
Guido van Rossum7bed2132002-08-08 21:57:53 +00004232 static PyObject *new_str;
4233 PyObject *func;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004234 PyObject *newargs, *x;
4235 int i, n;
4236
Guido van Rossum7bed2132002-08-08 21:57:53 +00004237 if (new_str == NULL) {
4238 new_str = PyString_InternFromString("__new__");
4239 if (new_str == NULL)
4240 return NULL;
4241 }
4242 func = PyObject_GetAttr((PyObject *)type, new_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004243 if (func == NULL)
4244 return NULL;
4245 assert(PyTuple_Check(args));
4246 n = PyTuple_GET_SIZE(args);
4247 newargs = PyTuple_New(n+1);
4248 if (newargs == NULL)
4249 return NULL;
4250 Py_INCREF(type);
4251 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
4252 for (i = 0; i < n; i++) {
4253 x = PyTuple_GET_ITEM(args, i);
4254 Py_INCREF(x);
4255 PyTuple_SET_ITEM(newargs, i+1, x);
4256 }
4257 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00004258 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004259 Py_DECREF(func);
4260 return x;
4261}
4262
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004263static void
4264slot_tp_del(PyObject *self)
4265{
4266 static PyObject *del_str = NULL;
4267 PyObject *del, *res;
4268 PyObject *error_type, *error_value, *error_traceback;
4269
4270 /* Temporarily resurrect the object. */
4271 assert(self->ob_refcnt == 0);
4272 self->ob_refcnt = 1;
4273
4274 /* Save the current exception, if any. */
4275 PyErr_Fetch(&error_type, &error_value, &error_traceback);
4276
4277 /* Execute __del__ method, if any. */
4278 del = lookup_maybe(self, "__del__", &del_str);
4279 if (del != NULL) {
4280 res = PyEval_CallObject(del, NULL);
4281 if (res == NULL)
4282 PyErr_WriteUnraisable(del);
4283 else
4284 Py_DECREF(res);
4285 Py_DECREF(del);
4286 }
4287
4288 /* Restore the saved exception. */
4289 PyErr_Restore(error_type, error_value, error_traceback);
4290
4291 /* Undo the temporary resurrection; can't use DECREF here, it would
4292 * cause a recursive call.
4293 */
4294 assert(self->ob_refcnt > 0);
4295 if (--self->ob_refcnt == 0)
4296 return; /* this is the normal path out */
4297
4298 /* __del__ resurrected it! Make it look like the original Py_DECREF
4299 * never happened.
4300 */
4301 {
4302 int refcnt = self->ob_refcnt;
4303 _Py_NewReference(self);
4304 self->ob_refcnt = refcnt;
4305 }
4306 assert(!PyType_IS_GC(self->ob_type) ||
4307 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
4308 /* If Py_REF_DEBUG, the original decref dropped _Py_RefTotal, but
4309 * _Py_NewReference bumped it again, so that's a wash.
4310 * If Py_TRACE_REFS, _Py_NewReference re-added self to the object
4311 * chain, so no more to do there either.
4312 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
4313 * _Py_NewReference bumped tp_allocs: both of those need to be
4314 * undone.
4315 */
4316#ifdef COUNT_ALLOCS
4317 --self->ob_type->tp_frees;
4318 --self->ob_type->tp_allocs;
4319#endif
4320}
4321
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004322
4323/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
4324 functions. The offsets here are relative to the 'etype' structure, which
4325 incorporates the additional structures used for numbers, sequences and
4326 mappings. Note that multiple names may map to the same slot (e.g. __eq__,
4327 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00004328 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
4329 terminated with an all-zero entry. (This table is further initialized and
4330 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004331
Guido van Rossum6d204072001-10-21 00:44:31 +00004332typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004333
4334#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00004335#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004336#undef ETSLOT
4337#undef SQSLOT
4338#undef MPSLOT
4339#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00004340#undef UNSLOT
4341#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004342#undef BINSLOT
4343#undef RBINSLOT
4344
Guido van Rossum6d204072001-10-21 00:44:31 +00004345#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004346 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
4347 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00004348#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
4349 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004350 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00004351#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004352 {NAME, offsetof(etype, SLOT), (void *)(FUNCTION), WRAPPER, \
4353 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00004354#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4355 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
4356#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4357 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
4358#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4359 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
4360#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4361 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
4362 "x." NAME "() <==> " DOC)
4363#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4364 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
4365 "x." NAME "(y) <==> x" DOC "y")
4366#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
4367 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
4368 "x." NAME "(y) <==> x" DOC "y")
4369#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
4370 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
4371 "x." NAME "(y) <==> y" DOC "x")
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004372
4373static slotdef slotdefs[] = {
Guido van Rossum6d204072001-10-21 00:44:31 +00004374 SQSLOT("__len__", sq_length, slot_sq_length, wrap_inquiry,
4375 "x.__len__() <==> len(x)"),
4376 SQSLOT("__add__", sq_concat, slot_sq_concat, wrap_binaryfunc,
4377 "x.__add__(y) <==> x+y"),
4378 SQSLOT("__mul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
4379 "x.__mul__(n) <==> x*n"),
4380 SQSLOT("__rmul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
4381 "x.__rmul__(n) <==> n*x"),
4382 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
4383 "x.__getitem__(y) <==> x[y]"),
4384 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_intintargfunc,
4385 "x.__getslice__(i, j) <==> x[i:j]"),
4386 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
4387 "x.__setitem__(i, y) <==> x[i]=y"),
4388 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
4389 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004390 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Guido van Rossum6d204072001-10-21 00:44:31 +00004391 wrap_intintobjargproc,
4392 "x.__setslice__(i, j, y) <==> x[i:j]=y"),
4393 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
4394 "x.__delslice__(i, j) <==> del x[i:j]"),
4395 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
4396 "x.__contains__(y) <==> y in x"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004397 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat,
Guido van Rossum6d204072001-10-21 00:44:31 +00004398 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004399 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat,
Guido van Rossum6d204072001-10-21 00:44:31 +00004400 wrap_intargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004401
Guido van Rossum6d204072001-10-21 00:44:31 +00004402 MPSLOT("__len__", mp_length, slot_mp_length, wrap_inquiry,
4403 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00004404 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004405 wrap_binaryfunc,
4406 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004407 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004408 wrap_objobjargproc,
4409 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004410 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004411 wrap_delitem,
4412 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004413
Guido van Rossum6d204072001-10-21 00:44:31 +00004414 BINSLOT("__add__", nb_add, slot_nb_add,
4415 "+"),
4416 RBINSLOT("__radd__", nb_add, slot_nb_add,
4417 "+"),
4418 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
4419 "-"),
4420 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
4421 "-"),
4422 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
4423 "*"),
4424 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
4425 "*"),
4426 BINSLOT("__div__", nb_divide, slot_nb_divide,
4427 "/"),
4428 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
4429 "/"),
4430 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
4431 "%"),
4432 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
4433 "%"),
4434 BINSLOT("__divmod__", nb_divmod, slot_nb_divmod,
4435 "divmod(x, y)"),
4436 RBINSLOT("__rdivmod__", nb_divmod, slot_nb_divmod,
4437 "divmod(y, x)"),
4438 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
4439 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
4440 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
4441 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
4442 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
4443 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
4444 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
4445 "abs(x)"),
Guido van Rossumdfce3bf2002-03-10 14:11:16 +00004446 UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquiry,
Guido van Rossum6d204072001-10-21 00:44:31 +00004447 "x != 0"),
4448 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
4449 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
4450 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
4451 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
4452 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
4453 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
4454 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
4455 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
4456 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
4457 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
4458 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
4459 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
4460 "x.__coerce__(y) <==> coerce(x, y)"),
4461 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
4462 "int(x)"),
4463 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
4464 "long(x)"),
4465 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
4466 "float(x)"),
4467 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
4468 "oct(x)"),
4469 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
4470 "hex(x)"),
4471 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
4472 wrap_binaryfunc, "+"),
4473 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
4474 wrap_binaryfunc, "-"),
4475 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
4476 wrap_binaryfunc, "*"),
4477 IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
4478 wrap_binaryfunc, "/"),
4479 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
4480 wrap_binaryfunc, "%"),
4481 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
Guido van Rossum6e5680f2002-10-15 01:01:53 +00004482 wrap_binaryfunc, "**"),
Guido van Rossum6d204072001-10-21 00:44:31 +00004483 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
4484 wrap_binaryfunc, "<<"),
4485 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
4486 wrap_binaryfunc, ">>"),
4487 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
4488 wrap_binaryfunc, "&"),
4489 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
4490 wrap_binaryfunc, "^"),
4491 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
4492 wrap_binaryfunc, "|"),
4493 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
4494 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
4495 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
4496 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
4497 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
4498 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
4499 IBSLOT("__itruediv__", nb_inplace_true_divide,
4500 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004501
Guido van Rossum6d204072001-10-21 00:44:31 +00004502 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
4503 "x.__str__() <==> str(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00004504 TPSLOT("__str__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00004505 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
4506 "x.__repr__() <==> repr(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00004507 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00004508 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
4509 "x.__cmp__(y) <==> cmp(x,y)"),
4510 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
4511 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00004512 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
4513 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004514 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00004515 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
4516 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
4517 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
4518 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
4519 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
4520 "x.__setattr__('name', value) <==> x.name = value"),
4521 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
4522 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
4523 "x.__delattr__('name') <==> del x.name"),
4524 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
4525 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
4526 "x.__lt__(y) <==> x<y"),
4527 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
4528 "x.__le__(y) <==> x<=y"),
4529 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
4530 "x.__eq__(y) <==> x==y"),
4531 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
4532 "x.__ne__(y) <==> x!=y"),
4533 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
4534 "x.__gt__(y) <==> x>y"),
4535 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
4536 "x.__ge__(y) <==> x>=y"),
4537 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
4538 "x.__iter__() <==> iter(x)"),
4539 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
4540 "x.next() -> the next value, or raise StopIteration"),
4541 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
4542 "descr.__get__(obj[, type]) -> value"),
4543 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
4544 "descr.__set__(obj, value)"),
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004545 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
4546 wrap_descr_delete, "descr.__delete__(obj)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00004547 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00004548 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00004549 "see x.__class__.__doc__ for signature",
4550 PyWrapperFlag_KEYWORDS),
4551 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004552 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004553 {NULL}
4554};
4555
Guido van Rossumc334df52002-04-04 23:44:47 +00004556/* Given a type pointer and an offset gotten from a slotdef entry, return a
4557 pointer to the actual slot. This is not quite the same as simply adding
4558 the offset to the type pointer, since it takes care to indirect through the
4559 proper indirection pointer (as_buffer, etc.); it returns NULL if the
4560 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004561static void **
4562slotptr(PyTypeObject *type, int offset)
4563{
4564 char *ptr;
4565
Guido van Rossum09638c12002-06-13 19:17:46 +00004566 /* Note: this depends on the order of the members of etype! */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004567 assert(offset >= 0);
4568 assert(offset < offsetof(etype, as_buffer));
Guido van Rossum09638c12002-06-13 19:17:46 +00004569 if (offset >= offsetof(etype, as_sequence)) {
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004570 ptr = (void *)type->tp_as_sequence;
4571 offset -= offsetof(etype, as_sequence);
4572 }
Guido van Rossum09638c12002-06-13 19:17:46 +00004573 else if (offset >= offsetof(etype, as_mapping)) {
4574 ptr = (void *)type->tp_as_mapping;
4575 offset -= offsetof(etype, as_mapping);
4576 }
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004577 else if (offset >= offsetof(etype, as_number)) {
4578 ptr = (void *)type->tp_as_number;
4579 offset -= offsetof(etype, as_number);
4580 }
4581 else {
4582 ptr = (void *)type;
4583 }
4584 if (ptr != NULL)
4585 ptr += offset;
4586 return (void **)ptr;
4587}
Guido van Rossumf040ede2001-08-07 16:40:56 +00004588
Guido van Rossumc334df52002-04-04 23:44:47 +00004589/* Length of array of slotdef pointers used to store slots with the
4590 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
4591 the same __name__, for any __name__. Since that's a static property, it is
4592 appropriate to declare fixed-size arrays for this. */
4593#define MAX_EQUIV 10
4594
4595/* Return a slot pointer for a given name, but ONLY if the attribute has
4596 exactly one slot function. The name must be an interned string. */
4597static void **
4598resolve_slotdups(PyTypeObject *type, PyObject *name)
4599{
4600 /* XXX Maybe this could be optimized more -- but is it worth it? */
4601
4602 /* pname and ptrs act as a little cache */
4603 static PyObject *pname;
4604 static slotdef *ptrs[MAX_EQUIV];
4605 slotdef *p, **pp;
4606 void **res, **ptr;
4607
4608 if (pname != name) {
4609 /* Collect all slotdefs that match name into ptrs. */
4610 pname = name;
4611 pp = ptrs;
4612 for (p = slotdefs; p->name_strobj; p++) {
4613 if (p->name_strobj == name)
4614 *pp++ = p;
4615 }
4616 *pp = NULL;
4617 }
4618
4619 /* Look in all matching slots of the type; if exactly one of these has
4620 a filled-in slot, return its value. Otherwise return NULL. */
4621 res = NULL;
4622 for (pp = ptrs; *pp; pp++) {
4623 ptr = slotptr(type, (*pp)->offset);
4624 if (ptr == NULL || *ptr == NULL)
4625 continue;
4626 if (res != NULL)
4627 return NULL;
4628 res = ptr;
4629 }
4630 return res;
4631}
4632
4633/* Common code for update_these_slots() and fixup_slot_dispatchers(). This
4634 does some incredibly complex thinking and then sticks something into the
4635 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
4636 interests, and then stores a generic wrapper or a specific function into
4637 the slot.) Return a pointer to the next slotdef with a different offset,
4638 because that's convenient for fixup_slot_dispatchers(). */
4639static slotdef *
4640update_one_slot(PyTypeObject *type, slotdef *p)
4641{
4642 PyObject *descr;
4643 PyWrapperDescrObject *d;
4644 void *generic = NULL, *specific = NULL;
4645 int use_generic = 0;
4646 int offset = p->offset;
4647 void **ptr = slotptr(type, offset);
4648
4649 if (ptr == NULL) {
4650 do {
4651 ++p;
4652 } while (p->offset == offset);
4653 return p;
4654 }
4655 do {
4656 descr = _PyType_Lookup(type, p->name_strobj);
4657 if (descr == NULL)
4658 continue;
4659 if (descr->ob_type == &PyWrapperDescr_Type) {
4660 void **tptr = resolve_slotdups(type, p->name_strobj);
4661 if (tptr == NULL || tptr == ptr)
4662 generic = p->function;
4663 d = (PyWrapperDescrObject *)descr;
4664 if (d->d_base->wrapper == p->wrapper &&
4665 PyType_IsSubtype(type, d->d_type))
4666 {
4667 if (specific == NULL ||
4668 specific == d->d_wrapped)
4669 specific = d->d_wrapped;
4670 else
4671 use_generic = 1;
4672 }
4673 }
Guido van Rossum721f62e2002-08-09 02:14:34 +00004674 else if (descr->ob_type == &PyCFunction_Type &&
4675 PyCFunction_GET_FUNCTION(descr) ==
4676 (PyCFunction)tp_new_wrapper &&
4677 strcmp(p->name, "__new__") == 0)
4678 {
4679 /* The __new__ wrapper is not a wrapper descriptor,
4680 so must be special-cased differently.
4681 If we don't do this, creating an instance will
4682 always use slot_tp_new which will look up
4683 __new__ in the MRO which will call tp_new_wrapper
4684 which will look through the base classes looking
4685 for a static base and call its tp_new (usually
4686 PyType_GenericNew), after performing various
4687 sanity checks and constructing a new argument
4688 list. Cut all that nonsense short -- this speeds
4689 up instance creation tremendously. */
4690 specific = type->tp_new;
4691 /* XXX I'm not 100% sure that there isn't a hole
4692 in this reasoning that requires additional
4693 sanity checks. I'll buy the first person to
4694 point out a bug in this reasoning a beer. */
4695 }
Guido van Rossumc334df52002-04-04 23:44:47 +00004696 else {
4697 use_generic = 1;
4698 generic = p->function;
4699 }
4700 } while ((++p)->offset == offset);
4701 if (specific && !use_generic)
4702 *ptr = specific;
4703 else
4704 *ptr = generic;
4705 return p;
4706}
4707
Guido van Rossum22b13872002-08-06 21:41:44 +00004708static int recurse_down_subclasses(PyTypeObject *type, slotdef **pp,
Jeremy Hylton938ace62002-07-17 16:30:39 +00004709 PyObject *name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004710
Guido van Rossumc334df52002-04-04 23:44:47 +00004711/* In the type, update the slots whose slotdefs are gathered in the pp0 array,
4712 and then do the same for all this type's subtypes. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004713static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004714update_these_slots(PyTypeObject *type, slotdef **pp0, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004715{
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004716 slotdef **pp;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004717
Guido van Rossumc334df52002-04-04 23:44:47 +00004718 for (pp = pp0; *pp; pp++)
4719 update_one_slot(type, *pp);
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004720 return recurse_down_subclasses(type, pp0, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004721}
4722
Guido van Rossumc334df52002-04-04 23:44:47 +00004723/* Update the slots whose slotdefs are gathered in the pp array in all (direct
4724 or indirect) subclasses of type. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004725static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004726recurse_down_subclasses(PyTypeObject *type, slotdef **pp, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004727{
4728 PyTypeObject *subclass;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004729 PyObject *ref, *subclasses, *dict;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004730 int i, n;
4731
4732 subclasses = type->tp_subclasses;
4733 if (subclasses == NULL)
4734 return 0;
4735 assert(PyList_Check(subclasses));
4736 n = PyList_GET_SIZE(subclasses);
4737 for (i = 0; i < n; i++) {
4738 ref = PyList_GET_ITEM(subclasses, i);
4739 assert(PyWeakref_CheckRef(ref));
4740 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
Guido van Rossum59e6c532002-06-14 02:27:07 +00004741 assert(subclass != NULL);
4742 if ((PyObject *)subclass == Py_None)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004743 continue;
4744 assert(PyType_Check(subclass));
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004745 /* Avoid recursing down into unaffected classes */
4746 dict = subclass->tp_dict;
4747 if (dict != NULL && PyDict_Check(dict) &&
4748 PyDict_GetItem(dict, name) != NULL)
4749 continue;
4750 if (update_these_slots(subclass, pp, name) < 0)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004751 return -1;
4752 }
4753 return 0;
4754}
4755
Guido van Rossumc334df52002-04-04 23:44:47 +00004756/* Comparison function for qsort() to compare slotdefs by their offset, and
4757 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004758static int
4759slotdef_cmp(const void *aa, const void *bb)
4760{
4761 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
4762 int c = a->offset - b->offset;
4763 if (c != 0)
4764 return c;
4765 else
4766 return a - b;
4767}
4768
Guido van Rossumc334df52002-04-04 23:44:47 +00004769/* Initialize the slotdefs table by adding interned string objects for the
4770 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004771static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004772init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004773{
4774 slotdef *p;
4775 static int initialized = 0;
4776
4777 if (initialized)
4778 return;
4779 for (p = slotdefs; p->name; p++) {
4780 p->name_strobj = PyString_InternFromString(p->name);
4781 if (!p->name_strobj)
Guido van Rossumc334df52002-04-04 23:44:47 +00004782 Py_FatalError("Out of memory interning slotdef names");
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004783 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004784 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
4785 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004786 initialized = 1;
4787}
4788
Guido van Rossumc334df52002-04-04 23:44:47 +00004789/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004790static int
4791update_slot(PyTypeObject *type, PyObject *name)
4792{
Guido van Rossumc334df52002-04-04 23:44:47 +00004793 slotdef *ptrs[MAX_EQUIV];
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004794 slotdef *p;
4795 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004796 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004797
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004798 init_slotdefs();
4799 pp = ptrs;
4800 for (p = slotdefs; p->name; p++) {
4801 /* XXX assume name is interned! */
4802 if (p->name_strobj == name)
4803 *pp++ = p;
4804 }
4805 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004806 for (pp = ptrs; *pp; pp++) {
4807 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004808 offset = p->offset;
4809 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004810 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004811 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004812 }
Guido van Rossumc334df52002-04-04 23:44:47 +00004813 if (ptrs[0] == NULL)
4814 return 0; /* Not an attribute that affects any slots */
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004815 return update_these_slots(type, ptrs, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004816}
4817
Guido van Rossumc334df52002-04-04 23:44:47 +00004818/* Store the proper functions in the slot dispatches at class (type)
4819 definition time, based upon which operations the class overrides in its
4820 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004821static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004822fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004823{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004824 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004825
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004826 init_slotdefs();
Guido van Rossumc334df52002-04-04 23:44:47 +00004827 for (p = slotdefs; p->name; )
4828 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004829}
Guido van Rossum705f0f52001-08-24 16:47:00 +00004830
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004831static void
4832update_all_slots(PyTypeObject* type)
4833{
4834 slotdef *p;
4835
4836 init_slotdefs();
4837 for (p = slotdefs; p->name; p++) {
4838 /* update_slot returns int but can't actually fail */
4839 update_slot(type, p->name_strobj);
4840 }
4841}
4842
Guido van Rossum6d204072001-10-21 00:44:31 +00004843/* This function is called by PyType_Ready() to populate the type's
4844 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00004845 function slot (like tp_repr) that's defined in the type, one or more
4846 corresponding descriptors are added in the type's tp_dict dictionary
4847 under the appropriate name (like __repr__). Some function slots
4848 cause more than one descriptor to be added (for example, the nb_add
4849 slot adds both __add__ and __radd__ descriptors) and some function
4850 slots compete for the same descriptor (for example both sq_item and
4851 mp_subscript generate a __getitem__ descriptor).
4852
4853 In the latter case, the first slotdef entry encoutered wins. Since
4854 slotdef entries are sorted by the offset of the slot in the etype
4855 struct, this gives us some control over disambiguating between
4856 competing slots: the members of struct etype are listed from most
4857 general to least general, so the most general slot is preferred. In
4858 particular, because as_mapping comes before as_sequence, for a type
4859 that defines both mp_subscript and sq_item, mp_subscript wins.
4860
4861 This only adds new descriptors and doesn't overwrite entries in
4862 tp_dict that were previously defined. The descriptors contain a
4863 reference to the C function they must call, so that it's safe if they
4864 are copied into a subtype's __dict__ and the subtype has a different
4865 C function in its slot -- calling the method defined by the
4866 descriptor will call the C function that was used to create it,
4867 rather than the C function present in the slot when it is called.
4868 (This is important because a subtype may have a C function in the
4869 slot that calls the method from the dictionary, and we want to avoid
4870 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00004871
4872static int
4873add_operators(PyTypeObject *type)
4874{
4875 PyObject *dict = type->tp_dict;
4876 slotdef *p;
4877 PyObject *descr;
4878 void **ptr;
4879
4880 init_slotdefs();
4881 for (p = slotdefs; p->name; p++) {
4882 if (p->wrapper == NULL)
4883 continue;
4884 ptr = slotptr(type, p->offset);
4885 if (!ptr || !*ptr)
4886 continue;
4887 if (PyDict_GetItem(dict, p->name_strobj))
4888 continue;
4889 descr = PyDescr_NewWrapper(type, p, *ptr);
4890 if (descr == NULL)
4891 return -1;
4892 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
4893 return -1;
4894 Py_DECREF(descr);
4895 }
4896 if (type->tp_new != NULL) {
4897 if (add_tp_new_wrapper(type) < 0)
4898 return -1;
4899 }
4900 return 0;
4901}
4902
Guido van Rossum705f0f52001-08-24 16:47:00 +00004903
4904/* Cooperative 'super' */
4905
4906typedef struct {
4907 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00004908 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004909 PyObject *obj;
4910} superobject;
4911
Guido van Rossum6f799372001-09-20 20:46:19 +00004912static PyMemberDef super_members[] = {
4913 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
4914 "the class invoking super()"},
4915 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
4916 "the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004917 {0}
4918};
4919
Guido van Rossum705f0f52001-08-24 16:47:00 +00004920static void
4921super_dealloc(PyObject *self)
4922{
4923 superobject *su = (superobject *)self;
4924
Guido van Rossum048eb752001-10-02 21:24:57 +00004925 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00004926 Py_XDECREF(su->obj);
4927 Py_XDECREF(su->type);
4928 self->ob_type->tp_free(self);
4929}
4930
4931static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004932super_repr(PyObject *self)
4933{
4934 superobject *su = (superobject *)self;
4935
4936 if (su->obj)
4937 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00004938 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004939 su->type ? su->type->tp_name : "NULL",
4940 su->obj->ob_type->tp_name);
4941 else
4942 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00004943 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004944 su->type ? su->type->tp_name : "NULL");
4945}
4946
4947static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00004948super_getattro(PyObject *self, PyObject *name)
4949{
4950 superobject *su = (superobject *)self;
4951
4952 if (su->obj != NULL) {
Tim Petersa91e9642001-11-14 23:32:33 +00004953 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum155db9a2002-04-02 17:53:47 +00004954 PyTypeObject *starttype;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004955 descrgetfunc f;
4956 int i, n;
4957
Guido van Rossum155db9a2002-04-02 17:53:47 +00004958 starttype = su->obj->ob_type;
4959 mro = starttype->tp_mro;
4960
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004961 if (mro == NULL)
4962 n = 0;
4963 else {
4964 assert(PyTuple_Check(mro));
4965 n = PyTuple_GET_SIZE(mro);
4966 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004967 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00004968 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00004969 break;
4970 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004971 if (i >= n && PyType_Check(su->obj)) {
Guido van Rossum155db9a2002-04-02 17:53:47 +00004972 starttype = (PyTypeObject *)(su->obj);
4973 mro = starttype->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004974 if (mro == NULL)
4975 n = 0;
4976 else {
4977 assert(PyTuple_Check(mro));
4978 n = PyTuple_GET_SIZE(mro);
4979 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004980 for (i = 0; i < n; i++) {
4981 if ((PyObject *)(su->type) ==
4982 PyTuple_GET_ITEM(mro, i))
4983 break;
4984 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004985 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004986 i++;
4987 res = NULL;
4988 for (; i < n; i++) {
4989 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00004990 if (PyType_Check(tmp))
4991 dict = ((PyTypeObject *)tmp)->tp_dict;
4992 else if (PyClass_Check(tmp))
4993 dict = ((PyClassObject *)tmp)->cl_dict;
4994 else
4995 continue;
4996 res = PyDict_GetItem(dict, name);
Guido van Rossum5b443c62001-12-03 15:38:28 +00004997 if (res != NULL && !PyDescr_IsData(res)) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00004998 Py_INCREF(res);
4999 f = res->ob_type->tp_descr_get;
5000 if (f != NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00005001 tmp = f(res, su->obj,
5002 (PyObject *)starttype);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005003 Py_DECREF(res);
5004 res = tmp;
5005 }
5006 return res;
5007 }
5008 }
5009 }
5010 return PyObject_GenericGetAttr(self, name);
5011}
5012
Guido van Rossum5b443c62001-12-03 15:38:28 +00005013static int
5014supercheck(PyTypeObject *type, PyObject *obj)
5015{
5016 if (!PyType_IsSubtype(obj->ob_type, type) &&
5017 !(PyType_Check(obj) &&
5018 PyType_IsSubtype((PyTypeObject *)obj, type))) {
5019 PyErr_SetString(PyExc_TypeError,
5020 "super(type, obj): "
5021 "obj must be an instance or subtype of type");
5022 return -1;
5023 }
5024 else
5025 return 0;
5026}
5027
Guido van Rossum705f0f52001-08-24 16:47:00 +00005028static PyObject *
5029super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5030{
5031 superobject *su = (superobject *)self;
5032 superobject *new;
5033
5034 if (obj == NULL || obj == Py_None || su->obj != NULL) {
5035 /* Not binding to an object, or already bound */
5036 Py_INCREF(self);
5037 return self;
5038 }
Guido van Rossum5b443c62001-12-03 15:38:28 +00005039 if (su->ob_type != &PySuper_Type)
5040 /* If su is an instance of a subclass of super,
5041 call its type */
5042 return PyObject_CallFunction((PyObject *)su->ob_type,
5043 "OO", su->type, obj);
5044 else {
5045 /* Inline the common case */
5046 if (supercheck(su->type, obj) < 0)
5047 return NULL;
5048 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
5049 NULL, NULL);
5050 if (new == NULL)
5051 return NULL;
5052 Py_INCREF(su->type);
5053 Py_INCREF(obj);
5054 new->type = su->type;
5055 new->obj = obj;
5056 return (PyObject *)new;
5057 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005058}
5059
5060static int
5061super_init(PyObject *self, PyObject *args, PyObject *kwds)
5062{
5063 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00005064 PyTypeObject *type;
5065 PyObject *obj = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005066
5067 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
5068 return -1;
5069 if (obj == Py_None)
5070 obj = NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005071 if (obj != NULL && supercheck(type, obj) < 0)
Guido van Rossum705f0f52001-08-24 16:47:00 +00005072 return -1;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005073 Py_INCREF(type);
5074 Py_XINCREF(obj);
5075 su->type = type;
5076 su->obj = obj;
5077 return 0;
5078}
5079
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005080PyDoc_STRVAR(super_doc,
Guido van Rossum705f0f52001-08-24 16:47:00 +00005081"super(type) -> unbound super object\n"
5082"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00005083"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00005084"Typical use to call a cooperative superclass method:\n"
5085"class C(B):\n"
5086" def meth(self, arg):\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005087" super(C, self).meth(arg)");
Guido van Rossum705f0f52001-08-24 16:47:00 +00005088
Guido van Rossum048eb752001-10-02 21:24:57 +00005089static int
5090super_traverse(PyObject *self, visitproc visit, void *arg)
5091{
5092 superobject *su = (superobject *)self;
5093 int err;
5094
5095#define VISIT(SLOT) \
5096 if (SLOT) { \
5097 err = visit((PyObject *)(SLOT), arg); \
5098 if (err) \
5099 return err; \
5100 }
5101
5102 VISIT(su->obj);
5103 VISIT(su->type);
5104
5105#undef VISIT
5106
5107 return 0;
5108}
5109
Guido van Rossum705f0f52001-08-24 16:47:00 +00005110PyTypeObject PySuper_Type = {
5111 PyObject_HEAD_INIT(&PyType_Type)
5112 0, /* ob_size */
5113 "super", /* tp_name */
5114 sizeof(superobject), /* tp_basicsize */
5115 0, /* tp_itemsize */
5116 /* methods */
5117 super_dealloc, /* tp_dealloc */
5118 0, /* tp_print */
5119 0, /* tp_getattr */
5120 0, /* tp_setattr */
5121 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005122 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005123 0, /* tp_as_number */
5124 0, /* tp_as_sequence */
5125 0, /* tp_as_mapping */
5126 0, /* tp_hash */
5127 0, /* tp_call */
5128 0, /* tp_str */
5129 super_getattro, /* tp_getattro */
5130 0, /* tp_setattro */
5131 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00005132 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
5133 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005134 super_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00005135 super_traverse, /* tp_traverse */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005136 0, /* tp_clear */
5137 0, /* tp_richcompare */
5138 0, /* tp_weaklistoffset */
5139 0, /* tp_iter */
5140 0, /* tp_iternext */
5141 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005142 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005143 0, /* tp_getset */
5144 0, /* tp_base */
5145 0, /* tp_dict */
5146 super_descr_get, /* tp_descr_get */
5147 0, /* tp_descr_set */
5148 0, /* tp_dictoffset */
5149 super_init, /* tp_init */
5150 PyType_GenericAlloc, /* tp_alloc */
5151 PyType_GenericNew, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00005152 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005153};