blob: f05cf7c97ce2614e2169829fc9a1cdab4920e3dd [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);
Guido van Rossum768158c2002-12-31 16:33:01 +00001070 if (remain[j] < PyList_GET_SIZE(j_lst) &&
1071 PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001072 remain[j]++;
1073 }
1074 }
1075 goto again;
Tim Peters9a6b8d82002-11-14 23:22:33 +00001076 skip: ;
Guido van Rossum1f121312002-11-14 19:49:16 +00001077 }
1078
Guido van Rossum98f33732002-11-25 21:36:54 +00001079 if (empty_cnt == to_merge_size) {
1080 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001081 return 0;
Guido van Rossum98f33732002-11-25 21:36:54 +00001082 }
1083 set_mro_error(to_merge, remain);
1084 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001085 return -1;
1086}
1087
Tim Peters6d6c1a32001-08-02 04:15:00 +00001088static PyObject *
1089mro_implementation(PyTypeObject *type)
1090{
1091 int i, n, ok;
1092 PyObject *bases, *result;
Guido van Rossum1f121312002-11-14 19:49:16 +00001093 PyObject *to_merge, *bases_aslist;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001094
Guido van Rossum63517572002-06-18 16:44:57 +00001095 if(type->tp_dict == NULL) {
1096 if(PyType_Ready(type) < 0)
1097 return NULL;
1098 }
1099
Guido van Rossum98f33732002-11-25 21:36:54 +00001100 /* Find a superclass linearization that honors the constraints
1101 of the explicit lists of bases and the constraints implied by
Tim Petersea7f75d2002-12-07 21:39:16 +00001102 each base class.
Guido van Rossum98f33732002-11-25 21:36:54 +00001103
1104 to_merge is a list of lists, where each list is a superclass
1105 linearization implied by a base class. The last element of
1106 to_merge is the declared list of bases.
1107 */
1108
Tim Peters6d6c1a32001-08-02 04:15:00 +00001109 bases = type->tp_bases;
1110 n = PyTuple_GET_SIZE(bases);
Guido van Rossum1f121312002-11-14 19:49:16 +00001111
1112 to_merge = PyList_New(n+1);
1113 if (to_merge == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001114 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001115
Tim Peters6d6c1a32001-08-02 04:15:00 +00001116 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001117 PyObject *base = PyTuple_GET_ITEM(bases, i);
1118 PyObject *parentMRO;
1119 if (PyType_Check(base))
1120 parentMRO = PySequence_List(
1121 ((PyTypeObject*)base)->tp_mro);
1122 else
1123 parentMRO = classic_mro(base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001124 if (parentMRO == NULL) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001125 Py_DECREF(to_merge);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001126 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001127 }
1128
1129 PyList_SET_ITEM(to_merge, i, parentMRO);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001130 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001131
1132 bases_aslist = PySequence_List(bases);
1133 if (bases_aslist == NULL) {
1134 Py_DECREF(to_merge);
1135 return NULL;
1136 }
Guido van Rossum98f33732002-11-25 21:36:54 +00001137 /* This is just a basic sanity check. */
1138 if (check_duplicates(bases_aslist) < 0) {
1139 Py_DECREF(to_merge);
1140 Py_DECREF(bases_aslist);
1141 return NULL;
1142 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001143 PyList_SET_ITEM(to_merge, n, bases_aslist);
1144
1145 result = Py_BuildValue("[O]", (PyObject *)type);
1146 if (result == NULL) {
1147 Py_DECREF(to_merge);
1148 return NULL;
1149 }
1150
1151 ok = pmerge(result, to_merge);
1152 Py_DECREF(to_merge);
1153 if (ok < 0) {
1154 Py_DECREF(result);
1155 return NULL;
1156 }
1157
Tim Peters6d6c1a32001-08-02 04:15:00 +00001158 return result;
1159}
1160
1161static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001162mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001163{
1164 PyTypeObject *type = (PyTypeObject *)self;
1165
Tim Peters6d6c1a32001-08-02 04:15:00 +00001166 return mro_implementation(type);
1167}
1168
1169static int
1170mro_internal(PyTypeObject *type)
1171{
1172 PyObject *mro, *result, *tuple;
1173
1174 if (type->ob_type == &PyType_Type) {
1175 result = mro_implementation(type);
1176 }
1177 else {
Guido van Rossum60718732001-08-28 17:47:51 +00001178 static PyObject *mro_str;
1179 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001180 if (mro == NULL)
1181 return -1;
1182 result = PyObject_CallObject(mro, NULL);
1183 Py_DECREF(mro);
1184 }
1185 if (result == NULL)
1186 return -1;
1187 tuple = PySequence_Tuple(result);
1188 Py_DECREF(result);
1189 type->tp_mro = tuple;
1190 return 0;
1191}
1192
1193
1194/* Calculate the best base amongst multiple base classes.
1195 This is the first one that's on the path to the "solid base". */
1196
1197static PyTypeObject *
1198best_base(PyObject *bases)
1199{
1200 int i, n;
1201 PyTypeObject *base, *winner, *candidate, *base_i;
Tim Petersa91e9642001-11-14 23:32:33 +00001202 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001203
1204 assert(PyTuple_Check(bases));
1205 n = PyTuple_GET_SIZE(bases);
1206 assert(n > 0);
Tim Petersa91e9642001-11-14 23:32:33 +00001207 base = NULL;
1208 winner = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001209 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001210 base_proto = PyTuple_GET_ITEM(bases, i);
1211 if (PyClass_Check(base_proto))
1212 continue;
1213 if (!PyType_Check(base_proto)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001214 PyErr_SetString(
1215 PyExc_TypeError,
1216 "bases must be types");
1217 return NULL;
1218 }
Tim Petersa91e9642001-11-14 23:32:33 +00001219 base_i = (PyTypeObject *)base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001220 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001221 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001222 return NULL;
1223 }
1224 candidate = solid_base(base_i);
Tim Petersa91e9642001-11-14 23:32:33 +00001225 if (winner == NULL) {
1226 winner = candidate;
1227 base = base_i;
1228 }
1229 else if (PyType_IsSubtype(winner, candidate))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001230 ;
1231 else if (PyType_IsSubtype(candidate, winner)) {
1232 winner = candidate;
1233 base = base_i;
1234 }
1235 else {
1236 PyErr_SetString(
1237 PyExc_TypeError,
1238 "multiple bases have "
1239 "instance lay-out conflict");
1240 return NULL;
1241 }
1242 }
Guido van Rossume54616c2001-12-14 04:19:56 +00001243 if (base == NULL)
1244 PyErr_SetString(PyExc_TypeError,
1245 "a new-style class can't have only classic bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001246 return base;
1247}
1248
1249static int
1250extra_ivars(PyTypeObject *type, PyTypeObject *base)
1251{
Neil Schemenauerc806c882001-08-29 23:54:54 +00001252 size_t t_size = type->tp_basicsize;
1253 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001254
Guido van Rossum9676b222001-08-17 20:32:36 +00001255 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001256 if (type->tp_itemsize || base->tp_itemsize) {
1257 /* If itemsize is involved, stricter rules */
1258 return t_size != b_size ||
1259 type->tp_itemsize != base->tp_itemsize;
1260 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001261 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
1262 type->tp_weaklistoffset + sizeof(PyObject *) == t_size)
1263 t_size -= sizeof(PyObject *);
1264 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
1265 type->tp_dictoffset + sizeof(PyObject *) == t_size)
1266 t_size -= sizeof(PyObject *);
1267
1268 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001269}
1270
1271static PyTypeObject *
1272solid_base(PyTypeObject *type)
1273{
1274 PyTypeObject *base;
1275
1276 if (type->tp_base)
1277 base = solid_base(type->tp_base);
1278 else
1279 base = &PyBaseObject_Type;
1280 if (extra_ivars(type, base))
1281 return type;
1282 else
1283 return base;
1284}
1285
Jeremy Hylton938ace62002-07-17 16:30:39 +00001286static void object_dealloc(PyObject *);
1287static int object_init(PyObject *, PyObject *, PyObject *);
1288static int update_slot(PyTypeObject *, PyObject *);
1289static void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001290
1291static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001292subtype_dict(PyObject *obj, void *context)
1293{
1294 PyObject **dictptr = _PyObject_GetDictPtr(obj);
1295 PyObject *dict;
1296
1297 if (dictptr == NULL) {
1298 PyErr_SetString(PyExc_AttributeError,
1299 "This object has no __dict__");
1300 return NULL;
1301 }
1302 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +00001303 if (dict == NULL)
1304 *dictptr = dict = PyDict_New();
1305 Py_XINCREF(dict);
1306 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001307}
1308
Guido van Rossum6661be32001-10-26 04:26:12 +00001309static int
1310subtype_setdict(PyObject *obj, PyObject *value, void *context)
1311{
1312 PyObject **dictptr = _PyObject_GetDictPtr(obj);
1313 PyObject *dict;
1314
1315 if (dictptr == NULL) {
1316 PyErr_SetString(PyExc_AttributeError,
1317 "This object has no __dict__");
1318 return -1;
1319 }
Guido van Rossumd331cb52001-12-05 19:46:42 +00001320 if (value != NULL && !PyDict_Check(value)) {
Guido van Rossum6661be32001-10-26 04:26:12 +00001321 PyErr_SetString(PyExc_TypeError,
1322 "__dict__ must be set to a dictionary");
1323 return -1;
1324 }
1325 dict = *dictptr;
Guido van Rossumd331cb52001-12-05 19:46:42 +00001326 Py_XINCREF(value);
Guido van Rossum6661be32001-10-26 04:26:12 +00001327 *dictptr = value;
1328 Py_XDECREF(dict);
1329 return 0;
1330}
1331
Guido van Rossumad47da02002-08-12 19:05:44 +00001332static PyObject *
1333subtype_getweakref(PyObject *obj, void *context)
1334{
1335 PyObject **weaklistptr;
1336 PyObject *result;
1337
1338 if (obj->ob_type->tp_weaklistoffset == 0) {
1339 PyErr_SetString(PyExc_AttributeError,
1340 "This object has no __weaklist__");
1341 return NULL;
1342 }
1343 assert(obj->ob_type->tp_weaklistoffset > 0);
1344 assert(obj->ob_type->tp_weaklistoffset + sizeof(PyObject *) <=
Guido van Rossum3747a0f2002-08-12 19:25:08 +00001345 (size_t)(obj->ob_type->tp_basicsize));
Guido van Rossumad47da02002-08-12 19:05:44 +00001346 weaklistptr = (PyObject **)
Guido van Rossum3747a0f2002-08-12 19:25:08 +00001347 ((char *)obj + obj->ob_type->tp_weaklistoffset);
Guido van Rossumad47da02002-08-12 19:05:44 +00001348 if (*weaklistptr == NULL)
1349 result = Py_None;
1350 else
1351 result = *weaklistptr;
1352 Py_INCREF(result);
1353 return result;
1354}
1355
Neil Schemenauerf23473f2001-10-21 22:28:58 +00001356static PyGetSetDef subtype_getsets[] = {
Guido van Rossumad47da02002-08-12 19:05:44 +00001357 /* Not all objects have these attributes!
1358 The descriptor's __get__ method may raise AttributeError. */
1359 {"__dict__", subtype_dict, subtype_setdict,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001360 PyDoc_STR("dictionary for instance variables (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001361 {"__weakref__", subtype_getweakref, NULL,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001362 PyDoc_STR("list of weak references to the object (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001363 {0}
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001364};
1365
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001366/* bozo: __getstate__ that raises TypeError */
1367
1368static PyObject *
1369bozo_func(PyObject *self, PyObject *args)
1370{
1371 PyErr_SetString(PyExc_TypeError,
1372 "a class that defines __slots__ without "
1373 "defining __getstate__ cannot be pickled");
1374 return NULL;
1375}
1376
Neal Norwitz93c1e232002-03-31 16:06:11 +00001377static PyMethodDef bozo_ml = {"__getstate__", bozo_func, METH_VARARGS};
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001378
1379static PyObject *bozo_obj = NULL;
1380
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001381static int
1382valid_identifier(PyObject *s)
1383{
Guido van Rossum03013a02002-07-16 14:30:28 +00001384 unsigned char *p;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001385 int i, n;
1386
1387 if (!PyString_Check(s)) {
1388 PyErr_SetString(PyExc_TypeError,
1389 "__slots__ must be strings");
1390 return 0;
1391 }
Guido van Rossum03013a02002-07-16 14:30:28 +00001392 p = (unsigned char *) PyString_AS_STRING(s);
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001393 n = PyString_GET_SIZE(s);
1394 /* We must reject an empty name. As a hack, we bump the
1395 length to 1 so that the loop will balk on the trailing \0. */
1396 if (n == 0)
1397 n = 1;
1398 for (i = 0; i < n; i++, p++) {
1399 if (!(i == 0 ? isalpha(*p) : isalnum(*p)) && *p != '_') {
1400 PyErr_SetString(PyExc_TypeError,
1401 "__slots__ must be identifiers");
1402 return 0;
1403 }
1404 }
1405 return 1;
1406}
1407
Martin v. Löwisd919a592002-10-14 21:07:28 +00001408#ifdef Py_USING_UNICODE
1409/* Replace Unicode objects in slots. */
1410
1411static PyObject *
1412_unicode_to_string(PyObject *slots, int nslots)
1413{
1414 PyObject *tmp = slots;
1415 PyObject *o, *o1;
1416 int i;
1417 intintargfunc copy = slots->ob_type->tp_as_sequence->sq_slice;
1418 for (i = 0; i < nslots; i++) {
1419 if (PyUnicode_Check(o = PyTuple_GET_ITEM(tmp, i))) {
1420 if (tmp == slots) {
1421 tmp = copy(slots, 0, PyTuple_GET_SIZE(slots));
1422 if (tmp == NULL)
1423 return NULL;
1424 }
1425 o1 = _PyUnicode_AsDefaultEncodedString
1426 (o, NULL);
1427 if (o1 == NULL) {
1428 Py_DECREF(tmp);
1429 return 0;
1430 }
1431 Py_INCREF(o1);
1432 Py_DECREF(o);
1433 PyTuple_SET_ITEM(tmp, i, o1);
1434 }
1435 }
1436 return tmp;
1437}
1438#endif
1439
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001440static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001441type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
1442{
1443 PyObject *name, *bases, *dict;
1444 static char *kwlist[] = {"name", "bases", "dict", 0};
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001445 PyObject *slots, *tmp, *newslots;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001446 PyTypeObject *type, *base, *tmptype, *winner;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001447 etype *et;
Guido van Rossum6f799372001-09-20 20:46:19 +00001448 PyMemberDef *mp;
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001449 int i, nbases, nslots, slotoffset, add_dict, add_weak;
Guido van Rossumad47da02002-08-12 19:05:44 +00001450 int j, may_add_dict, may_add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001451
Tim Peters3abca122001-10-27 19:37:48 +00001452 assert(args != NULL && PyTuple_Check(args));
1453 assert(kwds == NULL || PyDict_Check(kwds));
1454
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001455 /* Special case: type(x) should return x->ob_type */
Tim Peters3abca122001-10-27 19:37:48 +00001456 {
1457 const int nargs = PyTuple_GET_SIZE(args);
1458 const int nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
1459
1460 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
1461 PyObject *x = PyTuple_GET_ITEM(args, 0);
1462 Py_INCREF(x->ob_type);
1463 return (PyObject *) x->ob_type;
1464 }
1465
1466 /* SF bug 475327 -- if that didn't trigger, we need 3
1467 arguments. but PyArg_ParseTupleAndKeywords below may give
1468 a msg saying type() needs exactly 3. */
1469 if (nargs + nkwds != 3) {
1470 PyErr_SetString(PyExc_TypeError,
1471 "type() takes 1 or 3 arguments");
1472 return NULL;
1473 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001474 }
1475
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001476 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001477 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
1478 &name,
1479 &PyTuple_Type, &bases,
1480 &PyDict_Type, &dict))
1481 return NULL;
1482
1483 /* Determine the proper metatype to deal with this,
1484 and check for metatype conflicts while we're at it.
1485 Note that if some other metatype wins to contract,
1486 it's possible that its instances are not types. */
1487 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001488 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001489 for (i = 0; i < nbases; i++) {
1490 tmp = PyTuple_GET_ITEM(bases, i);
1491 tmptype = tmp->ob_type;
Tim Petersa91e9642001-11-14 23:32:33 +00001492 if (tmptype == &PyClass_Type)
1493 continue; /* Special case classic classes */
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001494 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001495 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001496 if (PyType_IsSubtype(tmptype, winner)) {
1497 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001498 continue;
1499 }
1500 PyErr_SetString(PyExc_TypeError,
1501 "metatype conflict among bases");
1502 return NULL;
1503 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001504 if (winner != metatype) {
1505 if (winner->tp_new != type_new) /* Pass it to the winner */
1506 return winner->tp_new(winner, args, kwds);
1507 metatype = winner;
1508 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001509
1510 /* Adjust for empty tuple bases */
1511 if (nbases == 0) {
1512 bases = Py_BuildValue("(O)", &PyBaseObject_Type);
1513 if (bases == NULL)
1514 return NULL;
1515 nbases = 1;
1516 }
1517 else
1518 Py_INCREF(bases);
1519
1520 /* XXX From here until type is allocated, "return NULL" leaks bases! */
1521
1522 /* Calculate best base, and check that all bases are type objects */
1523 base = best_base(bases);
1524 if (base == NULL)
1525 return NULL;
1526 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
1527 PyErr_Format(PyExc_TypeError,
1528 "type '%.100s' is not an acceptable base type",
1529 base->tp_name);
1530 return NULL;
1531 }
1532
Tim Peters6d6c1a32001-08-02 04:15:00 +00001533 /* Check for a __slots__ sequence variable in dict, and count it */
1534 slots = PyDict_GetItemString(dict, "__slots__");
1535 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +00001536 add_dict = 0;
1537 add_weak = 0;
Guido van Rossumad47da02002-08-12 19:05:44 +00001538 may_add_dict = base->tp_dictoffset == 0;
1539 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
1540 if (slots == NULL) {
1541 if (may_add_dict) {
1542 add_dict++;
1543 }
1544 if (may_add_weak) {
1545 add_weak++;
1546 }
1547 }
1548 else {
1549 /* Have slots */
1550
Tim Peters6d6c1a32001-08-02 04:15:00 +00001551 /* Make it into a tuple */
1552 if (PyString_Check(slots))
1553 slots = Py_BuildValue("(O)", slots);
1554 else
1555 slots = PySequence_Tuple(slots);
1556 if (slots == NULL)
1557 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00001558 assert(PyTuple_Check(slots));
1559
1560 /* Are slots allowed? */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001561 nslots = PyTuple_GET_SIZE(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +00001562 if (nslots > 0 && base->tp_itemsize != 0) {
1563 PyErr_Format(PyExc_TypeError,
1564 "nonempty __slots__ "
1565 "not supported for subtype of '%s'",
1566 base->tp_name);
Guido van Rossumad47da02002-08-12 19:05:44 +00001567 bad_slots:
1568 Py_DECREF(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +00001569 return NULL;
1570 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001571
Martin v. Löwisd919a592002-10-14 21:07:28 +00001572#ifdef Py_USING_UNICODE
1573 tmp = _unicode_to_string(slots, nslots);
Martin v. Löwis13b1a5c2002-10-14 21:11:34 +00001574 if (tmp != slots) {
1575 Py_DECREF(slots);
1576 slots = tmp;
1577 }
Martin v. Löwisd919a592002-10-14 21:07:28 +00001578 if (!tmp)
1579 return NULL;
1580#endif
Guido van Rossumad47da02002-08-12 19:05:44 +00001581 /* Check for valid slot names and two special cases */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001582 for (i = 0; i < nslots; i++) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001583 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
1584 char *s;
1585 if (!valid_identifier(tmp))
1586 goto bad_slots;
1587 assert(PyString_Check(tmp));
1588 s = PyString_AS_STRING(tmp);
1589 if (strcmp(s, "__dict__") == 0) {
1590 if (!may_add_dict || add_dict) {
1591 PyErr_SetString(PyExc_TypeError,
1592 "__dict__ slot disallowed: "
1593 "we already got one");
1594 goto bad_slots;
1595 }
1596 add_dict++;
1597 }
1598 if (strcmp(s, "__weakref__") == 0) {
1599 if (!may_add_weak || add_weak) {
1600 PyErr_SetString(PyExc_TypeError,
1601 "__weakref__ slot disallowed: "
1602 "either we already got one, "
1603 "or __itemsize__ != 0");
1604 goto bad_slots;
1605 }
1606 add_weak++;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001607 }
1608 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001609
Guido van Rossumad47da02002-08-12 19:05:44 +00001610 /* Copy slots into yet another tuple, demangling names */
1611 newslots = PyTuple_New(nslots - add_dict - add_weak);
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001612 if (newslots == NULL)
Guido van Rossumad47da02002-08-12 19:05:44 +00001613 goto bad_slots;
1614 for (i = j = 0; i < nslots; i++) {
1615 char *s;
Guido van Rossum8e829202002-08-16 03:47:49 +00001616 char buffer[256];
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001617 tmp = PyTuple_GET_ITEM(slots, i);
Guido van Rossumad47da02002-08-12 19:05:44 +00001618 s = PyString_AS_STRING(tmp);
1619 if ((add_dict && strcmp(s, "__dict__") == 0) ||
1620 (add_weak && strcmp(s, "__weakref__") == 0))
1621 continue;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001622 if (_Py_Mangle(PyString_AS_STRING(name),
Guido van Rossumad47da02002-08-12 19:05:44 +00001623 PyString_AS_STRING(tmp),
1624 buffer, sizeof(buffer)))
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001625 {
1626 tmp = PyString_FromString(buffer);
1627 } else {
1628 Py_INCREF(tmp);
1629 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001630 PyTuple_SET_ITEM(newslots, j, tmp);
1631 j++;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001632 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001633 assert(j == nslots - add_dict - add_weak);
1634 nslots = j;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001635 Py_DECREF(slots);
1636 slots = newslots;
1637
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001638 /* See if *this* class defines __getstate__ */
Guido van Rossumad47da02002-08-12 19:05:44 +00001639 if (PyDict_GetItemString(dict, "__getstate__") == NULL) {
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001640 /* If not, provide a bozo that raises TypeError */
1641 if (bozo_obj == NULL) {
1642 bozo_obj = PyCFunction_New(&bozo_ml, NULL);
Guido van Rossumad47da02002-08-12 19:05:44 +00001643 if (bozo_obj == NULL)
1644 goto bad_slots;
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001645 }
1646 if (PyDict_SetItemString(dict,
1647 "__getstate__",
Guido van Rossumad47da02002-08-12 19:05:44 +00001648 bozo_obj) < 0)
1649 {
1650 Py_DECREF(bozo_obj);
1651 goto bad_slots;
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001652 }
1653 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001654
1655 /* Secondary bases may provide weakrefs or dict */
1656 if (nbases > 1 &&
1657 ((may_add_dict && !add_dict) ||
1658 (may_add_weak && !add_weak))) {
1659 for (i = 0; i < nbases; i++) {
1660 tmp = PyTuple_GET_ITEM(bases, i);
1661 if (tmp == (PyObject *)base)
1662 continue; /* Skip primary base */
1663 if (PyClass_Check(tmp)) {
1664 /* Classic base class provides both */
1665 if (may_add_dict && !add_dict)
1666 add_dict++;
1667 if (may_add_weak && !add_weak)
1668 add_weak++;
1669 break;
1670 }
1671 assert(PyType_Check(tmp));
1672 tmptype = (PyTypeObject *)tmp;
1673 if (may_add_dict && !add_dict &&
1674 tmptype->tp_dictoffset != 0)
1675 add_dict++;
1676 if (may_add_weak && !add_weak &&
1677 tmptype->tp_weaklistoffset != 0)
1678 add_weak++;
1679 if (may_add_dict && !add_dict)
1680 continue;
1681 if (may_add_weak && !add_weak)
1682 continue;
1683 /* Nothing more to check */
1684 break;
1685 }
1686 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001687 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001688
1689 /* XXX From here until type is safely allocated,
1690 "return NULL" may leak slots! */
1691
1692 /* Allocate the type object */
1693 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
Guido van Rossumad47da02002-08-12 19:05:44 +00001694 if (type == NULL) {
1695 Py_XDECREF(slots);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001696 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00001697 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001698
1699 /* Keep name and slots alive in the extended type object */
1700 et = (etype *)type;
1701 Py_INCREF(name);
1702 et->name = name;
1703 et->slots = slots;
1704
Guido van Rossumdc91b992001-08-08 22:26:22 +00001705 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001706 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
1707 Py_TPFLAGS_BASETYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00001708 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
1709 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00001710
1711 /* It's a new-style number unless it specifically inherits any
1712 old-style numeric behavior */
1713 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
1714 (base->tp_as_number == NULL))
1715 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
1716
1717 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001718 type->tp_as_number = &et->as_number;
1719 type->tp_as_sequence = &et->as_sequence;
1720 type->tp_as_mapping = &et->as_mapping;
1721 type->tp_as_buffer = &et->as_buffer;
1722 type->tp_name = PyString_AS_STRING(name);
1723
1724 /* Set tp_base and tp_bases */
1725 type->tp_bases = bases;
1726 Py_INCREF(base);
1727 type->tp_base = base;
1728
Guido van Rossum687ae002001-10-15 22:03:32 +00001729 /* Initialize tp_dict from passed-in dict */
1730 type->tp_dict = dict = PyDict_Copy(dict);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001731 if (dict == NULL) {
1732 Py_DECREF(type);
1733 return NULL;
1734 }
1735
Guido van Rossumc3542212001-08-16 09:18:56 +00001736 /* Set __module__ in the dict */
1737 if (PyDict_GetItemString(dict, "__module__") == NULL) {
1738 tmp = PyEval_GetGlobals();
1739 if (tmp != NULL) {
1740 tmp = PyDict_GetItemString(tmp, "__name__");
1741 if (tmp != NULL) {
1742 if (PyDict_SetItemString(dict, "__module__",
1743 tmp) < 0)
1744 return NULL;
1745 }
1746 }
1747 }
1748
Tim Peters2f93e282001-10-04 05:27:00 +00001749 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
Tim Peters24008312002-03-17 18:56:20 +00001750 and is a string. The __doc__ accessor will first look for tp_doc;
1751 if that fails, it will still look into __dict__.
Tim Peters2f93e282001-10-04 05:27:00 +00001752 */
1753 {
1754 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
1755 if (doc != NULL && PyString_Check(doc)) {
1756 const size_t n = (size_t)PyString_GET_SIZE(doc);
Tim Peters59f809d2001-10-04 05:43:02 +00001757 type->tp_doc = (char *)PyObject_MALLOC(n+1);
Tim Peters2f93e282001-10-04 05:27:00 +00001758 if (type->tp_doc == NULL) {
1759 Py_DECREF(type);
1760 return NULL;
1761 }
1762 memcpy(type->tp_doc, PyString_AS_STRING(doc), n+1);
1763 }
1764 }
1765
Tim Peters6d6c1a32001-08-02 04:15:00 +00001766 /* Special-case __new__: if it's a plain function,
1767 make it a static function */
1768 tmp = PyDict_GetItemString(dict, "__new__");
1769 if (tmp != NULL && PyFunction_Check(tmp)) {
1770 tmp = PyStaticMethod_New(tmp);
1771 if (tmp == NULL) {
1772 Py_DECREF(type);
1773 return NULL;
1774 }
1775 PyDict_SetItemString(dict, "__new__", tmp);
1776 Py_DECREF(tmp);
1777 }
1778
1779 /* Add descriptors for custom slots from __slots__, or for __dict__ */
1780 mp = et->members;
Neil Schemenauerc806c882001-08-29 23:54:54 +00001781 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001782 if (slots != NULL) {
1783 for (i = 0; i < nslots; i++, mp++) {
1784 mp->name = PyString_AS_STRING(
1785 PyTuple_GET_ITEM(slots, i));
Guido van Rossum64b206c2001-12-04 17:13:22 +00001786 mp->type = T_OBJECT_EX;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001787 mp->offset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +00001788 if (base->tp_weaklistoffset == 0 &&
Guido van Rossum64b206c2001-12-04 17:13:22 +00001789 strcmp(mp->name, "__weakref__") == 0) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001790 add_weak++;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001791 mp->type = T_OBJECT;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001792 mp->flags = READONLY;
Guido van Rossum9676b222001-08-17 20:32:36 +00001793 type->tp_weaklistoffset = slotoffset;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001794 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001795 slotoffset += sizeof(PyObject *);
1796 }
1797 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001798 if (add_dict) {
1799 if (base->tp_itemsize)
1800 type->tp_dictoffset = -(long)sizeof(PyObject *);
1801 else
1802 type->tp_dictoffset = slotoffset;
1803 slotoffset += sizeof(PyObject *);
1804 }
1805 if (add_weak) {
1806 assert(!base->tp_itemsize);
1807 type->tp_weaklistoffset = slotoffset;
1808 slotoffset += sizeof(PyObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001809 }
1810 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001811 type->tp_itemsize = base->tp_itemsize;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001812 type->tp_members = et->members;
Guido van Rossumad47da02002-08-12 19:05:44 +00001813 type->tp_getset = subtype_getsets;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001814
1815 /* Special case some slots */
1816 if (type->tp_dictoffset != 0 || nslots > 0) {
1817 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
1818 type->tp_getattro = PyObject_GenericGetAttr;
1819 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
1820 type->tp_setattro = PyObject_GenericSetAttr;
1821 }
1822 type->tp_dealloc = subtype_dealloc;
1823
Guido van Rossum9475a232001-10-05 20:51:39 +00001824 /* Enable GC unless there are really no instance variables possible */
1825 if (!(type->tp_basicsize == sizeof(PyObject) &&
1826 type->tp_itemsize == 0))
1827 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
1828
Tim Peters6d6c1a32001-08-02 04:15:00 +00001829 /* Always override allocation strategy to use regular heap */
1830 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00001831 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001832 type->tp_free = PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00001833 type->tp_traverse = subtype_traverse;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001834 type->tp_clear = subtype_clear;
Guido van Rossum048eb752001-10-02 21:24:57 +00001835 }
1836 else
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001837 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001838
1839 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001840 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001841 Py_DECREF(type);
1842 return NULL;
1843 }
1844
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001845 /* Put the proper slots in place */
1846 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00001847
Tim Peters6d6c1a32001-08-02 04:15:00 +00001848 return (PyObject *)type;
1849}
1850
1851/* Internal API to look for a name through the MRO.
1852 This returns a borrowed reference, and doesn't set an exception! */
1853PyObject *
1854_PyType_Lookup(PyTypeObject *type, PyObject *name)
1855{
1856 int i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00001857 PyObject *mro, *res, *base, *dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001858
Guido van Rossum687ae002001-10-15 22:03:32 +00001859 /* Look in tp_dict of types in MRO */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001860 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00001861
1862 /* If mro is NULL, the type is either not yet initialized
1863 by PyType_Ready(), or already cleared by type_clear().
1864 Either way the safest thing to do is to return NULL. */
1865 if (mro == NULL)
1866 return NULL;
1867
Tim Peters6d6c1a32001-08-02 04:15:00 +00001868 assert(PyTuple_Check(mro));
1869 n = PyTuple_GET_SIZE(mro);
1870 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001871 base = PyTuple_GET_ITEM(mro, i);
1872 if (PyClass_Check(base))
1873 dict = ((PyClassObject *)base)->cl_dict;
1874 else {
1875 assert(PyType_Check(base));
1876 dict = ((PyTypeObject *)base)->tp_dict;
1877 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001878 assert(dict && PyDict_Check(dict));
1879 res = PyDict_GetItem(dict, name);
1880 if (res != NULL)
1881 return res;
1882 }
1883 return NULL;
1884}
1885
1886/* This is similar to PyObject_GenericGetAttr(),
1887 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
1888static PyObject *
1889type_getattro(PyTypeObject *type, PyObject *name)
1890{
1891 PyTypeObject *metatype = type->ob_type;
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001892 PyObject *meta_attribute, *attribute;
1893 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001894
1895 /* Initialize this type (we'll assume the metatype is initialized) */
1896 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001897 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001898 return NULL;
1899 }
1900
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001901 /* No readable descriptor found yet */
1902 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00001903
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001904 /* Look for the attribute in the metatype */
1905 meta_attribute = _PyType_Lookup(metatype, name);
1906
1907 if (meta_attribute != NULL) {
1908 meta_get = meta_attribute->ob_type->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00001909
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001910 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
1911 /* Data descriptors implement tp_descr_set to intercept
1912 * writes. Assume the attribute is not overridden in
1913 * type's tp_dict (and bases): call the descriptor now.
1914 */
1915 return meta_get(meta_attribute, (PyObject *)type,
1916 (PyObject *)metatype);
1917 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001918 }
1919
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001920 /* No data descriptor found on metatype. Look in tp_dict of this
1921 * type and its bases */
1922 attribute = _PyType_Lookup(type, name);
1923 if (attribute != NULL) {
1924 /* Implement descriptor functionality, if any */
1925 descrgetfunc local_get = attribute->ob_type->tp_descr_get;
1926 if (local_get != NULL) {
1927 /* NULL 2nd argument indicates the descriptor was
1928 * found on the target object itself (or a base) */
1929 return local_get(attribute, (PyObject *)NULL,
1930 (PyObject *)type);
1931 }
Tim Peters34592512002-07-11 06:23:50 +00001932
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001933 Py_INCREF(attribute);
1934 return attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001935 }
1936
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001937 /* No attribute found in local __dict__ (or bases): use the
1938 * descriptor from the metatype, if any */
1939 if (meta_get != NULL)
1940 return meta_get(meta_attribute, (PyObject *)type,
1941 (PyObject *)metatype);
1942
1943 /* If an ordinary attribute was found on the metatype, return it now */
1944 if (meta_attribute != NULL) {
1945 Py_INCREF(meta_attribute);
1946 return meta_attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001947 }
1948
1949 /* Give up */
1950 PyErr_Format(PyExc_AttributeError,
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001951 "type object '%.50s' has no attribute '%.400s'",
1952 type->tp_name, PyString_AS_STRING(name));
Tim Peters6d6c1a32001-08-02 04:15:00 +00001953 return NULL;
1954}
1955
1956static int
1957type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
1958{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001959 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
1960 PyErr_Format(
1961 PyExc_TypeError,
1962 "can't set attributes of built-in/extension type '%s'",
1963 type->tp_name);
1964 return -1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001965 }
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001966 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
1967 return -1;
1968 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001969}
1970
1971static void
1972type_dealloc(PyTypeObject *type)
1973{
1974 etype *et;
1975
1976 /* Assert this is a heap-allocated type object */
1977 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00001978 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00001979 PyObject_ClearWeakRefs((PyObject *)type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001980 et = (etype *)type;
1981 Py_XDECREF(type->tp_base);
1982 Py_XDECREF(type->tp_dict);
1983 Py_XDECREF(type->tp_bases);
1984 Py_XDECREF(type->tp_mro);
Guido van Rossum687ae002001-10-15 22:03:32 +00001985 Py_XDECREF(type->tp_cache);
Guido van Rossum1c450732001-10-08 15:18:27 +00001986 Py_XDECREF(type->tp_subclasses);
Neal Norwitzcee5ca02002-07-30 00:42:06 +00001987 PyObject_Free(type->tp_doc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001988 Py_XDECREF(et->name);
1989 Py_XDECREF(et->slots);
1990 type->ob_type->tp_free((PyObject *)type);
1991}
1992
Guido van Rossum1c450732001-10-08 15:18:27 +00001993static PyObject *
1994type_subclasses(PyTypeObject *type, PyObject *args_ignored)
1995{
1996 PyObject *list, *raw, *ref;
1997 int i, n;
1998
1999 list = PyList_New(0);
2000 if (list == NULL)
2001 return NULL;
2002 raw = type->tp_subclasses;
2003 if (raw == NULL)
2004 return list;
2005 assert(PyList_Check(raw));
2006 n = PyList_GET_SIZE(raw);
2007 for (i = 0; i < n; i++) {
2008 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00002009 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00002010 ref = PyWeakref_GET_OBJECT(ref);
2011 if (ref != Py_None) {
2012 if (PyList_Append(list, ref) < 0) {
2013 Py_DECREF(list);
2014 return NULL;
2015 }
2016 }
2017 }
2018 return list;
2019}
2020
Tim Peters6d6c1a32001-08-02 04:15:00 +00002021static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002022 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002023 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
Guido van Rossum1c450732001-10-08 15:18:27 +00002024 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002025 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002026 {0}
2027};
2028
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002029PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002030"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002031"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002032
Guido van Rossum048eb752001-10-02 21:24:57 +00002033static int
2034type_traverse(PyTypeObject *type, visitproc visit, void *arg)
2035{
Guido van Rossum048eb752001-10-02 21:24:57 +00002036 int err;
2037
Guido van Rossuma3862092002-06-10 15:24:42 +00002038 /* Because of type_is_gc(), the collector only calls this
2039 for heaptypes. */
2040 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002041
2042#define VISIT(SLOT) \
2043 if (SLOT) { \
2044 err = visit((PyObject *)(SLOT), arg); \
2045 if (err) \
2046 return err; \
2047 }
2048
2049 VISIT(type->tp_dict);
Guido van Rossum687ae002001-10-15 22:03:32 +00002050 VISIT(type->tp_cache);
Guido van Rossum048eb752001-10-02 21:24:57 +00002051 VISIT(type->tp_mro);
2052 VISIT(type->tp_bases);
2053 VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00002054
2055 /* There's no need to visit type->tp_subclasses or
2056 ((etype *)type)->slots, because they can't be involved
2057 in cycles; tp_subclasses is a list of weak references,
2058 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00002059
2060#undef VISIT
2061
2062 return 0;
2063}
2064
2065static int
2066type_clear(PyTypeObject *type)
2067{
Guido van Rossum048eb752001-10-02 21:24:57 +00002068 PyObject *tmp;
2069
Guido van Rossuma3862092002-06-10 15:24:42 +00002070 /* Because of type_is_gc(), the collector only calls this
2071 for heaptypes. */
2072 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002073
2074#define CLEAR(SLOT) \
2075 if (SLOT) { \
2076 tmp = (PyObject *)(SLOT); \
2077 SLOT = NULL; \
2078 Py_DECREF(tmp); \
2079 }
2080
Guido van Rossuma3862092002-06-10 15:24:42 +00002081 /* The only field we need to clear is tp_mro, which is part of a
2082 hard cycle (its first element is the class itself) that won't
2083 be broken otherwise (it's a tuple and tuples don't have a
2084 tp_clear handler). None of the other fields need to be
2085 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00002086
Guido van Rossuma3862092002-06-10 15:24:42 +00002087 tp_dict:
2088 It is a dict, so the collector will call its tp_clear.
2089
2090 tp_cache:
2091 Not used; if it were, it would be a dict.
2092
2093 tp_bases, tp_base:
2094 If these are involved in a cycle, there must be at least
2095 one other, mutable object in the cycle, e.g. a base
2096 class's dict; the cycle will be broken that way.
2097
2098 tp_subclasses:
2099 A list of weak references can't be part of a cycle; and
2100 lists have their own tp_clear.
2101
2102 slots (in etype):
2103 A tuple of strings can't be part of a cycle.
2104 */
2105
2106 CLEAR(type->tp_mro);
Tim Peters2f93e282001-10-04 05:27:00 +00002107
Guido van Rossum048eb752001-10-02 21:24:57 +00002108#undef CLEAR
2109
2110 return 0;
2111}
2112
2113static int
2114type_is_gc(PyTypeObject *type)
2115{
2116 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
2117}
2118
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002119PyTypeObject PyType_Type = {
2120 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002121 0, /* ob_size */
2122 "type", /* tp_name */
2123 sizeof(etype), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00002124 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002125 (destructor)type_dealloc, /* tp_dealloc */
2126 0, /* tp_print */
2127 0, /* tp_getattr */
2128 0, /* tp_setattr */
2129 type_compare, /* tp_compare */
2130 (reprfunc)type_repr, /* tp_repr */
2131 0, /* tp_as_number */
2132 0, /* tp_as_sequence */
2133 0, /* tp_as_mapping */
2134 (hashfunc)_Py_HashPointer, /* tp_hash */
2135 (ternaryfunc)type_call, /* tp_call */
2136 0, /* tp_str */
2137 (getattrofunc)type_getattro, /* tp_getattro */
2138 (setattrofunc)type_setattro, /* tp_setattro */
2139 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00002140 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2141 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002142 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00002143 (traverseproc)type_traverse, /* tp_traverse */
2144 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002145 0, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00002146 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002147 0, /* tp_iter */
2148 0, /* tp_iternext */
2149 type_methods, /* tp_methods */
2150 type_members, /* tp_members */
2151 type_getsets, /* tp_getset */
2152 0, /* tp_base */
2153 0, /* tp_dict */
2154 0, /* tp_descr_get */
2155 0, /* tp_descr_set */
2156 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
2157 0, /* tp_init */
2158 0, /* tp_alloc */
2159 type_new, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002160 PyObject_GC_Del, /* tp_free */
Guido van Rossum048eb752001-10-02 21:24:57 +00002161 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002162};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002163
2164
2165/* The base type of all types (eventually)... except itself. */
2166
2167static int
2168object_init(PyObject *self, PyObject *args, PyObject *kwds)
2169{
2170 return 0;
2171}
2172
2173static void
2174object_dealloc(PyObject *self)
2175{
2176 self->ob_type->tp_free(self);
2177}
2178
Guido van Rossum8e248182001-08-12 05:17:56 +00002179static PyObject *
2180object_repr(PyObject *self)
2181{
Guido van Rossum76e69632001-08-16 18:52:43 +00002182 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00002183 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002184
Guido van Rossum76e69632001-08-16 18:52:43 +00002185 type = self->ob_type;
2186 mod = type_module(type, NULL);
2187 if (mod == NULL)
2188 PyErr_Clear();
2189 else if (!PyString_Check(mod)) {
2190 Py_DECREF(mod);
2191 mod = NULL;
2192 }
2193 name = type_name(type, NULL);
2194 if (name == NULL)
2195 return NULL;
2196 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002197 rtn = PyString_FromFormat("<%s.%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002198 PyString_AS_STRING(mod),
2199 PyString_AS_STRING(name),
2200 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002201 else
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002202 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002203 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002204 Py_XDECREF(mod);
2205 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00002206 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002207}
2208
Guido van Rossumb8f63662001-08-15 23:57:02 +00002209static PyObject *
2210object_str(PyObject *self)
2211{
2212 unaryfunc f;
2213
2214 f = self->ob_type->tp_repr;
2215 if (f == NULL)
2216 f = object_repr;
2217 return f(self);
2218}
2219
Guido van Rossum8e248182001-08-12 05:17:56 +00002220static long
2221object_hash(PyObject *self)
2222{
2223 return _Py_HashPointer(self);
2224}
Guido van Rossum8e248182001-08-12 05:17:56 +00002225
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002226static PyObject *
2227object_get_class(PyObject *self, void *closure)
2228{
2229 Py_INCREF(self->ob_type);
2230 return (PyObject *)(self->ob_type);
2231}
2232
2233static int
2234equiv_structs(PyTypeObject *a, PyTypeObject *b)
2235{
2236 return a == b ||
2237 (a != NULL &&
2238 b != NULL &&
2239 a->tp_basicsize == b->tp_basicsize &&
2240 a->tp_itemsize == b->tp_itemsize &&
2241 a->tp_dictoffset == b->tp_dictoffset &&
2242 a->tp_weaklistoffset == b->tp_weaklistoffset &&
2243 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
2244 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
2245}
2246
2247static int
2248same_slots_added(PyTypeObject *a, PyTypeObject *b)
2249{
2250 PyTypeObject *base = a->tp_base;
2251 int size;
2252
2253 if (base != b->tp_base)
2254 return 0;
2255 if (equiv_structs(a, base) && equiv_structs(b, base))
2256 return 1;
2257 size = base->tp_basicsize;
2258 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
2259 size += sizeof(PyObject *);
2260 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
2261 size += sizeof(PyObject *);
2262 return size == a->tp_basicsize && size == b->tp_basicsize;
2263}
2264
2265static int
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002266compatible_for_assignment(PyTypeObject* old, PyTypeObject* new, char* attr)
2267{
2268 PyTypeObject *newbase, *oldbase;
2269
2270 if (new->tp_dealloc != old->tp_dealloc ||
2271 new->tp_free != old->tp_free)
2272 {
2273 PyErr_Format(PyExc_TypeError,
2274 "%s assignment: "
2275 "'%s' deallocator differs from '%s'",
2276 attr,
2277 new->tp_name,
2278 old->tp_name);
2279 return 0;
2280 }
2281 newbase = new;
2282 oldbase = old;
2283 while (equiv_structs(newbase, newbase->tp_base))
2284 newbase = newbase->tp_base;
2285 while (equiv_structs(oldbase, oldbase->tp_base))
2286 oldbase = oldbase->tp_base;
2287 if (newbase != oldbase &&
2288 (newbase->tp_base != oldbase->tp_base ||
2289 !same_slots_added(newbase, oldbase))) {
2290 PyErr_Format(PyExc_TypeError,
2291 "%s assignment: "
2292 "'%s' object layout differs from '%s'",
2293 attr,
2294 new->tp_name,
2295 old->tp_name);
2296 return 0;
2297 }
Tim Petersea7f75d2002-12-07 21:39:16 +00002298
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002299 return 1;
2300}
2301
2302static int
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002303object_set_class(PyObject *self, PyObject *value, void *closure)
2304{
2305 PyTypeObject *old = self->ob_type;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002306 PyTypeObject *new;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002307
Guido van Rossumb6b89422002-04-15 01:03:30 +00002308 if (value == NULL) {
2309 PyErr_SetString(PyExc_TypeError,
2310 "can't delete __class__ attribute");
2311 return -1;
2312 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002313 if (!PyType_Check(value)) {
2314 PyErr_Format(PyExc_TypeError,
2315 "__class__ must be set to new-style class, not '%s' object",
2316 value->ob_type->tp_name);
2317 return -1;
2318 }
2319 new = (PyTypeObject *)value;
Guido van Rossum40af8892002-08-10 05:42:07 +00002320 if (!(new->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
2321 !(old->tp_flags & Py_TPFLAGS_HEAPTYPE))
2322 {
2323 PyErr_Format(PyExc_TypeError,
2324 "__class__ assignment: only for heap types");
2325 return -1;
2326 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002327 if (compatible_for_assignment(new, old, "__class__")) {
2328 Py_INCREF(new);
2329 self->ob_type = new;
2330 Py_DECREF(old);
2331 return 0;
2332 }
2333 else {
Guido van Rossum9ee4b942002-05-24 18:47:47 +00002334 return -1;
2335 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002336}
2337
2338static PyGetSetDef object_getsets[] = {
2339 {"__class__", object_get_class, object_set_class,
Neal Norwitz858e34f2002-08-13 17:18:45 +00002340 PyDoc_STR("the object's class")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002341 {0}
2342};
2343
Guido van Rossum3926a632001-09-25 16:25:58 +00002344static PyObject *
2345object_reduce(PyObject *self, PyObject *args)
2346{
2347 /* Call copy_reg._reduce(self) */
2348 static PyObject *copy_reg_str;
2349 PyObject *copy_reg, *res;
2350
2351 if (!copy_reg_str) {
2352 copy_reg_str = PyString_InternFromString("copy_reg");
2353 if (copy_reg_str == NULL)
2354 return NULL;
2355 }
2356 copy_reg = PyImport_Import(copy_reg_str);
2357 if (!copy_reg)
2358 return NULL;
2359 res = PyEval_CallMethod(copy_reg, "_reduce", "(O)", self);
2360 Py_DECREF(copy_reg);
2361 return res;
2362}
2363
2364static PyMethodDef object_methods[] = {
Tim Petersea7f75d2002-12-07 21:39:16 +00002365 {"__reduce__", object_reduce, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002366 PyDoc_STR("helper for pickle")},
Guido van Rossum3926a632001-09-25 16:25:58 +00002367 {0}
2368};
2369
Tim Peters6d6c1a32001-08-02 04:15:00 +00002370PyTypeObject PyBaseObject_Type = {
2371 PyObject_HEAD_INIT(&PyType_Type)
2372 0, /* ob_size */
2373 "object", /* tp_name */
2374 sizeof(PyObject), /* tp_basicsize */
2375 0, /* tp_itemsize */
2376 (destructor)object_dealloc, /* tp_dealloc */
2377 0, /* tp_print */
2378 0, /* tp_getattr */
2379 0, /* tp_setattr */
2380 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002381 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002382 0, /* tp_as_number */
2383 0, /* tp_as_sequence */
2384 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002385 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002386 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002387 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002388 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002389 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002390 0, /* tp_as_buffer */
2391 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002392 PyDoc_STR("The most base type"), /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002393 0, /* tp_traverse */
2394 0, /* tp_clear */
2395 0, /* tp_richcompare */
2396 0, /* tp_weaklistoffset */
2397 0, /* tp_iter */
2398 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00002399 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002400 0, /* tp_members */
2401 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002402 0, /* tp_base */
2403 0, /* tp_dict */
2404 0, /* tp_descr_get */
2405 0, /* tp_descr_set */
2406 0, /* tp_dictoffset */
2407 object_init, /* tp_init */
2408 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossumc11e1922001-08-09 19:38:15 +00002409 PyType_GenericNew, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002410 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002411};
2412
2413
2414/* Initialize the __dict__ in a type object */
2415
Fred Drake7bf97152002-03-28 05:33:33 +00002416static PyObject *
2417create_specialmethod(PyMethodDef *meth, PyObject *(*func)(PyObject *))
2418{
2419 PyObject *cfunc;
2420 PyObject *result;
2421
2422 cfunc = PyCFunction_New(meth, NULL);
2423 if (cfunc == NULL)
2424 return NULL;
2425 result = func(cfunc);
2426 Py_DECREF(cfunc);
2427 return result;
2428}
2429
Tim Peters6d6c1a32001-08-02 04:15:00 +00002430static int
2431add_methods(PyTypeObject *type, PyMethodDef *meth)
2432{
Guido van Rossum687ae002001-10-15 22:03:32 +00002433 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002434
2435 for (; meth->ml_name != NULL; meth++) {
2436 PyObject *descr;
2437 if (PyDict_GetItemString(dict, meth->ml_name))
2438 continue;
Fred Drake7bf97152002-03-28 05:33:33 +00002439 if (meth->ml_flags & METH_CLASS) {
2440 if (meth->ml_flags & METH_STATIC) {
2441 PyErr_SetString(PyExc_ValueError,
2442 "method cannot be both class and static");
2443 return -1;
2444 }
Tim Petersbca1cbc2002-12-09 22:56:13 +00002445 descr = PyDescr_NewClassMethod(type, meth);
Fred Drake7bf97152002-03-28 05:33:33 +00002446 }
2447 else if (meth->ml_flags & METH_STATIC) {
2448 descr = create_specialmethod(meth, PyStaticMethod_New);
2449 }
2450 else {
2451 descr = PyDescr_NewMethod(type, meth);
2452 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002453 if (descr == NULL)
2454 return -1;
Fred Drake7bf97152002-03-28 05:33:33 +00002455 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002456 return -1;
2457 Py_DECREF(descr);
2458 }
2459 return 0;
2460}
2461
2462static int
Guido van Rossum6f799372001-09-20 20:46:19 +00002463add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002464{
Guido van Rossum687ae002001-10-15 22:03:32 +00002465 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002466
2467 for (; memb->name != NULL; memb++) {
2468 PyObject *descr;
2469 if (PyDict_GetItemString(dict, memb->name))
2470 continue;
2471 descr = PyDescr_NewMember(type, memb);
2472 if (descr == NULL)
2473 return -1;
2474 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
2475 return -1;
2476 Py_DECREF(descr);
2477 }
2478 return 0;
2479}
2480
2481static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00002482add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002483{
Guido van Rossum687ae002001-10-15 22:03:32 +00002484 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002485
2486 for (; gsp->name != NULL; gsp++) {
2487 PyObject *descr;
2488 if (PyDict_GetItemString(dict, gsp->name))
2489 continue;
2490 descr = PyDescr_NewGetSet(type, gsp);
2491
2492 if (descr == NULL)
2493 return -1;
2494 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
2495 return -1;
2496 Py_DECREF(descr);
2497 }
2498 return 0;
2499}
2500
Guido van Rossum13d52f02001-08-10 21:24:08 +00002501static void
2502inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002503{
2504 int oldsize, newsize;
2505
Guido van Rossum13d52f02001-08-10 21:24:08 +00002506 /* Special flag magic */
2507 if (!type->tp_as_buffer && base->tp_as_buffer) {
2508 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
2509 type->tp_flags |=
2510 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
2511 }
2512 if (!type->tp_as_sequence && base->tp_as_sequence) {
2513 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
2514 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
2515 }
2516 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
2517 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
2518 if ((!type->tp_as_number && base->tp_as_number) ||
2519 (!type->tp_as_sequence && base->tp_as_sequence)) {
2520 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
2521 if (!type->tp_as_number && !type->tp_as_sequence) {
2522 type->tp_flags |= base->tp_flags &
2523 Py_TPFLAGS_HAVE_INPLACEOPS;
2524 }
2525 }
2526 /* Wow */
2527 }
2528 if (!type->tp_as_number && base->tp_as_number) {
2529 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
2530 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
2531 }
2532
2533 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00002534 oldsize = base->tp_basicsize;
2535 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
2536 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
2537 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00002538 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
2539 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00002540 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00002541 if (type->tp_traverse == NULL)
2542 type->tp_traverse = base->tp_traverse;
2543 if (type->tp_clear == NULL)
2544 type->tp_clear = base->tp_clear;
2545 }
2546 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
Guido van Rossumf884b742001-12-17 17:14:22 +00002547 /* The condition below could use some explanation.
2548 It appears that tp_new is not inherited for static types
2549 whose base class is 'object'; this seems to be a precaution
2550 so that old extension types don't suddenly become
2551 callable (object.__new__ wouldn't insure the invariants
2552 that the extension type's own factory function ensures).
2553 Heap types, of course, are under our control, so they do
2554 inherit tp_new; static extension types that specify some
2555 other built-in type as the default are considered
2556 new-style-aware so they also inherit object.__new__. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002557 if (base != &PyBaseObject_Type ||
2558 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2559 if (type->tp_new == NULL)
2560 type->tp_new = base->tp_new;
2561 }
2562 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00002563 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00002564
2565 /* Copy other non-function slots */
2566
2567#undef COPYVAL
2568#define COPYVAL(SLOT) \
2569 if (type->SLOT == 0) type->SLOT = base->SLOT
2570
2571 COPYVAL(tp_itemsize);
2572 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
2573 COPYVAL(tp_weaklistoffset);
2574 }
2575 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2576 COPYVAL(tp_dictoffset);
2577 }
Guido van Rossum13d52f02001-08-10 21:24:08 +00002578}
2579
2580static void
2581inherit_slots(PyTypeObject *type, PyTypeObject *base)
2582{
2583 PyTypeObject *basebase;
2584
2585#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00002586#undef COPYSLOT
2587#undef COPYNUM
2588#undef COPYSEQ
2589#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00002590#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00002591
2592#define SLOTDEFINED(SLOT) \
2593 (base->SLOT != 0 && \
2594 (basebase == NULL || base->SLOT != basebase->SLOT))
2595
Tim Peters6d6c1a32001-08-02 04:15:00 +00002596#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00002597 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00002598
2599#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
2600#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
2601#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00002602#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002603
Guido van Rossum13d52f02001-08-10 21:24:08 +00002604 /* This won't inherit indirect slots (from tp_as_number etc.)
2605 if type doesn't provide the space. */
2606
2607 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
2608 basebase = base->tp_base;
2609 if (basebase->tp_as_number == NULL)
2610 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002611 COPYNUM(nb_add);
2612 COPYNUM(nb_subtract);
2613 COPYNUM(nb_multiply);
2614 COPYNUM(nb_divide);
2615 COPYNUM(nb_remainder);
2616 COPYNUM(nb_divmod);
2617 COPYNUM(nb_power);
2618 COPYNUM(nb_negative);
2619 COPYNUM(nb_positive);
2620 COPYNUM(nb_absolute);
2621 COPYNUM(nb_nonzero);
2622 COPYNUM(nb_invert);
2623 COPYNUM(nb_lshift);
2624 COPYNUM(nb_rshift);
2625 COPYNUM(nb_and);
2626 COPYNUM(nb_xor);
2627 COPYNUM(nb_or);
2628 COPYNUM(nb_coerce);
2629 COPYNUM(nb_int);
2630 COPYNUM(nb_long);
2631 COPYNUM(nb_float);
2632 COPYNUM(nb_oct);
2633 COPYNUM(nb_hex);
2634 COPYNUM(nb_inplace_add);
2635 COPYNUM(nb_inplace_subtract);
2636 COPYNUM(nb_inplace_multiply);
2637 COPYNUM(nb_inplace_divide);
2638 COPYNUM(nb_inplace_remainder);
2639 COPYNUM(nb_inplace_power);
2640 COPYNUM(nb_inplace_lshift);
2641 COPYNUM(nb_inplace_rshift);
2642 COPYNUM(nb_inplace_and);
2643 COPYNUM(nb_inplace_xor);
2644 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00002645 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
2646 COPYNUM(nb_true_divide);
2647 COPYNUM(nb_floor_divide);
2648 COPYNUM(nb_inplace_true_divide);
2649 COPYNUM(nb_inplace_floor_divide);
2650 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002651 }
2652
Guido van Rossum13d52f02001-08-10 21:24:08 +00002653 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
2654 basebase = base->tp_base;
2655 if (basebase->tp_as_sequence == NULL)
2656 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002657 COPYSEQ(sq_length);
2658 COPYSEQ(sq_concat);
2659 COPYSEQ(sq_repeat);
2660 COPYSEQ(sq_item);
2661 COPYSEQ(sq_slice);
2662 COPYSEQ(sq_ass_item);
2663 COPYSEQ(sq_ass_slice);
2664 COPYSEQ(sq_contains);
2665 COPYSEQ(sq_inplace_concat);
2666 COPYSEQ(sq_inplace_repeat);
2667 }
2668
Guido van Rossum13d52f02001-08-10 21:24:08 +00002669 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
2670 basebase = base->tp_base;
2671 if (basebase->tp_as_mapping == NULL)
2672 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002673 COPYMAP(mp_length);
2674 COPYMAP(mp_subscript);
2675 COPYMAP(mp_ass_subscript);
2676 }
2677
Tim Petersfc57ccb2001-10-12 02:38:24 +00002678 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
2679 basebase = base->tp_base;
2680 if (basebase->tp_as_buffer == NULL)
2681 basebase = NULL;
2682 COPYBUF(bf_getreadbuffer);
2683 COPYBUF(bf_getwritebuffer);
2684 COPYBUF(bf_getsegcount);
2685 COPYBUF(bf_getcharbuffer);
2686 }
2687
Guido van Rossum13d52f02001-08-10 21:24:08 +00002688 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002689
Tim Peters6d6c1a32001-08-02 04:15:00 +00002690 COPYSLOT(tp_dealloc);
2691 COPYSLOT(tp_print);
2692 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
2693 type->tp_getattr = base->tp_getattr;
2694 type->tp_getattro = base->tp_getattro;
2695 }
2696 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
2697 type->tp_setattr = base->tp_setattr;
2698 type->tp_setattro = base->tp_setattro;
2699 }
2700 /* tp_compare see tp_richcompare */
2701 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002702 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002703 COPYSLOT(tp_call);
2704 COPYSLOT(tp_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002705 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00002706 if (type->tp_compare == NULL &&
2707 type->tp_richcompare == NULL &&
2708 type->tp_hash == NULL)
2709 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00002710 type->tp_compare = base->tp_compare;
2711 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002712 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002713 }
2714 }
2715 else {
2716 COPYSLOT(tp_compare);
2717 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002718 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
2719 COPYSLOT(tp_iter);
2720 COPYSLOT(tp_iternext);
2721 }
2722 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2723 COPYSLOT(tp_descr_get);
2724 COPYSLOT(tp_descr_set);
2725 COPYSLOT(tp_dictoffset);
2726 COPYSLOT(tp_init);
2727 COPYSLOT(tp_alloc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002728 COPYSLOT(tp_free);
Guido van Rossumcc8fe042002-04-05 17:10:16 +00002729 COPYSLOT(tp_is_gc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002730 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002731}
2732
Jeremy Hylton938ace62002-07-17 16:30:39 +00002733static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00002734
Tim Peters6d6c1a32001-08-02 04:15:00 +00002735int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002736PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002737{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002738 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002739 PyTypeObject *base;
2740 int i, n;
2741
Guido van Rossumcab05802002-06-10 15:29:03 +00002742 if (type->tp_flags & Py_TPFLAGS_READY) {
2743 assert(type->tp_dict != NULL);
Guido van Rossumd614f972001-08-10 17:39:49 +00002744 return 0;
Guido van Rossumcab05802002-06-10 15:29:03 +00002745 }
Guido van Rossumd614f972001-08-10 17:39:49 +00002746 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00002747
2748 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002749
2750 /* Initialize tp_base (defaults to BaseObject unless that's us) */
2751 base = type->tp_base;
2752 if (base == NULL && type != &PyBaseObject_Type)
2753 base = type->tp_base = &PyBaseObject_Type;
2754
Guido van Rossum323a9cf2002-08-14 17:26:30 +00002755 /* Initialize the base class */
2756 if (base && base->tp_dict == NULL) {
2757 if (PyType_Ready(base) < 0)
2758 goto error;
2759 }
2760
Guido van Rossum0986d822002-04-08 01:38:42 +00002761 /* Initialize ob_type if NULL. This means extensions that want to be
2762 compilable separately on Windows can call PyType_Ready() instead of
2763 initializing the ob_type field of their type objects. */
2764 if (type->ob_type == NULL)
2765 type->ob_type = base->ob_type;
2766
Tim Peters6d6c1a32001-08-02 04:15:00 +00002767 /* Initialize tp_bases */
2768 bases = type->tp_bases;
2769 if (bases == NULL) {
2770 if (base == NULL)
2771 bases = PyTuple_New(0);
2772 else
2773 bases = Py_BuildValue("(O)", base);
2774 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00002775 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002776 type->tp_bases = bases;
2777 }
2778
Guido van Rossum687ae002001-10-15 22:03:32 +00002779 /* Initialize tp_dict */
2780 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002781 if (dict == NULL) {
2782 dict = PyDict_New();
2783 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00002784 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00002785 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002786 }
2787
Guido van Rossum687ae002001-10-15 22:03:32 +00002788 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002789 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002790 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002791 if (type->tp_methods != NULL) {
2792 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002793 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002794 }
2795 if (type->tp_members != NULL) {
2796 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002797 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002798 }
2799 if (type->tp_getset != NULL) {
2800 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002801 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002802 }
2803
Tim Peters6d6c1a32001-08-02 04:15:00 +00002804 /* Calculate method resolution order */
2805 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00002806 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002807 }
2808
Guido van Rossum13d52f02001-08-10 21:24:08 +00002809 /* Inherit special flags from dominant base */
2810 if (type->tp_base != NULL)
2811 inherit_special(type, type->tp_base);
2812
Tim Peters6d6c1a32001-08-02 04:15:00 +00002813 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002814 bases = type->tp_mro;
2815 assert(bases != NULL);
2816 assert(PyTuple_Check(bases));
2817 n = PyTuple_GET_SIZE(bases);
2818 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002819 PyObject *b = PyTuple_GET_ITEM(bases, i);
2820 if (PyType_Check(b))
2821 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002822 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002823
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00002824 /* if the type dictionary doesn't contain a __doc__, set it from
2825 the tp_doc slot.
2826 */
2827 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
2828 if (type->tp_doc != NULL) {
2829 PyObject *doc = PyString_FromString(type->tp_doc);
2830 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
2831 Py_DECREF(doc);
2832 } else {
Guido van Rossumd4641072002-04-03 02:13:37 +00002833 PyDict_SetItemString(type->tp_dict,
2834 "__doc__", Py_None);
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00002835 }
2836 }
2837
Guido van Rossum13d52f02001-08-10 21:24:08 +00002838 /* Some more special stuff */
2839 base = type->tp_base;
2840 if (base != NULL) {
2841 if (type->tp_as_number == NULL)
2842 type->tp_as_number = base->tp_as_number;
2843 if (type->tp_as_sequence == NULL)
2844 type->tp_as_sequence = base->tp_as_sequence;
2845 if (type->tp_as_mapping == NULL)
2846 type->tp_as_mapping = base->tp_as_mapping;
2847 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002848
Guido van Rossum1c450732001-10-08 15:18:27 +00002849 /* Link into each base class's list of subclasses */
2850 bases = type->tp_bases;
2851 n = PyTuple_GET_SIZE(bases);
2852 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002853 PyObject *b = PyTuple_GET_ITEM(bases, i);
2854 if (PyType_Check(b) &&
2855 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00002856 goto error;
2857 }
2858
Guido van Rossum13d52f02001-08-10 21:24:08 +00002859 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00002860 assert(type->tp_dict != NULL);
2861 type->tp_flags =
2862 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002863 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00002864
2865 error:
2866 type->tp_flags &= ~Py_TPFLAGS_READYING;
2867 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002868}
2869
Guido van Rossum1c450732001-10-08 15:18:27 +00002870static int
2871add_subclass(PyTypeObject *base, PyTypeObject *type)
2872{
2873 int i;
2874 PyObject *list, *ref, *new;
2875
2876 list = base->tp_subclasses;
2877 if (list == NULL) {
2878 base->tp_subclasses = list = PyList_New(0);
2879 if (list == NULL)
2880 return -1;
2881 }
2882 assert(PyList_Check(list));
2883 new = PyWeakref_NewRef((PyObject *)type, NULL);
2884 i = PyList_GET_SIZE(list);
2885 while (--i >= 0) {
2886 ref = PyList_GET_ITEM(list, i);
2887 assert(PyWeakref_CheckRef(ref));
Guido van Rossum3930bc32002-10-18 13:51:49 +00002888 if (PyWeakref_GET_OBJECT(ref) == Py_None)
2889 return PyList_SetItem(list, i, new);
Guido van Rossum1c450732001-10-08 15:18:27 +00002890 }
2891 i = PyList_Append(list, new);
2892 Py_DECREF(new);
2893 return i;
2894}
2895
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002896static void
2897remove_subclass(PyTypeObject *base, PyTypeObject *type)
2898{
2899 int i;
2900 PyObject *list, *ref;
2901
2902 list = base->tp_subclasses;
2903 if (list == NULL) {
2904 return;
2905 }
2906 assert(PyList_Check(list));
2907 i = PyList_GET_SIZE(list);
2908 while (--i >= 0) {
2909 ref = PyList_GET_ITEM(list, i);
2910 assert(PyWeakref_CheckRef(ref));
2911 if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
2912 /* this can't fail, right? */
2913 PySequence_DelItem(list, i);
2914 return;
2915 }
2916 }
2917}
Tim Peters6d6c1a32001-08-02 04:15:00 +00002918
2919/* Generic wrappers for overloadable 'operators' such as __getitem__ */
2920
2921/* There's a wrapper *function* for each distinct function typedef used
2922 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
2923 wrapper *table* for each distinct operation (e.g. __len__, __add__).
2924 Most tables have only one entry; the tables for binary operators have two
2925 entries, one regular and one with reversed arguments. */
2926
2927static PyObject *
2928wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
2929{
2930 inquiry func = (inquiry)wrapped;
2931 int res;
2932
2933 if (!PyArg_ParseTuple(args, ""))
2934 return NULL;
2935 res = (*func)(self);
2936 if (res == -1 && PyErr_Occurred())
2937 return NULL;
2938 return PyInt_FromLong((long)res);
2939}
2940
Tim Peters6d6c1a32001-08-02 04:15:00 +00002941static PyObject *
2942wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
2943{
2944 binaryfunc func = (binaryfunc)wrapped;
2945 PyObject *other;
2946
2947 if (!PyArg_ParseTuple(args, "O", &other))
2948 return NULL;
2949 return (*func)(self, other);
2950}
2951
2952static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002953wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
2954{
2955 binaryfunc func = (binaryfunc)wrapped;
2956 PyObject *other;
2957
2958 if (!PyArg_ParseTuple(args, "O", &other))
2959 return NULL;
2960 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002961 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002962 Py_INCREF(Py_NotImplemented);
2963 return Py_NotImplemented;
2964 }
2965 return (*func)(self, other);
2966}
2967
2968static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00002969wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2970{
2971 binaryfunc func = (binaryfunc)wrapped;
2972 PyObject *other;
2973
2974 if (!PyArg_ParseTuple(args, "O", &other))
2975 return NULL;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002976 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002977 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002978 Py_INCREF(Py_NotImplemented);
2979 return Py_NotImplemented;
2980 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002981 return (*func)(other, self);
2982}
2983
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00002984static PyObject *
2985wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
2986{
2987 coercion func = (coercion)wrapped;
2988 PyObject *other, *res;
2989 int ok;
2990
2991 if (!PyArg_ParseTuple(args, "O", &other))
2992 return NULL;
2993 ok = func(&self, &other);
2994 if (ok < 0)
2995 return NULL;
2996 if (ok > 0) {
2997 Py_INCREF(Py_NotImplemented);
2998 return Py_NotImplemented;
2999 }
3000 res = PyTuple_New(2);
3001 if (res == NULL) {
3002 Py_DECREF(self);
3003 Py_DECREF(other);
3004 return NULL;
3005 }
3006 PyTuple_SET_ITEM(res, 0, self);
3007 PyTuple_SET_ITEM(res, 1, other);
3008 return res;
3009}
3010
Tim Peters6d6c1a32001-08-02 04:15:00 +00003011static PyObject *
3012wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
3013{
3014 ternaryfunc func = (ternaryfunc)wrapped;
3015 PyObject *other;
3016 PyObject *third = Py_None;
3017
3018 /* Note: This wrapper only works for __pow__() */
3019
3020 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
3021 return NULL;
3022 return (*func)(self, other, third);
3023}
3024
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00003025static PyObject *
3026wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3027{
3028 ternaryfunc func = (ternaryfunc)wrapped;
3029 PyObject *other;
3030 PyObject *third = Py_None;
3031
3032 /* Note: This wrapper only works for __pow__() */
3033
3034 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
3035 return NULL;
3036 return (*func)(other, self, third);
3037}
3038
Tim Peters6d6c1a32001-08-02 04:15:00 +00003039static PyObject *
3040wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
3041{
3042 unaryfunc func = (unaryfunc)wrapped;
3043
3044 if (!PyArg_ParseTuple(args, ""))
3045 return NULL;
3046 return (*func)(self);
3047}
3048
Tim Peters6d6c1a32001-08-02 04:15:00 +00003049static PyObject *
3050wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
3051{
3052 intargfunc func = (intargfunc)wrapped;
3053 int i;
3054
3055 if (!PyArg_ParseTuple(args, "i", &i))
3056 return NULL;
3057 return (*func)(self, i);
3058}
3059
Guido van Rossum5d815f32001-08-17 21:57:47 +00003060static int
3061getindex(PyObject *self, PyObject *arg)
3062{
3063 int i;
3064
3065 i = PyInt_AsLong(arg);
3066 if (i == -1 && PyErr_Occurred())
3067 return -1;
3068 if (i < 0) {
3069 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
3070 if (sq && sq->sq_length) {
3071 int n = (*sq->sq_length)(self);
3072 if (n < 0)
3073 return -1;
3074 i += n;
3075 }
3076 }
3077 return i;
3078}
3079
3080static PyObject *
3081wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
3082{
3083 intargfunc func = (intargfunc)wrapped;
3084 PyObject *arg;
3085 int i;
3086
Guido van Rossumf4593e02001-10-03 12:09:30 +00003087 if (PyTuple_GET_SIZE(args) == 1) {
3088 arg = PyTuple_GET_ITEM(args, 0);
3089 i = getindex(self, arg);
3090 if (i == -1 && PyErr_Occurred())
3091 return NULL;
3092 return (*func)(self, i);
3093 }
3094 PyArg_ParseTuple(args, "O", &arg);
3095 assert(PyErr_Occurred());
3096 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003097}
3098
Tim Peters6d6c1a32001-08-02 04:15:00 +00003099static PyObject *
3100wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
3101{
3102 intintargfunc func = (intintargfunc)wrapped;
3103 int i, j;
3104
3105 if (!PyArg_ParseTuple(args, "ii", &i, &j))
3106 return NULL;
3107 return (*func)(self, i, j);
3108}
3109
Tim Peters6d6c1a32001-08-02 04:15:00 +00003110static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003111wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003112{
3113 intobjargproc func = (intobjargproc)wrapped;
3114 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003115 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003116
Guido van Rossum5d815f32001-08-17 21:57:47 +00003117 if (!PyArg_ParseTuple(args, "OO", &arg, &value))
3118 return NULL;
3119 i = getindex(self, arg);
3120 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00003121 return NULL;
3122 res = (*func)(self, i, value);
3123 if (res == -1 && PyErr_Occurred())
3124 return NULL;
3125 Py_INCREF(Py_None);
3126 return Py_None;
3127}
3128
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003129static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003130wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003131{
3132 intobjargproc func = (intobjargproc)wrapped;
3133 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003134 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003135
Guido van Rossum5d815f32001-08-17 21:57:47 +00003136 if (!PyArg_ParseTuple(args, "O", &arg))
3137 return NULL;
3138 i = getindex(self, arg);
3139 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003140 return NULL;
3141 res = (*func)(self, i, NULL);
3142 if (res == -1 && PyErr_Occurred())
3143 return NULL;
3144 Py_INCREF(Py_None);
3145 return Py_None;
3146}
3147
Tim Peters6d6c1a32001-08-02 04:15:00 +00003148static PyObject *
3149wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
3150{
3151 intintobjargproc func = (intintobjargproc)wrapped;
3152 int i, j, res;
3153 PyObject *value;
3154
3155 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
3156 return NULL;
3157 res = (*func)(self, i, j, value);
3158 if (res == -1 && PyErr_Occurred())
3159 return NULL;
3160 Py_INCREF(Py_None);
3161 return Py_None;
3162}
3163
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003164static PyObject *
3165wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
3166{
3167 intintobjargproc func = (intintobjargproc)wrapped;
3168 int i, j, res;
3169
3170 if (!PyArg_ParseTuple(args, "ii", &i, &j))
3171 return NULL;
3172 res = (*func)(self, i, j, NULL);
3173 if (res == -1 && PyErr_Occurred())
3174 return NULL;
3175 Py_INCREF(Py_None);
3176 return Py_None;
3177}
3178
Tim Peters6d6c1a32001-08-02 04:15:00 +00003179/* XXX objobjproc is a misnomer; should be objargpred */
3180static PyObject *
3181wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
3182{
3183 objobjproc func = (objobjproc)wrapped;
3184 int res;
3185 PyObject *value;
3186
3187 if (!PyArg_ParseTuple(args, "O", &value))
3188 return NULL;
3189 res = (*func)(self, value);
3190 if (res == -1 && PyErr_Occurred())
3191 return NULL;
3192 return PyInt_FromLong((long)res);
3193}
3194
Tim Peters6d6c1a32001-08-02 04:15:00 +00003195static PyObject *
3196wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
3197{
3198 objobjargproc func = (objobjargproc)wrapped;
3199 int res;
3200 PyObject *key, *value;
3201
3202 if (!PyArg_ParseTuple(args, "OO", &key, &value))
3203 return NULL;
3204 res = (*func)(self, key, value);
3205 if (res == -1 && PyErr_Occurred())
3206 return NULL;
3207 Py_INCREF(Py_None);
3208 return Py_None;
3209}
3210
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003211static PyObject *
3212wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
3213{
3214 objobjargproc func = (objobjargproc)wrapped;
3215 int res;
3216 PyObject *key;
3217
3218 if (!PyArg_ParseTuple(args, "O", &key))
3219 return NULL;
3220 res = (*func)(self, key, NULL);
3221 if (res == -1 && PyErr_Occurred())
3222 return NULL;
3223 Py_INCREF(Py_None);
3224 return Py_None;
3225}
3226
Tim Peters6d6c1a32001-08-02 04:15:00 +00003227static PyObject *
3228wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
3229{
3230 cmpfunc func = (cmpfunc)wrapped;
3231 int res;
3232 PyObject *other;
3233
3234 if (!PyArg_ParseTuple(args, "O", &other))
3235 return NULL;
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00003236 if (other->ob_type->tp_compare != func &&
3237 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00003238 PyErr_Format(
3239 PyExc_TypeError,
3240 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
3241 self->ob_type->tp_name,
3242 self->ob_type->tp_name,
3243 other->ob_type->tp_name);
3244 return NULL;
3245 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003246 res = (*func)(self, other);
3247 if (PyErr_Occurred())
3248 return NULL;
3249 return PyInt_FromLong((long)res);
3250}
3251
Tim Peters6d6c1a32001-08-02 04:15:00 +00003252static PyObject *
3253wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
3254{
3255 setattrofunc func = (setattrofunc)wrapped;
3256 int res;
3257 PyObject *name, *value;
3258
3259 if (!PyArg_ParseTuple(args, "OO", &name, &value))
3260 return NULL;
3261 res = (*func)(self, name, value);
3262 if (res < 0)
3263 return NULL;
3264 Py_INCREF(Py_None);
3265 return Py_None;
3266}
3267
3268static PyObject *
3269wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
3270{
3271 setattrofunc func = (setattrofunc)wrapped;
3272 int res;
3273 PyObject *name;
3274
3275 if (!PyArg_ParseTuple(args, "O", &name))
3276 return NULL;
3277 res = (*func)(self, name, NULL);
3278 if (res < 0)
3279 return NULL;
3280 Py_INCREF(Py_None);
3281 return Py_None;
3282}
3283
Tim Peters6d6c1a32001-08-02 04:15:00 +00003284static PyObject *
3285wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
3286{
3287 hashfunc func = (hashfunc)wrapped;
3288 long res;
3289
3290 if (!PyArg_ParseTuple(args, ""))
3291 return NULL;
3292 res = (*func)(self);
3293 if (res == -1 && PyErr_Occurred())
3294 return NULL;
3295 return PyInt_FromLong(res);
3296}
3297
Tim Peters6d6c1a32001-08-02 04:15:00 +00003298static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00003299wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003300{
3301 ternaryfunc func = (ternaryfunc)wrapped;
3302
Guido van Rossumc8e56452001-10-22 00:43:43 +00003303 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003304}
3305
Tim Peters6d6c1a32001-08-02 04:15:00 +00003306static PyObject *
3307wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
3308{
3309 richcmpfunc func = (richcmpfunc)wrapped;
3310 PyObject *other;
3311
3312 if (!PyArg_ParseTuple(args, "O", &other))
3313 return NULL;
3314 return (*func)(self, other, op);
3315}
3316
3317#undef RICHCMP_WRAPPER
3318#define RICHCMP_WRAPPER(NAME, OP) \
3319static PyObject * \
3320richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
3321{ \
3322 return wrap_richcmpfunc(self, args, wrapped, OP); \
3323}
3324
Jack Jansen8e938b42001-08-08 15:29:49 +00003325RICHCMP_WRAPPER(lt, Py_LT)
3326RICHCMP_WRAPPER(le, Py_LE)
3327RICHCMP_WRAPPER(eq, Py_EQ)
3328RICHCMP_WRAPPER(ne, Py_NE)
3329RICHCMP_WRAPPER(gt, Py_GT)
3330RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003331
Tim Peters6d6c1a32001-08-02 04:15:00 +00003332static PyObject *
3333wrap_next(PyObject *self, PyObject *args, void *wrapped)
3334{
3335 unaryfunc func = (unaryfunc)wrapped;
3336 PyObject *res;
3337
3338 if (!PyArg_ParseTuple(args, ""))
3339 return NULL;
3340 res = (*func)(self);
3341 if (res == NULL && !PyErr_Occurred())
3342 PyErr_SetNone(PyExc_StopIteration);
3343 return res;
3344}
3345
Tim Peters6d6c1a32001-08-02 04:15:00 +00003346static PyObject *
3347wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
3348{
3349 descrgetfunc func = (descrgetfunc)wrapped;
3350 PyObject *obj;
3351 PyObject *type = NULL;
3352
3353 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
3354 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003355 return (*func)(self, obj, type);
3356}
3357
Tim Peters6d6c1a32001-08-02 04:15:00 +00003358static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003359wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003360{
3361 descrsetfunc func = (descrsetfunc)wrapped;
3362 PyObject *obj, *value;
3363 int ret;
3364
3365 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
3366 return NULL;
3367 ret = (*func)(self, obj, value);
3368 if (ret < 0)
3369 return NULL;
3370 Py_INCREF(Py_None);
3371 return Py_None;
3372}
Guido van Rossum22b13872002-08-06 21:41:44 +00003373
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00003374static PyObject *
3375wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
3376{
3377 descrsetfunc func = (descrsetfunc)wrapped;
3378 PyObject *obj;
3379 int ret;
3380
3381 if (!PyArg_ParseTuple(args, "O", &obj))
3382 return NULL;
3383 ret = (*func)(self, obj, NULL);
3384 if (ret < 0)
3385 return NULL;
3386 Py_INCREF(Py_None);
3387 return Py_None;
3388}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003389
Tim Peters6d6c1a32001-08-02 04:15:00 +00003390static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00003391wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003392{
3393 initproc func = (initproc)wrapped;
3394
Guido van Rossumc8e56452001-10-22 00:43:43 +00003395 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003396 return NULL;
3397 Py_INCREF(Py_None);
3398 return Py_None;
3399}
3400
Tim Peters6d6c1a32001-08-02 04:15:00 +00003401static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003402tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003403{
Barry Warsaw60f01882001-08-22 19:24:42 +00003404 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003405 PyObject *arg0, *res;
3406
3407 if (self == NULL || !PyType_Check(self))
3408 Py_FatalError("__new__() called with non-type 'self'");
3409 type = (PyTypeObject *)self;
3410 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003411 PyErr_Format(PyExc_TypeError,
3412 "%s.__new__(): not enough arguments",
3413 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003414 return NULL;
3415 }
3416 arg0 = PyTuple_GET_ITEM(args, 0);
3417 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003418 PyErr_Format(PyExc_TypeError,
3419 "%s.__new__(X): X is not a type object (%s)",
3420 type->tp_name,
3421 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003422 return NULL;
3423 }
3424 subtype = (PyTypeObject *)arg0;
3425 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003426 PyErr_Format(PyExc_TypeError,
3427 "%s.__new__(%s): %s is not a subtype of %s",
3428 type->tp_name,
3429 subtype->tp_name,
3430 subtype->tp_name,
3431 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003432 return NULL;
3433 }
Barry Warsaw60f01882001-08-22 19:24:42 +00003434
3435 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00003436 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00003437 most derived base that's not a heap type is this type. */
3438 staticbase = subtype;
3439 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
3440 staticbase = staticbase->tp_base;
Guido van Rossuma8c60f42001-09-14 19:43:36 +00003441 if (staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003442 PyErr_Format(PyExc_TypeError,
3443 "%s.__new__(%s) is not safe, use %s.__new__()",
3444 type->tp_name,
3445 subtype->tp_name,
3446 staticbase == NULL ? "?" : staticbase->tp_name);
3447 return NULL;
3448 }
3449
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003450 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
3451 if (args == NULL)
3452 return NULL;
3453 res = type->tp_new(subtype, args, kwds);
3454 Py_DECREF(args);
3455 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003456}
3457
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003458static struct PyMethodDef tp_new_methoddef[] = {
3459 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00003460 PyDoc_STR("T.__new__(S, ...) -> "
3461 "a new object with type S, a subtype of T")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00003462 {0}
3463};
3464
3465static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003466add_tp_new_wrapper(PyTypeObject *type)
3467{
Guido van Rossumf040ede2001-08-07 16:40:56 +00003468 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003469
Guido van Rossum687ae002001-10-15 22:03:32 +00003470 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00003471 return 0;
3472 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003473 if (func == NULL)
3474 return -1;
Guido van Rossum687ae002001-10-15 22:03:32 +00003475 return PyDict_SetItemString(type->tp_dict, "__new__", func);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003476}
3477
Guido van Rossumf040ede2001-08-07 16:40:56 +00003478/* Slot wrappers that call the corresponding __foo__ slot. See comments
3479 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003480
Guido van Rossumdc91b992001-08-08 22:26:22 +00003481#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003482static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003483FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003484{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00003485 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003486 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003487}
3488
Guido van Rossumdc91b992001-08-08 22:26:22 +00003489#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003490static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003491FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003492{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003493 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003494 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003495}
3496
Guido van Rossumdc91b992001-08-08 22:26:22 +00003497
3498#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003499static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003500FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003501{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003502 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00003503 int do_other = self->ob_type != other->ob_type && \
3504 other->ob_type->tp_as_number != NULL && \
3505 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003506 if (self->ob_type->tp_as_number != NULL && \
3507 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
3508 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00003509 if (do_other && \
3510 PyType_IsSubtype(other->ob_type, self->ob_type)) { \
3511 r = call_maybe( \
3512 other, ROPSTR, &rcache_str, "(O)", self); \
3513 if (r != Py_NotImplemented) \
3514 return r; \
3515 Py_DECREF(r); \
3516 do_other = 0; \
3517 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00003518 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00003519 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003520 if (r != Py_NotImplemented || \
3521 other->ob_type == self->ob_type) \
3522 return r; \
3523 Py_DECREF(r); \
3524 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00003525 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00003526 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00003527 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003528 } \
3529 Py_INCREF(Py_NotImplemented); \
3530 return Py_NotImplemented; \
3531}
3532
3533#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
3534 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
3535
3536#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
3537static PyObject * \
3538FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
3539{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003540 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003541 return call_method(self, OPSTR, &cache_str, \
3542 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003543}
3544
3545static int
3546slot_sq_length(PyObject *self)
3547{
Guido van Rossum2730b132001-08-28 18:22:14 +00003548 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00003549 PyObject *res = call_method(self, "__len__", &len_str, "()");
Guido van Rossum26111622001-10-01 16:42:49 +00003550 int len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003551
3552 if (res == NULL)
3553 return -1;
Guido van Rossum26111622001-10-01 16:42:49 +00003554 len = (int)PyInt_AsLong(res);
3555 Py_DECREF(res);
Jeremy Hylton73a088e2002-07-25 16:43:29 +00003556 if (len == -1 && PyErr_Occurred())
3557 return -1;
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00003558 if (len < 0) {
Guido van Rossum22b13872002-08-06 21:41:44 +00003559 PyErr_SetString(PyExc_ValueError,
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00003560 "__len__() should return >= 0");
3561 return -1;
3562 }
Guido van Rossum26111622001-10-01 16:42:49 +00003563 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003564}
3565
Guido van Rossumdc91b992001-08-08 22:26:22 +00003566SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
3567SLOT1(slot_sq_repeat, "__mul__", int, "i")
Guido van Rossumf4593e02001-10-03 12:09:30 +00003568
3569/* Super-optimized version of slot_sq_item.
3570 Other slots could do the same... */
3571static PyObject *
3572slot_sq_item(PyObject *self, int i)
3573{
3574 static PyObject *getitem_str;
3575 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
3576 descrgetfunc f;
3577
3578 if (getitem_str == NULL) {
3579 getitem_str = PyString_InternFromString("__getitem__");
3580 if (getitem_str == NULL)
3581 return NULL;
3582 }
3583 func = _PyType_Lookup(self->ob_type, getitem_str);
3584 if (func != NULL) {
Guido van Rossumf4593e02001-10-03 12:09:30 +00003585 if ((f = func->ob_type->tp_descr_get) == NULL)
3586 Py_INCREF(func);
Neal Norwitz673cd822002-10-18 16:33:13 +00003587 else {
Guido van Rossumf4593e02001-10-03 12:09:30 +00003588 func = f(func, self, (PyObject *)(self->ob_type));
Neal Norwitz673cd822002-10-18 16:33:13 +00003589 if (func == NULL) {
3590 return NULL;
3591 }
3592 }
Guido van Rossumf4593e02001-10-03 12:09:30 +00003593 ival = PyInt_FromLong(i);
3594 if (ival != NULL) {
3595 args = PyTuple_New(1);
3596 if (args != NULL) {
3597 PyTuple_SET_ITEM(args, 0, ival);
3598 retval = PyObject_Call(func, args, NULL);
3599 Py_XDECREF(args);
3600 Py_XDECREF(func);
3601 return retval;
3602 }
3603 }
3604 }
3605 else {
3606 PyErr_SetObject(PyExc_AttributeError, getitem_str);
3607 }
3608 Py_XDECREF(args);
3609 Py_XDECREF(ival);
3610 Py_XDECREF(func);
3611 return NULL;
3612}
3613
Guido van Rossumdc91b992001-08-08 22:26:22 +00003614SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003615
3616static int
3617slot_sq_ass_item(PyObject *self, int index, PyObject *value)
3618{
3619 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003620 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003621
3622 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003623 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003624 "(i)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003625 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003626 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003627 "(iO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003628 if (res == NULL)
3629 return -1;
3630 Py_DECREF(res);
3631 return 0;
3632}
3633
3634static int
3635slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
3636{
3637 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003638 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003639
3640 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003641 res = call_method(self, "__delslice__", &delslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003642 "(ii)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003643 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003644 res = call_method(self, "__setslice__", &setslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003645 "(iiO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003646 if (res == NULL)
3647 return -1;
3648 Py_DECREF(res);
3649 return 0;
3650}
3651
3652static int
3653slot_sq_contains(PyObject *self, PyObject *value)
3654{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003655 PyObject *func, *res, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00003656 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003657
Guido van Rossum55f20992001-10-01 17:18:22 +00003658 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003659
3660 if (func != NULL) {
3661 args = Py_BuildValue("(O)", value);
3662 if (args == NULL)
3663 res = NULL;
3664 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003665 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003666 Py_DECREF(args);
3667 }
3668 Py_DECREF(func);
3669 if (res == NULL)
3670 return -1;
3671 return PyObject_IsTrue(res);
3672 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003673 else if (PyErr_Occurred())
3674 return -1;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003675 else {
Tim Peters16a77ad2001-09-08 04:00:12 +00003676 return _PySequence_IterSearch(self, value,
3677 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003678 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003679}
3680
Guido van Rossumdc91b992001-08-08 22:26:22 +00003681SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
3682SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003683
3684#define slot_mp_length slot_sq_length
3685
Guido van Rossumdc91b992001-08-08 22:26:22 +00003686SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003687
3688static int
3689slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
3690{
3691 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003692 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003693
3694 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003695 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003696 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003697 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003698 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003699 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003700 if (res == NULL)
3701 return -1;
3702 Py_DECREF(res);
3703 return 0;
3704}
3705
Guido van Rossumdc91b992001-08-08 22:26:22 +00003706SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
3707SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
3708SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
3709SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
3710SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
3711SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
3712
Jeremy Hylton938ace62002-07-17 16:30:39 +00003713static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003714
3715SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
3716 nb_power, "__pow__", "__rpow__")
3717
3718static PyObject *
3719slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
3720{
Guido van Rossum2730b132001-08-28 18:22:14 +00003721 static PyObject *pow_str;
3722
Guido van Rossumdc91b992001-08-08 22:26:22 +00003723 if (modulus == Py_None)
3724 return slot_nb_power_binary(self, other);
Guido van Rossum23094982002-06-10 14:30:43 +00003725 /* Three-arg power doesn't use __rpow__. But ternary_op
3726 can call this when the second argument's type uses
3727 slot_nb_power, so check before calling self.__pow__. */
3728 if (self->ob_type->tp_as_number != NULL &&
3729 self->ob_type->tp_as_number->nb_power == slot_nb_power) {
3730 return call_method(self, "__pow__", &pow_str,
3731 "(OO)", other, modulus);
3732 }
3733 Py_INCREF(Py_NotImplemented);
3734 return Py_NotImplemented;
Guido van Rossumdc91b992001-08-08 22:26:22 +00003735}
3736
3737SLOT0(slot_nb_negative, "__neg__")
3738SLOT0(slot_nb_positive, "__pos__")
3739SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003740
3741static int
3742slot_nb_nonzero(PyObject *self)
3743{
Tim Petersea7f75d2002-12-07 21:39:16 +00003744 PyObject *func, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00003745 static PyObject *nonzero_str, *len_str;
Tim Petersea7f75d2002-12-07 21:39:16 +00003746 int result = -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003747
Guido van Rossum55f20992001-10-01 17:18:22 +00003748 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003749 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00003750 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00003751 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00003752 func = lookup_maybe(self, "__len__", &len_str);
Tim Petersea7f75d2002-12-07 21:39:16 +00003753 if (func == NULL)
3754 return PyErr_Occurred() ? -1 : 1;
3755 }
3756 args = PyTuple_New(0);
3757 if (args != NULL) {
3758 PyObject *temp = PyObject_Call(func, args, NULL);
3759 Py_DECREF(args);
3760 if (temp != NULL) {
3761 result = PyObject_IsTrue(temp);
3762 Py_DECREF(temp);
Guido van Rossum55f20992001-10-01 17:18:22 +00003763 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00003764 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003765 Py_DECREF(func);
Tim Petersea7f75d2002-12-07 21:39:16 +00003766 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003767}
3768
Guido van Rossumdc91b992001-08-08 22:26:22 +00003769SLOT0(slot_nb_invert, "__invert__")
3770SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
3771SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
3772SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
3773SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
3774SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003775
3776static int
3777slot_nb_coerce(PyObject **a, PyObject **b)
3778{
3779 static PyObject *coerce_str;
3780 PyObject *self = *a, *other = *b;
3781
3782 if (self->ob_type->tp_as_number != NULL &&
3783 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3784 PyObject *r;
3785 r = call_maybe(
3786 self, "__coerce__", &coerce_str, "(O)", other);
3787 if (r == NULL)
3788 return -1;
3789 if (r == Py_NotImplemented) {
3790 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003791 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003792 else {
3793 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3794 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003795 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00003796 Py_DECREF(r);
3797 return -1;
3798 }
3799 *a = PyTuple_GET_ITEM(r, 0);
3800 Py_INCREF(*a);
3801 *b = PyTuple_GET_ITEM(r, 1);
3802 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003803 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00003804 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003805 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003806 }
3807 if (other->ob_type->tp_as_number != NULL &&
3808 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3809 PyObject *r;
3810 r = call_maybe(
3811 other, "__coerce__", &coerce_str, "(O)", self);
3812 if (r == NULL)
3813 return -1;
3814 if (r == Py_NotImplemented) {
3815 Py_DECREF(r);
3816 return 1;
3817 }
3818 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3819 PyErr_SetString(PyExc_TypeError,
3820 "__coerce__ didn't return a 2-tuple");
3821 Py_DECREF(r);
3822 return -1;
3823 }
3824 *a = PyTuple_GET_ITEM(r, 1);
3825 Py_INCREF(*a);
3826 *b = PyTuple_GET_ITEM(r, 0);
3827 Py_INCREF(*b);
3828 Py_DECREF(r);
3829 return 0;
3830 }
3831 return 1;
3832}
3833
Guido van Rossumdc91b992001-08-08 22:26:22 +00003834SLOT0(slot_nb_int, "__int__")
3835SLOT0(slot_nb_long, "__long__")
3836SLOT0(slot_nb_float, "__float__")
3837SLOT0(slot_nb_oct, "__oct__")
3838SLOT0(slot_nb_hex, "__hex__")
3839SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
3840SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
3841SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
3842SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
3843SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003844SLOT1(slot_nb_inplace_power, "__ipow__", PyObject *, "O")
Guido van Rossumdc91b992001-08-08 22:26:22 +00003845SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
3846SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
3847SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
3848SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
3849SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
3850SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
3851 "__floordiv__", "__rfloordiv__")
3852SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
3853SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
3854SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003855
3856static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00003857half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003858{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003859 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003860 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003861 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003862
Guido van Rossum60718732001-08-28 17:47:51 +00003863 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003864 if (func == NULL) {
3865 PyErr_Clear();
3866 }
3867 else {
3868 args = Py_BuildValue("(O)", other);
3869 if (args == NULL)
3870 res = NULL;
3871 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003872 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003873 Py_DECREF(args);
3874 }
Raymond Hettingerab5dae32002-06-24 13:08:16 +00003875 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003876 if (res != Py_NotImplemented) {
3877 if (res == NULL)
3878 return -2;
3879 c = PyInt_AsLong(res);
3880 Py_DECREF(res);
3881 if (c == -1 && PyErr_Occurred())
3882 return -2;
3883 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
3884 }
3885 Py_DECREF(res);
3886 }
3887 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003888}
3889
Guido van Rossumab3b0342001-09-18 20:38:53 +00003890/* This slot is published for the benefit of try_3way_compare in object.c */
3891int
3892_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00003893{
3894 int c;
3895
Guido van Rossumab3b0342001-09-18 20:38:53 +00003896 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003897 c = half_compare(self, other);
3898 if (c <= 1)
3899 return c;
3900 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00003901 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003902 c = half_compare(other, self);
3903 if (c < -1)
3904 return -2;
3905 if (c <= 1)
3906 return -c;
3907 }
3908 return (void *)self < (void *)other ? -1 :
3909 (void *)self > (void *)other ? 1 : 0;
3910}
3911
3912static PyObject *
3913slot_tp_repr(PyObject *self)
3914{
3915 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003916 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003917
Guido van Rossum60718732001-08-28 17:47:51 +00003918 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003919 if (func != NULL) {
3920 res = PyEval_CallObject(func, NULL);
3921 Py_DECREF(func);
3922 return res;
3923 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00003924 PyErr_Clear();
3925 return PyString_FromFormat("<%s object at %p>",
3926 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003927}
3928
3929static PyObject *
3930slot_tp_str(PyObject *self)
3931{
3932 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003933 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003934
Guido van Rossum60718732001-08-28 17:47:51 +00003935 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003936 if (func != NULL) {
3937 res = PyEval_CallObject(func, NULL);
3938 Py_DECREF(func);
3939 return res;
3940 }
3941 else {
3942 PyErr_Clear();
3943 return slot_tp_repr(self);
3944 }
3945}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003946
3947static long
3948slot_tp_hash(PyObject *self)
3949{
Tim Peters61ce0a92002-12-06 23:38:02 +00003950 PyObject *func;
Guido van Rossum60718732001-08-28 17:47:51 +00003951 static PyObject *hash_str, *eq_str, *cmp_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003952 long h;
3953
Guido van Rossum60718732001-08-28 17:47:51 +00003954 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003955
3956 if (func != NULL) {
Tim Peters61ce0a92002-12-06 23:38:02 +00003957 PyObject *res = PyEval_CallObject(func, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003958 Py_DECREF(func);
3959 if (res == NULL)
3960 return -1;
3961 h = PyInt_AsLong(res);
Tim Peters61ce0a92002-12-06 23:38:02 +00003962 Py_DECREF(res);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003963 }
3964 else {
3965 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003966 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003967 if (func == NULL) {
3968 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00003969 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003970 }
3971 if (func != NULL) {
3972 Py_DECREF(func);
3973 PyErr_SetString(PyExc_TypeError, "unhashable type");
3974 return -1;
3975 }
3976 PyErr_Clear();
3977 h = _Py_HashPointer((void *)self);
3978 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003979 if (h == -1 && !PyErr_Occurred())
3980 h = -2;
3981 return h;
3982}
3983
3984static PyObject *
3985slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
3986{
Guido van Rossum60718732001-08-28 17:47:51 +00003987 static PyObject *call_str;
3988 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003989 PyObject *res;
3990
3991 if (meth == NULL)
3992 return NULL;
3993 res = PyObject_Call(meth, args, kwds);
3994 Py_DECREF(meth);
3995 return res;
3996}
3997
Guido van Rossum14a6f832001-10-17 13:59:09 +00003998/* There are two slot dispatch functions for tp_getattro.
3999
4000 - slot_tp_getattro() is used when __getattribute__ is overridden
4001 but no __getattr__ hook is present;
4002
4003 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
4004
Guido van Rossumc334df52002-04-04 23:44:47 +00004005 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
4006 detects the absence of __getattr__ and then installs the simpler slot if
4007 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00004008
Tim Peters6d6c1a32001-08-02 04:15:00 +00004009static PyObject *
4010slot_tp_getattro(PyObject *self, PyObject *name)
4011{
Guido van Rossum14a6f832001-10-17 13:59:09 +00004012 static PyObject *getattribute_str = NULL;
4013 return call_method(self, "__getattribute__", &getattribute_str,
4014 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004015}
4016
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004017static PyObject *
4018slot_tp_getattr_hook(PyObject *self, PyObject *name)
4019{
4020 PyTypeObject *tp = self->ob_type;
4021 PyObject *getattr, *getattribute, *res;
4022 static PyObject *getattribute_str = NULL;
4023 static PyObject *getattr_str = NULL;
4024
4025 if (getattr_str == NULL) {
4026 getattr_str = PyString_InternFromString("__getattr__");
4027 if (getattr_str == NULL)
4028 return NULL;
4029 }
4030 if (getattribute_str == NULL) {
4031 getattribute_str =
4032 PyString_InternFromString("__getattribute__");
4033 if (getattribute_str == NULL)
4034 return NULL;
4035 }
4036 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004037 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004038 /* No __getattr__ hook: use a simpler dispatcher */
4039 tp->tp_getattro = slot_tp_getattro;
4040 return slot_tp_getattro(self, name);
4041 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004042 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004043 if (getattribute == NULL ||
4044 (getattribute->ob_type == &PyWrapperDescr_Type &&
4045 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
4046 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004047 res = PyObject_GenericGetAttr(self, name);
4048 else
4049 res = PyObject_CallFunction(getattribute, "OO", self, name);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004050 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004051 PyErr_Clear();
4052 res = PyObject_CallFunction(getattr, "OO", self, name);
4053 }
4054 return res;
4055}
4056
Tim Peters6d6c1a32001-08-02 04:15:00 +00004057static int
4058slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
4059{
4060 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004061 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004062
4063 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004064 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004065 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004066 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004067 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004068 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004069 if (res == NULL)
4070 return -1;
4071 Py_DECREF(res);
4072 return 0;
4073}
4074
4075/* Map rich comparison operators to their __xx__ namesakes */
4076static char *name_op[] = {
4077 "__lt__",
4078 "__le__",
4079 "__eq__",
4080 "__ne__",
4081 "__gt__",
4082 "__ge__",
4083};
4084
4085static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00004086half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004087{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004088 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004089 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00004090
Guido van Rossum60718732001-08-28 17:47:51 +00004091 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004092 if (func == NULL) {
4093 PyErr_Clear();
4094 Py_INCREF(Py_NotImplemented);
4095 return Py_NotImplemented;
4096 }
4097 args = Py_BuildValue("(O)", other);
4098 if (args == NULL)
4099 res = NULL;
4100 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004101 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004102 Py_DECREF(args);
4103 }
4104 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004105 return res;
4106}
4107
Guido van Rossumb8f63662001-08-15 23:57:02 +00004108/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
4109static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
4110
4111static PyObject *
4112slot_tp_richcompare(PyObject *self, PyObject *other, int op)
4113{
4114 PyObject *res;
4115
4116 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
4117 res = half_richcompare(self, other, op);
4118 if (res != Py_NotImplemented)
4119 return res;
4120 Py_DECREF(res);
4121 }
4122 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
4123 res = half_richcompare(other, self, swapped_op[op]);
4124 if (res != Py_NotImplemented) {
4125 return res;
4126 }
4127 Py_DECREF(res);
4128 }
4129 Py_INCREF(Py_NotImplemented);
4130 return Py_NotImplemented;
4131}
4132
4133static PyObject *
4134slot_tp_iter(PyObject *self)
4135{
4136 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004137 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004138
Guido van Rossum60718732001-08-28 17:47:51 +00004139 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004140 if (func != NULL) {
Guido van Rossum84b2bed2002-08-16 17:01:09 +00004141 PyObject *args;
4142 args = res = PyTuple_New(0);
4143 if (args != NULL) {
4144 res = PyObject_Call(func, args, NULL);
4145 Py_DECREF(args);
4146 }
4147 Py_DECREF(func);
4148 return res;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004149 }
4150 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004151 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004152 if (func == NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00004153 PyErr_SetString(PyExc_TypeError,
4154 "iteration over non-sequence");
Guido van Rossumb8f63662001-08-15 23:57:02 +00004155 return NULL;
4156 }
4157 Py_DECREF(func);
4158 return PySeqIter_New(self);
4159}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004160
4161static PyObject *
4162slot_tp_iternext(PyObject *self)
4163{
Guido van Rossum2730b132001-08-28 18:22:14 +00004164 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00004165 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004166}
4167
Guido van Rossum1a493502001-08-17 16:47:50 +00004168static PyObject *
4169slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4170{
4171 PyTypeObject *tp = self->ob_type;
4172 PyObject *get;
4173 static PyObject *get_str = NULL;
4174
4175 if (get_str == NULL) {
4176 get_str = PyString_InternFromString("__get__");
4177 if (get_str == NULL)
4178 return NULL;
4179 }
4180 get = _PyType_Lookup(tp, get_str);
4181 if (get == NULL) {
4182 /* Avoid further slowdowns */
4183 if (tp->tp_descr_get == slot_tp_descr_get)
4184 tp->tp_descr_get = NULL;
4185 Py_INCREF(self);
4186 return self;
4187 }
Guido van Rossum2c252392001-08-24 10:13:31 +00004188 if (obj == NULL)
4189 obj = Py_None;
4190 if (type == NULL)
4191 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00004192 return PyObject_CallFunction(get, "OOO", self, obj, type);
4193}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004194
4195static int
4196slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
4197{
Guido van Rossum2c252392001-08-24 10:13:31 +00004198 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004199 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00004200
4201 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00004202 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004203 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00004204 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004205 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004206 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004207 if (res == NULL)
4208 return -1;
4209 Py_DECREF(res);
4210 return 0;
4211}
4212
4213static int
4214slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
4215{
Guido van Rossum60718732001-08-28 17:47:51 +00004216 static PyObject *init_str;
4217 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004218 PyObject *res;
4219
4220 if (meth == NULL)
4221 return -1;
4222 res = PyObject_Call(meth, args, kwds);
4223 Py_DECREF(meth);
4224 if (res == NULL)
4225 return -1;
4226 Py_DECREF(res);
4227 return 0;
4228}
4229
4230static PyObject *
4231slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4232{
Guido van Rossum7bed2132002-08-08 21:57:53 +00004233 static PyObject *new_str;
4234 PyObject *func;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004235 PyObject *newargs, *x;
4236 int i, n;
4237
Guido van Rossum7bed2132002-08-08 21:57:53 +00004238 if (new_str == NULL) {
4239 new_str = PyString_InternFromString("__new__");
4240 if (new_str == NULL)
4241 return NULL;
4242 }
4243 func = PyObject_GetAttr((PyObject *)type, new_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004244 if (func == NULL)
4245 return NULL;
4246 assert(PyTuple_Check(args));
4247 n = PyTuple_GET_SIZE(args);
4248 newargs = PyTuple_New(n+1);
4249 if (newargs == NULL)
4250 return NULL;
4251 Py_INCREF(type);
4252 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
4253 for (i = 0; i < n; i++) {
4254 x = PyTuple_GET_ITEM(args, i);
4255 Py_INCREF(x);
4256 PyTuple_SET_ITEM(newargs, i+1, x);
4257 }
4258 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00004259 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004260 Py_DECREF(func);
4261 return x;
4262}
4263
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004264static void
4265slot_tp_del(PyObject *self)
4266{
4267 static PyObject *del_str = NULL;
4268 PyObject *del, *res;
4269 PyObject *error_type, *error_value, *error_traceback;
4270
4271 /* Temporarily resurrect the object. */
4272 assert(self->ob_refcnt == 0);
4273 self->ob_refcnt = 1;
4274
4275 /* Save the current exception, if any. */
4276 PyErr_Fetch(&error_type, &error_value, &error_traceback);
4277
4278 /* Execute __del__ method, if any. */
4279 del = lookup_maybe(self, "__del__", &del_str);
4280 if (del != NULL) {
4281 res = PyEval_CallObject(del, NULL);
4282 if (res == NULL)
4283 PyErr_WriteUnraisable(del);
4284 else
4285 Py_DECREF(res);
4286 Py_DECREF(del);
4287 }
4288
4289 /* Restore the saved exception. */
4290 PyErr_Restore(error_type, error_value, error_traceback);
4291
4292 /* Undo the temporary resurrection; can't use DECREF here, it would
4293 * cause a recursive call.
4294 */
4295 assert(self->ob_refcnt > 0);
4296 if (--self->ob_refcnt == 0)
4297 return; /* this is the normal path out */
4298
4299 /* __del__ resurrected it! Make it look like the original Py_DECREF
4300 * never happened.
4301 */
4302 {
4303 int refcnt = self->ob_refcnt;
4304 _Py_NewReference(self);
4305 self->ob_refcnt = refcnt;
4306 }
4307 assert(!PyType_IS_GC(self->ob_type) ||
4308 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
4309 /* If Py_REF_DEBUG, the original decref dropped _Py_RefTotal, but
4310 * _Py_NewReference bumped it again, so that's a wash.
4311 * If Py_TRACE_REFS, _Py_NewReference re-added self to the object
4312 * chain, so no more to do there either.
4313 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
4314 * _Py_NewReference bumped tp_allocs: both of those need to be
4315 * undone.
4316 */
4317#ifdef COUNT_ALLOCS
4318 --self->ob_type->tp_frees;
4319 --self->ob_type->tp_allocs;
4320#endif
4321}
4322
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004323
4324/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
4325 functions. The offsets here are relative to the 'etype' structure, which
4326 incorporates the additional structures used for numbers, sequences and
4327 mappings. Note that multiple names may map to the same slot (e.g. __eq__,
4328 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00004329 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
4330 terminated with an all-zero entry. (This table is further initialized and
4331 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004332
Guido van Rossum6d204072001-10-21 00:44:31 +00004333typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004334
4335#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00004336#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004337#undef ETSLOT
4338#undef SQSLOT
4339#undef MPSLOT
4340#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00004341#undef UNSLOT
4342#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004343#undef BINSLOT
4344#undef RBINSLOT
4345
Guido van Rossum6d204072001-10-21 00:44:31 +00004346#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004347 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
4348 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00004349#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
4350 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004351 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00004352#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004353 {NAME, offsetof(etype, SLOT), (void *)(FUNCTION), WRAPPER, \
4354 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00004355#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4356 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
4357#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4358 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
4359#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4360 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
4361#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4362 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
4363 "x." NAME "() <==> " DOC)
4364#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4365 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
4366 "x." NAME "(y) <==> x" DOC "y")
4367#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
4368 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
4369 "x." NAME "(y) <==> x" DOC "y")
4370#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
4371 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
4372 "x." NAME "(y) <==> y" DOC "x")
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004373
4374static slotdef slotdefs[] = {
Guido van Rossum6d204072001-10-21 00:44:31 +00004375 SQSLOT("__len__", sq_length, slot_sq_length, wrap_inquiry,
4376 "x.__len__() <==> len(x)"),
4377 SQSLOT("__add__", sq_concat, slot_sq_concat, wrap_binaryfunc,
4378 "x.__add__(y) <==> x+y"),
4379 SQSLOT("__mul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
4380 "x.__mul__(n) <==> x*n"),
4381 SQSLOT("__rmul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
4382 "x.__rmul__(n) <==> n*x"),
4383 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
4384 "x.__getitem__(y) <==> x[y]"),
4385 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_intintargfunc,
4386 "x.__getslice__(i, j) <==> x[i:j]"),
4387 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
4388 "x.__setitem__(i, y) <==> x[i]=y"),
4389 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
4390 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004391 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Guido van Rossum6d204072001-10-21 00:44:31 +00004392 wrap_intintobjargproc,
4393 "x.__setslice__(i, j, y) <==> x[i:j]=y"),
4394 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
4395 "x.__delslice__(i, j) <==> del x[i:j]"),
4396 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
4397 "x.__contains__(y) <==> y in x"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004398 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat,
Guido van Rossum6d204072001-10-21 00:44:31 +00004399 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004400 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat,
Guido van Rossum6d204072001-10-21 00:44:31 +00004401 wrap_intargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004402
Guido van Rossum6d204072001-10-21 00:44:31 +00004403 MPSLOT("__len__", mp_length, slot_mp_length, wrap_inquiry,
4404 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00004405 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004406 wrap_binaryfunc,
4407 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004408 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004409 wrap_objobjargproc,
4410 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004411 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004412 wrap_delitem,
4413 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004414
Guido van Rossum6d204072001-10-21 00:44:31 +00004415 BINSLOT("__add__", nb_add, slot_nb_add,
4416 "+"),
4417 RBINSLOT("__radd__", nb_add, slot_nb_add,
4418 "+"),
4419 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
4420 "-"),
4421 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
4422 "-"),
4423 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
4424 "*"),
4425 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
4426 "*"),
4427 BINSLOT("__div__", nb_divide, slot_nb_divide,
4428 "/"),
4429 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
4430 "/"),
4431 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
4432 "%"),
4433 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
4434 "%"),
4435 BINSLOT("__divmod__", nb_divmod, slot_nb_divmod,
4436 "divmod(x, y)"),
4437 RBINSLOT("__rdivmod__", nb_divmod, slot_nb_divmod,
4438 "divmod(y, x)"),
4439 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
4440 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
4441 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
4442 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
4443 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
4444 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
4445 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
4446 "abs(x)"),
Guido van Rossumdfce3bf2002-03-10 14:11:16 +00004447 UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquiry,
Guido van Rossum6d204072001-10-21 00:44:31 +00004448 "x != 0"),
4449 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
4450 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
4451 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
4452 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
4453 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
4454 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
4455 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
4456 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
4457 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
4458 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
4459 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
4460 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
4461 "x.__coerce__(y) <==> coerce(x, y)"),
4462 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
4463 "int(x)"),
4464 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
4465 "long(x)"),
4466 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
4467 "float(x)"),
4468 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
4469 "oct(x)"),
4470 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
4471 "hex(x)"),
4472 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
4473 wrap_binaryfunc, "+"),
4474 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
4475 wrap_binaryfunc, "-"),
4476 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
4477 wrap_binaryfunc, "*"),
4478 IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
4479 wrap_binaryfunc, "/"),
4480 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
4481 wrap_binaryfunc, "%"),
4482 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
Guido van Rossum6e5680f2002-10-15 01:01:53 +00004483 wrap_binaryfunc, "**"),
Guido van Rossum6d204072001-10-21 00:44:31 +00004484 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
4485 wrap_binaryfunc, "<<"),
4486 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
4487 wrap_binaryfunc, ">>"),
4488 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
4489 wrap_binaryfunc, "&"),
4490 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
4491 wrap_binaryfunc, "^"),
4492 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
4493 wrap_binaryfunc, "|"),
4494 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
4495 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
4496 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
4497 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
4498 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
4499 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
4500 IBSLOT("__itruediv__", nb_inplace_true_divide,
4501 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004502
Guido van Rossum6d204072001-10-21 00:44:31 +00004503 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
4504 "x.__str__() <==> str(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00004505 TPSLOT("__str__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00004506 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
4507 "x.__repr__() <==> repr(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00004508 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00004509 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
4510 "x.__cmp__(y) <==> cmp(x,y)"),
4511 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
4512 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00004513 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
4514 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004515 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00004516 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
4517 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
4518 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
4519 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
4520 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
4521 "x.__setattr__('name', value) <==> x.name = value"),
4522 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
4523 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
4524 "x.__delattr__('name') <==> del x.name"),
4525 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
4526 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
4527 "x.__lt__(y) <==> x<y"),
4528 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
4529 "x.__le__(y) <==> x<=y"),
4530 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
4531 "x.__eq__(y) <==> x==y"),
4532 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
4533 "x.__ne__(y) <==> x!=y"),
4534 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
4535 "x.__gt__(y) <==> x>y"),
4536 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
4537 "x.__ge__(y) <==> x>=y"),
4538 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
4539 "x.__iter__() <==> iter(x)"),
4540 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
4541 "x.next() -> the next value, or raise StopIteration"),
4542 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
4543 "descr.__get__(obj[, type]) -> value"),
4544 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
4545 "descr.__set__(obj, value)"),
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004546 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
4547 wrap_descr_delete, "descr.__delete__(obj)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00004548 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00004549 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00004550 "see x.__class__.__doc__ for signature",
4551 PyWrapperFlag_KEYWORDS),
4552 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004553 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004554 {NULL}
4555};
4556
Guido van Rossumc334df52002-04-04 23:44:47 +00004557/* Given a type pointer and an offset gotten from a slotdef entry, return a
4558 pointer to the actual slot. This is not quite the same as simply adding
4559 the offset to the type pointer, since it takes care to indirect through the
4560 proper indirection pointer (as_buffer, etc.); it returns NULL if the
4561 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004562static void **
4563slotptr(PyTypeObject *type, int offset)
4564{
4565 char *ptr;
4566
Guido van Rossum09638c12002-06-13 19:17:46 +00004567 /* Note: this depends on the order of the members of etype! */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004568 assert(offset >= 0);
4569 assert(offset < offsetof(etype, as_buffer));
Guido van Rossum09638c12002-06-13 19:17:46 +00004570 if (offset >= offsetof(etype, as_sequence)) {
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004571 ptr = (void *)type->tp_as_sequence;
4572 offset -= offsetof(etype, as_sequence);
4573 }
Guido van Rossum09638c12002-06-13 19:17:46 +00004574 else if (offset >= offsetof(etype, as_mapping)) {
4575 ptr = (void *)type->tp_as_mapping;
4576 offset -= offsetof(etype, as_mapping);
4577 }
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004578 else if (offset >= offsetof(etype, as_number)) {
4579 ptr = (void *)type->tp_as_number;
4580 offset -= offsetof(etype, as_number);
4581 }
4582 else {
4583 ptr = (void *)type;
4584 }
4585 if (ptr != NULL)
4586 ptr += offset;
4587 return (void **)ptr;
4588}
Guido van Rossumf040ede2001-08-07 16:40:56 +00004589
Guido van Rossumc334df52002-04-04 23:44:47 +00004590/* Length of array of slotdef pointers used to store slots with the
4591 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
4592 the same __name__, for any __name__. Since that's a static property, it is
4593 appropriate to declare fixed-size arrays for this. */
4594#define MAX_EQUIV 10
4595
4596/* Return a slot pointer for a given name, but ONLY if the attribute has
4597 exactly one slot function. The name must be an interned string. */
4598static void **
4599resolve_slotdups(PyTypeObject *type, PyObject *name)
4600{
4601 /* XXX Maybe this could be optimized more -- but is it worth it? */
4602
4603 /* pname and ptrs act as a little cache */
4604 static PyObject *pname;
4605 static slotdef *ptrs[MAX_EQUIV];
4606 slotdef *p, **pp;
4607 void **res, **ptr;
4608
4609 if (pname != name) {
4610 /* Collect all slotdefs that match name into ptrs. */
4611 pname = name;
4612 pp = ptrs;
4613 for (p = slotdefs; p->name_strobj; p++) {
4614 if (p->name_strobj == name)
4615 *pp++ = p;
4616 }
4617 *pp = NULL;
4618 }
4619
4620 /* Look in all matching slots of the type; if exactly one of these has
4621 a filled-in slot, return its value. Otherwise return NULL. */
4622 res = NULL;
4623 for (pp = ptrs; *pp; pp++) {
4624 ptr = slotptr(type, (*pp)->offset);
4625 if (ptr == NULL || *ptr == NULL)
4626 continue;
4627 if (res != NULL)
4628 return NULL;
4629 res = ptr;
4630 }
4631 return res;
4632}
4633
4634/* Common code for update_these_slots() and fixup_slot_dispatchers(). This
4635 does some incredibly complex thinking and then sticks something into the
4636 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
4637 interests, and then stores a generic wrapper or a specific function into
4638 the slot.) Return a pointer to the next slotdef with a different offset,
4639 because that's convenient for fixup_slot_dispatchers(). */
4640static slotdef *
4641update_one_slot(PyTypeObject *type, slotdef *p)
4642{
4643 PyObject *descr;
4644 PyWrapperDescrObject *d;
4645 void *generic = NULL, *specific = NULL;
4646 int use_generic = 0;
4647 int offset = p->offset;
4648 void **ptr = slotptr(type, offset);
4649
4650 if (ptr == NULL) {
4651 do {
4652 ++p;
4653 } while (p->offset == offset);
4654 return p;
4655 }
4656 do {
4657 descr = _PyType_Lookup(type, p->name_strobj);
4658 if (descr == NULL)
4659 continue;
4660 if (descr->ob_type == &PyWrapperDescr_Type) {
4661 void **tptr = resolve_slotdups(type, p->name_strobj);
4662 if (tptr == NULL || tptr == ptr)
4663 generic = p->function;
4664 d = (PyWrapperDescrObject *)descr;
4665 if (d->d_base->wrapper == p->wrapper &&
4666 PyType_IsSubtype(type, d->d_type))
4667 {
4668 if (specific == NULL ||
4669 specific == d->d_wrapped)
4670 specific = d->d_wrapped;
4671 else
4672 use_generic = 1;
4673 }
4674 }
Guido van Rossum721f62e2002-08-09 02:14:34 +00004675 else if (descr->ob_type == &PyCFunction_Type &&
4676 PyCFunction_GET_FUNCTION(descr) ==
4677 (PyCFunction)tp_new_wrapper &&
4678 strcmp(p->name, "__new__") == 0)
4679 {
4680 /* The __new__ wrapper is not a wrapper descriptor,
4681 so must be special-cased differently.
4682 If we don't do this, creating an instance will
4683 always use slot_tp_new which will look up
4684 __new__ in the MRO which will call tp_new_wrapper
4685 which will look through the base classes looking
4686 for a static base and call its tp_new (usually
4687 PyType_GenericNew), after performing various
4688 sanity checks and constructing a new argument
4689 list. Cut all that nonsense short -- this speeds
4690 up instance creation tremendously. */
4691 specific = type->tp_new;
4692 /* XXX I'm not 100% sure that there isn't a hole
4693 in this reasoning that requires additional
4694 sanity checks. I'll buy the first person to
4695 point out a bug in this reasoning a beer. */
4696 }
Guido van Rossumc334df52002-04-04 23:44:47 +00004697 else {
4698 use_generic = 1;
4699 generic = p->function;
4700 }
4701 } while ((++p)->offset == offset);
4702 if (specific && !use_generic)
4703 *ptr = specific;
4704 else
4705 *ptr = generic;
4706 return p;
4707}
4708
Guido van Rossum22b13872002-08-06 21:41:44 +00004709static int recurse_down_subclasses(PyTypeObject *type, slotdef **pp,
Jeremy Hylton938ace62002-07-17 16:30:39 +00004710 PyObject *name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004711
Guido van Rossumc334df52002-04-04 23:44:47 +00004712/* In the type, update the slots whose slotdefs are gathered in the pp0 array,
4713 and then do the same for all this type's subtypes. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004714static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004715update_these_slots(PyTypeObject *type, slotdef **pp0, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004716{
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004717 slotdef **pp;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004718
Guido van Rossumc334df52002-04-04 23:44:47 +00004719 for (pp = pp0; *pp; pp++)
4720 update_one_slot(type, *pp);
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004721 return recurse_down_subclasses(type, pp0, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004722}
4723
Guido van Rossumc334df52002-04-04 23:44:47 +00004724/* Update the slots whose slotdefs are gathered in the pp array in all (direct
4725 or indirect) subclasses of type. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004726static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004727recurse_down_subclasses(PyTypeObject *type, slotdef **pp, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004728{
4729 PyTypeObject *subclass;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004730 PyObject *ref, *subclasses, *dict;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004731 int i, n;
4732
4733 subclasses = type->tp_subclasses;
4734 if (subclasses == NULL)
4735 return 0;
4736 assert(PyList_Check(subclasses));
4737 n = PyList_GET_SIZE(subclasses);
4738 for (i = 0; i < n; i++) {
4739 ref = PyList_GET_ITEM(subclasses, i);
4740 assert(PyWeakref_CheckRef(ref));
4741 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
Guido van Rossum59e6c532002-06-14 02:27:07 +00004742 assert(subclass != NULL);
4743 if ((PyObject *)subclass == Py_None)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004744 continue;
4745 assert(PyType_Check(subclass));
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004746 /* Avoid recursing down into unaffected classes */
4747 dict = subclass->tp_dict;
4748 if (dict != NULL && PyDict_Check(dict) &&
4749 PyDict_GetItem(dict, name) != NULL)
4750 continue;
4751 if (update_these_slots(subclass, pp, name) < 0)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004752 return -1;
4753 }
4754 return 0;
4755}
4756
Guido van Rossumc334df52002-04-04 23:44:47 +00004757/* Comparison function for qsort() to compare slotdefs by their offset, and
4758 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004759static int
4760slotdef_cmp(const void *aa, const void *bb)
4761{
4762 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
4763 int c = a->offset - b->offset;
4764 if (c != 0)
4765 return c;
4766 else
4767 return a - b;
4768}
4769
Guido van Rossumc334df52002-04-04 23:44:47 +00004770/* Initialize the slotdefs table by adding interned string objects for the
4771 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004772static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004773init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004774{
4775 slotdef *p;
4776 static int initialized = 0;
4777
4778 if (initialized)
4779 return;
4780 for (p = slotdefs; p->name; p++) {
4781 p->name_strobj = PyString_InternFromString(p->name);
4782 if (!p->name_strobj)
Guido van Rossumc334df52002-04-04 23:44:47 +00004783 Py_FatalError("Out of memory interning slotdef names");
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004784 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004785 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
4786 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004787 initialized = 1;
4788}
4789
Guido van Rossumc334df52002-04-04 23:44:47 +00004790/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004791static int
4792update_slot(PyTypeObject *type, PyObject *name)
4793{
Guido van Rossumc334df52002-04-04 23:44:47 +00004794 slotdef *ptrs[MAX_EQUIV];
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004795 slotdef *p;
4796 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004797 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004798
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004799 init_slotdefs();
4800 pp = ptrs;
4801 for (p = slotdefs; p->name; p++) {
4802 /* XXX assume name is interned! */
4803 if (p->name_strobj == name)
4804 *pp++ = p;
4805 }
4806 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004807 for (pp = ptrs; *pp; pp++) {
4808 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004809 offset = p->offset;
4810 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004811 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004812 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004813 }
Guido van Rossumc334df52002-04-04 23:44:47 +00004814 if (ptrs[0] == NULL)
4815 return 0; /* Not an attribute that affects any slots */
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004816 return update_these_slots(type, ptrs, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004817}
4818
Guido van Rossumc334df52002-04-04 23:44:47 +00004819/* Store the proper functions in the slot dispatches at class (type)
4820 definition time, based upon which operations the class overrides in its
4821 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004822static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004823fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004824{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004825 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004826
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004827 init_slotdefs();
Guido van Rossumc334df52002-04-04 23:44:47 +00004828 for (p = slotdefs; p->name; )
4829 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004830}
Guido van Rossum705f0f52001-08-24 16:47:00 +00004831
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004832static void
4833update_all_slots(PyTypeObject* type)
4834{
4835 slotdef *p;
4836
4837 init_slotdefs();
4838 for (p = slotdefs; p->name; p++) {
4839 /* update_slot returns int but can't actually fail */
4840 update_slot(type, p->name_strobj);
4841 }
4842}
4843
Guido van Rossum6d204072001-10-21 00:44:31 +00004844/* This function is called by PyType_Ready() to populate the type's
4845 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00004846 function slot (like tp_repr) that's defined in the type, one or more
4847 corresponding descriptors are added in the type's tp_dict dictionary
4848 under the appropriate name (like __repr__). Some function slots
4849 cause more than one descriptor to be added (for example, the nb_add
4850 slot adds both __add__ and __radd__ descriptors) and some function
4851 slots compete for the same descriptor (for example both sq_item and
4852 mp_subscript generate a __getitem__ descriptor).
4853
4854 In the latter case, the first slotdef entry encoutered wins. Since
4855 slotdef entries are sorted by the offset of the slot in the etype
4856 struct, this gives us some control over disambiguating between
4857 competing slots: the members of struct etype are listed from most
4858 general to least general, so the most general slot is preferred. In
4859 particular, because as_mapping comes before as_sequence, for a type
4860 that defines both mp_subscript and sq_item, mp_subscript wins.
4861
4862 This only adds new descriptors and doesn't overwrite entries in
4863 tp_dict that were previously defined. The descriptors contain a
4864 reference to the C function they must call, so that it's safe if they
4865 are copied into a subtype's __dict__ and the subtype has a different
4866 C function in its slot -- calling the method defined by the
4867 descriptor will call the C function that was used to create it,
4868 rather than the C function present in the slot when it is called.
4869 (This is important because a subtype may have a C function in the
4870 slot that calls the method from the dictionary, and we want to avoid
4871 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00004872
4873static int
4874add_operators(PyTypeObject *type)
4875{
4876 PyObject *dict = type->tp_dict;
4877 slotdef *p;
4878 PyObject *descr;
4879 void **ptr;
4880
4881 init_slotdefs();
4882 for (p = slotdefs; p->name; p++) {
4883 if (p->wrapper == NULL)
4884 continue;
4885 ptr = slotptr(type, p->offset);
4886 if (!ptr || !*ptr)
4887 continue;
4888 if (PyDict_GetItem(dict, p->name_strobj))
4889 continue;
4890 descr = PyDescr_NewWrapper(type, p, *ptr);
4891 if (descr == NULL)
4892 return -1;
4893 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
4894 return -1;
4895 Py_DECREF(descr);
4896 }
4897 if (type->tp_new != NULL) {
4898 if (add_tp_new_wrapper(type) < 0)
4899 return -1;
4900 }
4901 return 0;
4902}
4903
Guido van Rossum705f0f52001-08-24 16:47:00 +00004904
4905/* Cooperative 'super' */
4906
4907typedef struct {
4908 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00004909 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004910 PyObject *obj;
4911} superobject;
4912
Guido van Rossum6f799372001-09-20 20:46:19 +00004913static PyMemberDef super_members[] = {
4914 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
4915 "the class invoking super()"},
4916 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
4917 "the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004918 {0}
4919};
4920
Guido van Rossum705f0f52001-08-24 16:47:00 +00004921static void
4922super_dealloc(PyObject *self)
4923{
4924 superobject *su = (superobject *)self;
4925
Guido van Rossum048eb752001-10-02 21:24:57 +00004926 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00004927 Py_XDECREF(su->obj);
4928 Py_XDECREF(su->type);
4929 self->ob_type->tp_free(self);
4930}
4931
4932static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004933super_repr(PyObject *self)
4934{
4935 superobject *su = (superobject *)self;
4936
4937 if (su->obj)
4938 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00004939 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004940 su->type ? su->type->tp_name : "NULL",
4941 su->obj->ob_type->tp_name);
4942 else
4943 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00004944 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004945 su->type ? su->type->tp_name : "NULL");
4946}
4947
4948static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00004949super_getattro(PyObject *self, PyObject *name)
4950{
4951 superobject *su = (superobject *)self;
4952
4953 if (su->obj != NULL) {
Tim Petersa91e9642001-11-14 23:32:33 +00004954 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum155db9a2002-04-02 17:53:47 +00004955 PyTypeObject *starttype;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004956 descrgetfunc f;
4957 int i, n;
4958
Guido van Rossum155db9a2002-04-02 17:53:47 +00004959 starttype = su->obj->ob_type;
4960 mro = starttype->tp_mro;
4961
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004962 if (mro == NULL)
4963 n = 0;
4964 else {
4965 assert(PyTuple_Check(mro));
4966 n = PyTuple_GET_SIZE(mro);
4967 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004968 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00004969 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00004970 break;
4971 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004972 if (i >= n && PyType_Check(su->obj)) {
Guido van Rossum155db9a2002-04-02 17:53:47 +00004973 starttype = (PyTypeObject *)(su->obj);
4974 mro = starttype->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004975 if (mro == NULL)
4976 n = 0;
4977 else {
4978 assert(PyTuple_Check(mro));
4979 n = PyTuple_GET_SIZE(mro);
4980 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004981 for (i = 0; i < n; i++) {
4982 if ((PyObject *)(su->type) ==
4983 PyTuple_GET_ITEM(mro, i))
4984 break;
4985 }
Guido van Rossume705ef12001-08-29 15:47:06 +00004986 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00004987 i++;
4988 res = NULL;
4989 for (; i < n; i++) {
4990 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00004991 if (PyType_Check(tmp))
4992 dict = ((PyTypeObject *)tmp)->tp_dict;
4993 else if (PyClass_Check(tmp))
4994 dict = ((PyClassObject *)tmp)->cl_dict;
4995 else
4996 continue;
4997 res = PyDict_GetItem(dict, name);
Guido van Rossum5b443c62001-12-03 15:38:28 +00004998 if (res != NULL && !PyDescr_IsData(res)) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00004999 Py_INCREF(res);
5000 f = res->ob_type->tp_descr_get;
5001 if (f != NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00005002 tmp = f(res, su->obj,
5003 (PyObject *)starttype);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005004 Py_DECREF(res);
5005 res = tmp;
5006 }
5007 return res;
5008 }
5009 }
5010 }
5011 return PyObject_GenericGetAttr(self, name);
5012}
5013
Guido van Rossum5b443c62001-12-03 15:38:28 +00005014static int
5015supercheck(PyTypeObject *type, PyObject *obj)
5016{
5017 if (!PyType_IsSubtype(obj->ob_type, type) &&
5018 !(PyType_Check(obj) &&
5019 PyType_IsSubtype((PyTypeObject *)obj, type))) {
5020 PyErr_SetString(PyExc_TypeError,
5021 "super(type, obj): "
5022 "obj must be an instance or subtype of type");
5023 return -1;
5024 }
5025 else
5026 return 0;
5027}
5028
Guido van Rossum705f0f52001-08-24 16:47:00 +00005029static PyObject *
5030super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5031{
5032 superobject *su = (superobject *)self;
5033 superobject *new;
5034
5035 if (obj == NULL || obj == Py_None || su->obj != NULL) {
5036 /* Not binding to an object, or already bound */
5037 Py_INCREF(self);
5038 return self;
5039 }
Guido van Rossum5b443c62001-12-03 15:38:28 +00005040 if (su->ob_type != &PySuper_Type)
5041 /* If su is an instance of a subclass of super,
5042 call its type */
5043 return PyObject_CallFunction((PyObject *)su->ob_type,
5044 "OO", su->type, obj);
5045 else {
5046 /* Inline the common case */
5047 if (supercheck(su->type, obj) < 0)
5048 return NULL;
5049 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
5050 NULL, NULL);
5051 if (new == NULL)
5052 return NULL;
5053 Py_INCREF(su->type);
5054 Py_INCREF(obj);
5055 new->type = su->type;
5056 new->obj = obj;
5057 return (PyObject *)new;
5058 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005059}
5060
5061static int
5062super_init(PyObject *self, PyObject *args, PyObject *kwds)
5063{
5064 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00005065 PyTypeObject *type;
5066 PyObject *obj = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005067
5068 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
5069 return -1;
5070 if (obj == Py_None)
5071 obj = NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005072 if (obj != NULL && supercheck(type, obj) < 0)
Guido van Rossum705f0f52001-08-24 16:47:00 +00005073 return -1;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005074 Py_INCREF(type);
5075 Py_XINCREF(obj);
5076 su->type = type;
5077 su->obj = obj;
5078 return 0;
5079}
5080
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005081PyDoc_STRVAR(super_doc,
Guido van Rossum705f0f52001-08-24 16:47:00 +00005082"super(type) -> unbound super object\n"
5083"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00005084"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00005085"Typical use to call a cooperative superclass method:\n"
5086"class C(B):\n"
5087" def meth(self, arg):\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005088" super(C, self).meth(arg)");
Guido van Rossum705f0f52001-08-24 16:47:00 +00005089
Guido van Rossum048eb752001-10-02 21:24:57 +00005090static int
5091super_traverse(PyObject *self, visitproc visit, void *arg)
5092{
5093 superobject *su = (superobject *)self;
5094 int err;
5095
5096#define VISIT(SLOT) \
5097 if (SLOT) { \
5098 err = visit((PyObject *)(SLOT), arg); \
5099 if (err) \
5100 return err; \
5101 }
5102
5103 VISIT(su->obj);
5104 VISIT(su->type);
5105
5106#undef VISIT
5107
5108 return 0;
5109}
5110
Guido van Rossum705f0f52001-08-24 16:47:00 +00005111PyTypeObject PySuper_Type = {
5112 PyObject_HEAD_INIT(&PyType_Type)
5113 0, /* ob_size */
5114 "super", /* tp_name */
5115 sizeof(superobject), /* tp_basicsize */
5116 0, /* tp_itemsize */
5117 /* methods */
5118 super_dealloc, /* tp_dealloc */
5119 0, /* tp_print */
5120 0, /* tp_getattr */
5121 0, /* tp_setattr */
5122 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005123 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005124 0, /* tp_as_number */
5125 0, /* tp_as_sequence */
5126 0, /* tp_as_mapping */
5127 0, /* tp_hash */
5128 0, /* tp_call */
5129 0, /* tp_str */
5130 super_getattro, /* tp_getattro */
5131 0, /* tp_setattro */
5132 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00005133 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
5134 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005135 super_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00005136 super_traverse, /* tp_traverse */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005137 0, /* tp_clear */
5138 0, /* tp_richcompare */
5139 0, /* tp_weaklistoffset */
5140 0, /* tp_iter */
5141 0, /* tp_iternext */
5142 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005143 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005144 0, /* tp_getset */
5145 0, /* tp_base */
5146 0, /* tp_dict */
5147 super_descr_get, /* tp_descr_get */
5148 0, /* tp_descr_set */
5149 0, /* tp_dictoffset */
5150 super_init, /* tp_init */
5151 PyType_GenericAlloc, /* tp_alloc */
5152 PyType_GenericNew, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00005153 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005154};