blob: 2de539515c1a419ac7915b2cc780aada7dd5c9c0 [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 Rossumcd118802003-01-06 22:57:47 +00003497/* Boolean helper for SLOT1BINFULL().
3498 right.__class__ is a nontrivial subclass of left.__class__. */
3499static int
3500method_is_overloaded(PyObject *left, PyObject *right, char *name)
3501{
3502 PyObject *a, *b;
3503 int ok;
3504
3505 b = PyObject_GetAttrString((PyObject *)(right->ob_type), name);
3506 if (b == NULL) {
3507 PyErr_Clear();
3508 /* If right doesn't have it, it's not overloaded */
3509 return 0;
3510 }
3511
3512 a = PyObject_GetAttrString((PyObject *)(left->ob_type), name);
3513 if (a == NULL) {
3514 PyErr_Clear();
3515 Py_DECREF(b);
3516 /* If right has it but left doesn't, it's overloaded */
3517 return 1;
3518 }
3519
3520 ok = PyObject_RichCompareBool(a, b, Py_NE);
3521 Py_DECREF(a);
3522 Py_DECREF(b);
3523 if (ok < 0) {
3524 PyErr_Clear();
3525 return 0;
3526 }
3527
3528 return ok;
3529}
3530
Guido van Rossumdc91b992001-08-08 22:26:22 +00003531
3532#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003533static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003534FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003535{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003536 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00003537 int do_other = self->ob_type != other->ob_type && \
3538 other->ob_type->tp_as_number != NULL && \
3539 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003540 if (self->ob_type->tp_as_number != NULL && \
3541 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
3542 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00003543 if (do_other && \
Guido van Rossumcd118802003-01-06 22:57:47 +00003544 PyType_IsSubtype(other->ob_type, self->ob_type) && \
3545 method_is_overloaded(self, other, ROPSTR)) { \
Guido van Rossum55f20992001-10-01 17:18:22 +00003546 r = call_maybe( \
3547 other, ROPSTR, &rcache_str, "(O)", self); \
3548 if (r != Py_NotImplemented) \
3549 return r; \
3550 Py_DECREF(r); \
3551 do_other = 0; \
3552 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00003553 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00003554 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003555 if (r != Py_NotImplemented || \
3556 other->ob_type == self->ob_type) \
3557 return r; \
3558 Py_DECREF(r); \
3559 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00003560 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00003561 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00003562 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003563 } \
3564 Py_INCREF(Py_NotImplemented); \
3565 return Py_NotImplemented; \
3566}
3567
3568#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
3569 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
3570
3571#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
3572static PyObject * \
3573FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
3574{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003575 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003576 return call_method(self, OPSTR, &cache_str, \
3577 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003578}
3579
3580static int
3581slot_sq_length(PyObject *self)
3582{
Guido van Rossum2730b132001-08-28 18:22:14 +00003583 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00003584 PyObject *res = call_method(self, "__len__", &len_str, "()");
Guido van Rossum26111622001-10-01 16:42:49 +00003585 int len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003586
3587 if (res == NULL)
3588 return -1;
Guido van Rossum26111622001-10-01 16:42:49 +00003589 len = (int)PyInt_AsLong(res);
3590 Py_DECREF(res);
Jeremy Hylton73a088e2002-07-25 16:43:29 +00003591 if (len == -1 && PyErr_Occurred())
3592 return -1;
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00003593 if (len < 0) {
Guido van Rossum22b13872002-08-06 21:41:44 +00003594 PyErr_SetString(PyExc_ValueError,
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00003595 "__len__() should return >= 0");
3596 return -1;
3597 }
Guido van Rossum26111622001-10-01 16:42:49 +00003598 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003599}
3600
Guido van Rossumdc91b992001-08-08 22:26:22 +00003601SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
3602SLOT1(slot_sq_repeat, "__mul__", int, "i")
Guido van Rossumf4593e02001-10-03 12:09:30 +00003603
3604/* Super-optimized version of slot_sq_item.
3605 Other slots could do the same... */
3606static PyObject *
3607slot_sq_item(PyObject *self, int i)
3608{
3609 static PyObject *getitem_str;
3610 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
3611 descrgetfunc f;
3612
3613 if (getitem_str == NULL) {
3614 getitem_str = PyString_InternFromString("__getitem__");
3615 if (getitem_str == NULL)
3616 return NULL;
3617 }
3618 func = _PyType_Lookup(self->ob_type, getitem_str);
3619 if (func != NULL) {
Guido van Rossumf4593e02001-10-03 12:09:30 +00003620 if ((f = func->ob_type->tp_descr_get) == NULL)
3621 Py_INCREF(func);
Neal Norwitz673cd822002-10-18 16:33:13 +00003622 else {
Guido van Rossumf4593e02001-10-03 12:09:30 +00003623 func = f(func, self, (PyObject *)(self->ob_type));
Neal Norwitz673cd822002-10-18 16:33:13 +00003624 if (func == NULL) {
3625 return NULL;
3626 }
3627 }
Guido van Rossumf4593e02001-10-03 12:09:30 +00003628 ival = PyInt_FromLong(i);
3629 if (ival != NULL) {
3630 args = PyTuple_New(1);
3631 if (args != NULL) {
3632 PyTuple_SET_ITEM(args, 0, ival);
3633 retval = PyObject_Call(func, args, NULL);
3634 Py_XDECREF(args);
3635 Py_XDECREF(func);
3636 return retval;
3637 }
3638 }
3639 }
3640 else {
3641 PyErr_SetObject(PyExc_AttributeError, getitem_str);
3642 }
3643 Py_XDECREF(args);
3644 Py_XDECREF(ival);
3645 Py_XDECREF(func);
3646 return NULL;
3647}
3648
Guido van Rossumdc91b992001-08-08 22:26:22 +00003649SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003650
3651static int
3652slot_sq_ass_item(PyObject *self, int index, PyObject *value)
3653{
3654 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003655 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003656
3657 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003658 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003659 "(i)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003660 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003661 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003662 "(iO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003663 if (res == NULL)
3664 return -1;
3665 Py_DECREF(res);
3666 return 0;
3667}
3668
3669static int
3670slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
3671{
3672 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003673 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003674
3675 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003676 res = call_method(self, "__delslice__", &delslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003677 "(ii)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003678 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003679 res = call_method(self, "__setslice__", &setslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003680 "(iiO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003681 if (res == NULL)
3682 return -1;
3683 Py_DECREF(res);
3684 return 0;
3685}
3686
3687static int
3688slot_sq_contains(PyObject *self, PyObject *value)
3689{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003690 PyObject *func, *res, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00003691 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003692
Guido van Rossum55f20992001-10-01 17:18:22 +00003693 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003694
3695 if (func != NULL) {
3696 args = Py_BuildValue("(O)", value);
3697 if (args == NULL)
3698 res = NULL;
3699 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003700 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003701 Py_DECREF(args);
3702 }
3703 Py_DECREF(func);
3704 if (res == NULL)
3705 return -1;
3706 return PyObject_IsTrue(res);
3707 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003708 else if (PyErr_Occurred())
3709 return -1;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003710 else {
Tim Peters16a77ad2001-09-08 04:00:12 +00003711 return _PySequence_IterSearch(self, value,
3712 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003713 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003714}
3715
Guido van Rossumdc91b992001-08-08 22:26:22 +00003716SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
3717SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003718
3719#define slot_mp_length slot_sq_length
3720
Guido van Rossumdc91b992001-08-08 22:26:22 +00003721SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003722
3723static int
3724slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
3725{
3726 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003727 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003728
3729 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003730 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003731 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003732 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003733 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003734 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003735 if (res == NULL)
3736 return -1;
3737 Py_DECREF(res);
3738 return 0;
3739}
3740
Guido van Rossumdc91b992001-08-08 22:26:22 +00003741SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
3742SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
3743SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
3744SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
3745SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
3746SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
3747
Jeremy Hylton938ace62002-07-17 16:30:39 +00003748static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003749
3750SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
3751 nb_power, "__pow__", "__rpow__")
3752
3753static PyObject *
3754slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
3755{
Guido van Rossum2730b132001-08-28 18:22:14 +00003756 static PyObject *pow_str;
3757
Guido van Rossumdc91b992001-08-08 22:26:22 +00003758 if (modulus == Py_None)
3759 return slot_nb_power_binary(self, other);
Guido van Rossum23094982002-06-10 14:30:43 +00003760 /* Three-arg power doesn't use __rpow__. But ternary_op
3761 can call this when the second argument's type uses
3762 slot_nb_power, so check before calling self.__pow__. */
3763 if (self->ob_type->tp_as_number != NULL &&
3764 self->ob_type->tp_as_number->nb_power == slot_nb_power) {
3765 return call_method(self, "__pow__", &pow_str,
3766 "(OO)", other, modulus);
3767 }
3768 Py_INCREF(Py_NotImplemented);
3769 return Py_NotImplemented;
Guido van Rossumdc91b992001-08-08 22:26:22 +00003770}
3771
3772SLOT0(slot_nb_negative, "__neg__")
3773SLOT0(slot_nb_positive, "__pos__")
3774SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003775
3776static int
3777slot_nb_nonzero(PyObject *self)
3778{
Tim Petersea7f75d2002-12-07 21:39:16 +00003779 PyObject *func, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00003780 static PyObject *nonzero_str, *len_str;
Tim Petersea7f75d2002-12-07 21:39:16 +00003781 int result = -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003782
Guido van Rossum55f20992001-10-01 17:18:22 +00003783 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003784 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00003785 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00003786 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00003787 func = lookup_maybe(self, "__len__", &len_str);
Tim Petersea7f75d2002-12-07 21:39:16 +00003788 if (func == NULL)
3789 return PyErr_Occurred() ? -1 : 1;
3790 }
3791 args = PyTuple_New(0);
3792 if (args != NULL) {
3793 PyObject *temp = PyObject_Call(func, args, NULL);
3794 Py_DECREF(args);
3795 if (temp != NULL) {
3796 result = PyObject_IsTrue(temp);
3797 Py_DECREF(temp);
Guido van Rossum55f20992001-10-01 17:18:22 +00003798 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00003799 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003800 Py_DECREF(func);
Tim Petersea7f75d2002-12-07 21:39:16 +00003801 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003802}
3803
Guido van Rossumdc91b992001-08-08 22:26:22 +00003804SLOT0(slot_nb_invert, "__invert__")
3805SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
3806SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
3807SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
3808SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
3809SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003810
3811static int
3812slot_nb_coerce(PyObject **a, PyObject **b)
3813{
3814 static PyObject *coerce_str;
3815 PyObject *self = *a, *other = *b;
3816
3817 if (self->ob_type->tp_as_number != NULL &&
3818 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3819 PyObject *r;
3820 r = call_maybe(
3821 self, "__coerce__", &coerce_str, "(O)", other);
3822 if (r == NULL)
3823 return -1;
3824 if (r == Py_NotImplemented) {
3825 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003826 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003827 else {
3828 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3829 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003830 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00003831 Py_DECREF(r);
3832 return -1;
3833 }
3834 *a = PyTuple_GET_ITEM(r, 0);
3835 Py_INCREF(*a);
3836 *b = PyTuple_GET_ITEM(r, 1);
3837 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003838 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00003839 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003840 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003841 }
3842 if (other->ob_type->tp_as_number != NULL &&
3843 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3844 PyObject *r;
3845 r = call_maybe(
3846 other, "__coerce__", &coerce_str, "(O)", self);
3847 if (r == NULL)
3848 return -1;
3849 if (r == Py_NotImplemented) {
3850 Py_DECREF(r);
3851 return 1;
3852 }
3853 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3854 PyErr_SetString(PyExc_TypeError,
3855 "__coerce__ didn't return a 2-tuple");
3856 Py_DECREF(r);
3857 return -1;
3858 }
3859 *a = PyTuple_GET_ITEM(r, 1);
3860 Py_INCREF(*a);
3861 *b = PyTuple_GET_ITEM(r, 0);
3862 Py_INCREF(*b);
3863 Py_DECREF(r);
3864 return 0;
3865 }
3866 return 1;
3867}
3868
Guido van Rossumdc91b992001-08-08 22:26:22 +00003869SLOT0(slot_nb_int, "__int__")
3870SLOT0(slot_nb_long, "__long__")
3871SLOT0(slot_nb_float, "__float__")
3872SLOT0(slot_nb_oct, "__oct__")
3873SLOT0(slot_nb_hex, "__hex__")
3874SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
3875SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
3876SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
3877SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
3878SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003879SLOT1(slot_nb_inplace_power, "__ipow__", PyObject *, "O")
Guido van Rossumdc91b992001-08-08 22:26:22 +00003880SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
3881SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
3882SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
3883SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
3884SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
3885SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
3886 "__floordiv__", "__rfloordiv__")
3887SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
3888SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
3889SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003890
3891static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00003892half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003893{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003894 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003895 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003896 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003897
Guido van Rossum60718732001-08-28 17:47:51 +00003898 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003899 if (func == NULL) {
3900 PyErr_Clear();
3901 }
3902 else {
3903 args = Py_BuildValue("(O)", other);
3904 if (args == NULL)
3905 res = NULL;
3906 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003907 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003908 Py_DECREF(args);
3909 }
Raymond Hettingerab5dae32002-06-24 13:08:16 +00003910 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003911 if (res != Py_NotImplemented) {
3912 if (res == NULL)
3913 return -2;
3914 c = PyInt_AsLong(res);
3915 Py_DECREF(res);
3916 if (c == -1 && PyErr_Occurred())
3917 return -2;
3918 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
3919 }
3920 Py_DECREF(res);
3921 }
3922 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003923}
3924
Guido van Rossumab3b0342001-09-18 20:38:53 +00003925/* This slot is published for the benefit of try_3way_compare in object.c */
3926int
3927_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00003928{
3929 int c;
3930
Guido van Rossumab3b0342001-09-18 20:38:53 +00003931 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003932 c = half_compare(self, other);
3933 if (c <= 1)
3934 return c;
3935 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00003936 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003937 c = half_compare(other, self);
3938 if (c < -1)
3939 return -2;
3940 if (c <= 1)
3941 return -c;
3942 }
3943 return (void *)self < (void *)other ? -1 :
3944 (void *)self > (void *)other ? 1 : 0;
3945}
3946
3947static PyObject *
3948slot_tp_repr(PyObject *self)
3949{
3950 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003951 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003952
Guido van Rossum60718732001-08-28 17:47:51 +00003953 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003954 if (func != NULL) {
3955 res = PyEval_CallObject(func, NULL);
3956 Py_DECREF(func);
3957 return res;
3958 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00003959 PyErr_Clear();
3960 return PyString_FromFormat("<%s object at %p>",
3961 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003962}
3963
3964static PyObject *
3965slot_tp_str(PyObject *self)
3966{
3967 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003968 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003969
Guido van Rossum60718732001-08-28 17:47:51 +00003970 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003971 if (func != NULL) {
3972 res = PyEval_CallObject(func, NULL);
3973 Py_DECREF(func);
3974 return res;
3975 }
3976 else {
3977 PyErr_Clear();
3978 return slot_tp_repr(self);
3979 }
3980}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003981
3982static long
3983slot_tp_hash(PyObject *self)
3984{
Tim Peters61ce0a92002-12-06 23:38:02 +00003985 PyObject *func;
Guido van Rossum60718732001-08-28 17:47:51 +00003986 static PyObject *hash_str, *eq_str, *cmp_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003987 long h;
3988
Guido van Rossum60718732001-08-28 17:47:51 +00003989 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003990
3991 if (func != NULL) {
Tim Peters61ce0a92002-12-06 23:38:02 +00003992 PyObject *res = PyEval_CallObject(func, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003993 Py_DECREF(func);
3994 if (res == NULL)
3995 return -1;
3996 h = PyInt_AsLong(res);
Tim Peters61ce0a92002-12-06 23:38:02 +00003997 Py_DECREF(res);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003998 }
3999 else {
4000 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004001 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004002 if (func == NULL) {
4003 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004004 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004005 }
4006 if (func != NULL) {
4007 Py_DECREF(func);
4008 PyErr_SetString(PyExc_TypeError, "unhashable type");
4009 return -1;
4010 }
4011 PyErr_Clear();
4012 h = _Py_HashPointer((void *)self);
4013 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004014 if (h == -1 && !PyErr_Occurred())
4015 h = -2;
4016 return h;
4017}
4018
4019static PyObject *
4020slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
4021{
Guido van Rossum60718732001-08-28 17:47:51 +00004022 static PyObject *call_str;
4023 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004024 PyObject *res;
4025
4026 if (meth == NULL)
4027 return NULL;
4028 res = PyObject_Call(meth, args, kwds);
4029 Py_DECREF(meth);
4030 return res;
4031}
4032
Guido van Rossum14a6f832001-10-17 13:59:09 +00004033/* There are two slot dispatch functions for tp_getattro.
4034
4035 - slot_tp_getattro() is used when __getattribute__ is overridden
4036 but no __getattr__ hook is present;
4037
4038 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
4039
Guido van Rossumc334df52002-04-04 23:44:47 +00004040 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
4041 detects the absence of __getattr__ and then installs the simpler slot if
4042 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00004043
Tim Peters6d6c1a32001-08-02 04:15:00 +00004044static PyObject *
4045slot_tp_getattro(PyObject *self, PyObject *name)
4046{
Guido van Rossum14a6f832001-10-17 13:59:09 +00004047 static PyObject *getattribute_str = NULL;
4048 return call_method(self, "__getattribute__", &getattribute_str,
4049 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004050}
4051
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004052static PyObject *
4053slot_tp_getattr_hook(PyObject *self, PyObject *name)
4054{
4055 PyTypeObject *tp = self->ob_type;
4056 PyObject *getattr, *getattribute, *res;
4057 static PyObject *getattribute_str = NULL;
4058 static PyObject *getattr_str = NULL;
4059
4060 if (getattr_str == NULL) {
4061 getattr_str = PyString_InternFromString("__getattr__");
4062 if (getattr_str == NULL)
4063 return NULL;
4064 }
4065 if (getattribute_str == NULL) {
4066 getattribute_str =
4067 PyString_InternFromString("__getattribute__");
4068 if (getattribute_str == NULL)
4069 return NULL;
4070 }
4071 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004072 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004073 /* No __getattr__ hook: use a simpler dispatcher */
4074 tp->tp_getattro = slot_tp_getattro;
4075 return slot_tp_getattro(self, name);
4076 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004077 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004078 if (getattribute == NULL ||
4079 (getattribute->ob_type == &PyWrapperDescr_Type &&
4080 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
4081 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004082 res = PyObject_GenericGetAttr(self, name);
4083 else
4084 res = PyObject_CallFunction(getattribute, "OO", self, name);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004085 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004086 PyErr_Clear();
4087 res = PyObject_CallFunction(getattr, "OO", self, name);
4088 }
4089 return res;
4090}
4091
Tim Peters6d6c1a32001-08-02 04:15:00 +00004092static int
4093slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
4094{
4095 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004096 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004097
4098 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004099 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004100 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004101 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004102 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004103 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004104 if (res == NULL)
4105 return -1;
4106 Py_DECREF(res);
4107 return 0;
4108}
4109
4110/* Map rich comparison operators to their __xx__ namesakes */
4111static char *name_op[] = {
4112 "__lt__",
4113 "__le__",
4114 "__eq__",
4115 "__ne__",
4116 "__gt__",
4117 "__ge__",
4118};
4119
4120static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00004121half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004122{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004123 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004124 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00004125
Guido van Rossum60718732001-08-28 17:47:51 +00004126 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004127 if (func == NULL) {
4128 PyErr_Clear();
4129 Py_INCREF(Py_NotImplemented);
4130 return Py_NotImplemented;
4131 }
4132 args = Py_BuildValue("(O)", other);
4133 if (args == NULL)
4134 res = NULL;
4135 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004136 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004137 Py_DECREF(args);
4138 }
4139 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004140 return res;
4141}
4142
Guido van Rossumb8f63662001-08-15 23:57:02 +00004143/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
4144static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
4145
4146static PyObject *
4147slot_tp_richcompare(PyObject *self, PyObject *other, int op)
4148{
4149 PyObject *res;
4150
4151 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
4152 res = half_richcompare(self, other, op);
4153 if (res != Py_NotImplemented)
4154 return res;
4155 Py_DECREF(res);
4156 }
4157 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
4158 res = half_richcompare(other, self, swapped_op[op]);
4159 if (res != Py_NotImplemented) {
4160 return res;
4161 }
4162 Py_DECREF(res);
4163 }
4164 Py_INCREF(Py_NotImplemented);
4165 return Py_NotImplemented;
4166}
4167
4168static PyObject *
4169slot_tp_iter(PyObject *self)
4170{
4171 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004172 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004173
Guido van Rossum60718732001-08-28 17:47:51 +00004174 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004175 if (func != NULL) {
Guido van Rossum84b2bed2002-08-16 17:01:09 +00004176 PyObject *args;
4177 args = res = PyTuple_New(0);
4178 if (args != NULL) {
4179 res = PyObject_Call(func, args, NULL);
4180 Py_DECREF(args);
4181 }
4182 Py_DECREF(func);
4183 return res;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004184 }
4185 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004186 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004187 if (func == NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00004188 PyErr_SetString(PyExc_TypeError,
4189 "iteration over non-sequence");
Guido van Rossumb8f63662001-08-15 23:57:02 +00004190 return NULL;
4191 }
4192 Py_DECREF(func);
4193 return PySeqIter_New(self);
4194}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004195
4196static PyObject *
4197slot_tp_iternext(PyObject *self)
4198{
Guido van Rossum2730b132001-08-28 18:22:14 +00004199 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00004200 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004201}
4202
Guido van Rossum1a493502001-08-17 16:47:50 +00004203static PyObject *
4204slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4205{
4206 PyTypeObject *tp = self->ob_type;
4207 PyObject *get;
4208 static PyObject *get_str = NULL;
4209
4210 if (get_str == NULL) {
4211 get_str = PyString_InternFromString("__get__");
4212 if (get_str == NULL)
4213 return NULL;
4214 }
4215 get = _PyType_Lookup(tp, get_str);
4216 if (get == NULL) {
4217 /* Avoid further slowdowns */
4218 if (tp->tp_descr_get == slot_tp_descr_get)
4219 tp->tp_descr_get = NULL;
4220 Py_INCREF(self);
4221 return self;
4222 }
Guido van Rossum2c252392001-08-24 10:13:31 +00004223 if (obj == NULL)
4224 obj = Py_None;
4225 if (type == NULL)
4226 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00004227 return PyObject_CallFunction(get, "OOO", self, obj, type);
4228}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004229
4230static int
4231slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
4232{
Guido van Rossum2c252392001-08-24 10:13:31 +00004233 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004234 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00004235
4236 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00004237 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004238 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00004239 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004240 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004241 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004242 if (res == NULL)
4243 return -1;
4244 Py_DECREF(res);
4245 return 0;
4246}
4247
4248static int
4249slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
4250{
Guido van Rossum60718732001-08-28 17:47:51 +00004251 static PyObject *init_str;
4252 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004253 PyObject *res;
4254
4255 if (meth == NULL)
4256 return -1;
4257 res = PyObject_Call(meth, args, kwds);
4258 Py_DECREF(meth);
4259 if (res == NULL)
4260 return -1;
4261 Py_DECREF(res);
4262 return 0;
4263}
4264
4265static PyObject *
4266slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4267{
Guido van Rossum7bed2132002-08-08 21:57:53 +00004268 static PyObject *new_str;
4269 PyObject *func;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004270 PyObject *newargs, *x;
4271 int i, n;
4272
Guido van Rossum7bed2132002-08-08 21:57:53 +00004273 if (new_str == NULL) {
4274 new_str = PyString_InternFromString("__new__");
4275 if (new_str == NULL)
4276 return NULL;
4277 }
4278 func = PyObject_GetAttr((PyObject *)type, new_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004279 if (func == NULL)
4280 return NULL;
4281 assert(PyTuple_Check(args));
4282 n = PyTuple_GET_SIZE(args);
4283 newargs = PyTuple_New(n+1);
4284 if (newargs == NULL)
4285 return NULL;
4286 Py_INCREF(type);
4287 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
4288 for (i = 0; i < n; i++) {
4289 x = PyTuple_GET_ITEM(args, i);
4290 Py_INCREF(x);
4291 PyTuple_SET_ITEM(newargs, i+1, x);
4292 }
4293 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00004294 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004295 Py_DECREF(func);
4296 return x;
4297}
4298
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004299static void
4300slot_tp_del(PyObject *self)
4301{
4302 static PyObject *del_str = NULL;
4303 PyObject *del, *res;
4304 PyObject *error_type, *error_value, *error_traceback;
4305
4306 /* Temporarily resurrect the object. */
4307 assert(self->ob_refcnt == 0);
4308 self->ob_refcnt = 1;
4309
4310 /* Save the current exception, if any. */
4311 PyErr_Fetch(&error_type, &error_value, &error_traceback);
4312
4313 /* Execute __del__ method, if any. */
4314 del = lookup_maybe(self, "__del__", &del_str);
4315 if (del != NULL) {
4316 res = PyEval_CallObject(del, NULL);
4317 if (res == NULL)
4318 PyErr_WriteUnraisable(del);
4319 else
4320 Py_DECREF(res);
4321 Py_DECREF(del);
4322 }
4323
4324 /* Restore the saved exception. */
4325 PyErr_Restore(error_type, error_value, error_traceback);
4326
4327 /* Undo the temporary resurrection; can't use DECREF here, it would
4328 * cause a recursive call.
4329 */
4330 assert(self->ob_refcnt > 0);
4331 if (--self->ob_refcnt == 0)
4332 return; /* this is the normal path out */
4333
4334 /* __del__ resurrected it! Make it look like the original Py_DECREF
4335 * never happened.
4336 */
4337 {
4338 int refcnt = self->ob_refcnt;
4339 _Py_NewReference(self);
4340 self->ob_refcnt = refcnt;
4341 }
4342 assert(!PyType_IS_GC(self->ob_type) ||
4343 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
4344 /* If Py_REF_DEBUG, the original decref dropped _Py_RefTotal, but
4345 * _Py_NewReference bumped it again, so that's a wash.
4346 * If Py_TRACE_REFS, _Py_NewReference re-added self to the object
4347 * chain, so no more to do there either.
4348 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
4349 * _Py_NewReference bumped tp_allocs: both of those need to be
4350 * undone.
4351 */
4352#ifdef COUNT_ALLOCS
4353 --self->ob_type->tp_frees;
4354 --self->ob_type->tp_allocs;
4355#endif
4356}
4357
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004358
4359/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
4360 functions. The offsets here are relative to the 'etype' structure, which
4361 incorporates the additional structures used for numbers, sequences and
4362 mappings. Note that multiple names may map to the same slot (e.g. __eq__,
4363 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00004364 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
4365 terminated with an all-zero entry. (This table is further initialized and
4366 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004367
Guido van Rossum6d204072001-10-21 00:44:31 +00004368typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004369
4370#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00004371#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004372#undef ETSLOT
4373#undef SQSLOT
4374#undef MPSLOT
4375#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00004376#undef UNSLOT
4377#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004378#undef BINSLOT
4379#undef RBINSLOT
4380
Guido van Rossum6d204072001-10-21 00:44:31 +00004381#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004382 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
4383 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00004384#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
4385 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004386 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00004387#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004388 {NAME, offsetof(etype, SLOT), (void *)(FUNCTION), WRAPPER, \
4389 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00004390#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4391 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
4392#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4393 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
4394#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4395 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
4396#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4397 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
4398 "x." NAME "() <==> " DOC)
4399#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4400 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
4401 "x." NAME "(y) <==> x" DOC "y")
4402#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
4403 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
4404 "x." NAME "(y) <==> x" DOC "y")
4405#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
4406 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
4407 "x." NAME "(y) <==> y" DOC "x")
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004408
4409static slotdef slotdefs[] = {
Guido van Rossum6d204072001-10-21 00:44:31 +00004410 SQSLOT("__len__", sq_length, slot_sq_length, wrap_inquiry,
4411 "x.__len__() <==> len(x)"),
4412 SQSLOT("__add__", sq_concat, slot_sq_concat, wrap_binaryfunc,
4413 "x.__add__(y) <==> x+y"),
4414 SQSLOT("__mul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
4415 "x.__mul__(n) <==> x*n"),
4416 SQSLOT("__rmul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
4417 "x.__rmul__(n) <==> n*x"),
4418 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
4419 "x.__getitem__(y) <==> x[y]"),
4420 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_intintargfunc,
4421 "x.__getslice__(i, j) <==> x[i:j]"),
4422 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
4423 "x.__setitem__(i, y) <==> x[i]=y"),
4424 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
4425 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004426 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Guido van Rossum6d204072001-10-21 00:44:31 +00004427 wrap_intintobjargproc,
4428 "x.__setslice__(i, j, y) <==> x[i:j]=y"),
4429 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
4430 "x.__delslice__(i, j) <==> del x[i:j]"),
4431 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
4432 "x.__contains__(y) <==> y in x"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004433 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat,
Guido van Rossum6d204072001-10-21 00:44:31 +00004434 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004435 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat,
Guido van Rossum6d204072001-10-21 00:44:31 +00004436 wrap_intargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004437
Guido van Rossum6d204072001-10-21 00:44:31 +00004438 MPSLOT("__len__", mp_length, slot_mp_length, wrap_inquiry,
4439 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00004440 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004441 wrap_binaryfunc,
4442 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004443 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004444 wrap_objobjargproc,
4445 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004446 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004447 wrap_delitem,
4448 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004449
Guido van Rossum6d204072001-10-21 00:44:31 +00004450 BINSLOT("__add__", nb_add, slot_nb_add,
4451 "+"),
4452 RBINSLOT("__radd__", nb_add, slot_nb_add,
4453 "+"),
4454 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
4455 "-"),
4456 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
4457 "-"),
4458 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
4459 "*"),
4460 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
4461 "*"),
4462 BINSLOT("__div__", nb_divide, slot_nb_divide,
4463 "/"),
4464 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
4465 "/"),
4466 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
4467 "%"),
4468 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
4469 "%"),
4470 BINSLOT("__divmod__", nb_divmod, slot_nb_divmod,
4471 "divmod(x, y)"),
4472 RBINSLOT("__rdivmod__", nb_divmod, slot_nb_divmod,
4473 "divmod(y, x)"),
4474 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
4475 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
4476 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
4477 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
4478 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
4479 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
4480 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
4481 "abs(x)"),
Guido van Rossumdfce3bf2002-03-10 14:11:16 +00004482 UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquiry,
Guido van Rossum6d204072001-10-21 00:44:31 +00004483 "x != 0"),
4484 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
4485 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
4486 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
4487 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
4488 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
4489 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
4490 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
4491 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
4492 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
4493 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
4494 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
4495 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
4496 "x.__coerce__(y) <==> coerce(x, y)"),
4497 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
4498 "int(x)"),
4499 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
4500 "long(x)"),
4501 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
4502 "float(x)"),
4503 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
4504 "oct(x)"),
4505 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
4506 "hex(x)"),
4507 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
4508 wrap_binaryfunc, "+"),
4509 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
4510 wrap_binaryfunc, "-"),
4511 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
4512 wrap_binaryfunc, "*"),
4513 IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
4514 wrap_binaryfunc, "/"),
4515 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
4516 wrap_binaryfunc, "%"),
4517 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
Guido van Rossum6e5680f2002-10-15 01:01:53 +00004518 wrap_binaryfunc, "**"),
Guido van Rossum6d204072001-10-21 00:44:31 +00004519 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
4520 wrap_binaryfunc, "<<"),
4521 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
4522 wrap_binaryfunc, ">>"),
4523 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
4524 wrap_binaryfunc, "&"),
4525 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
4526 wrap_binaryfunc, "^"),
4527 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
4528 wrap_binaryfunc, "|"),
4529 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
4530 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
4531 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
4532 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
4533 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
4534 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
4535 IBSLOT("__itruediv__", nb_inplace_true_divide,
4536 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004537
Guido van Rossum6d204072001-10-21 00:44:31 +00004538 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
4539 "x.__str__() <==> str(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00004540 TPSLOT("__str__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00004541 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
4542 "x.__repr__() <==> repr(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00004543 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00004544 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
4545 "x.__cmp__(y) <==> cmp(x,y)"),
4546 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
4547 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00004548 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
4549 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004550 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00004551 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
4552 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
4553 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
4554 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
4555 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
4556 "x.__setattr__('name', value) <==> x.name = value"),
4557 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
4558 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
4559 "x.__delattr__('name') <==> del x.name"),
4560 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
4561 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
4562 "x.__lt__(y) <==> x<y"),
4563 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
4564 "x.__le__(y) <==> x<=y"),
4565 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
4566 "x.__eq__(y) <==> x==y"),
4567 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
4568 "x.__ne__(y) <==> x!=y"),
4569 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
4570 "x.__gt__(y) <==> x>y"),
4571 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
4572 "x.__ge__(y) <==> x>=y"),
4573 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
4574 "x.__iter__() <==> iter(x)"),
4575 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
4576 "x.next() -> the next value, or raise StopIteration"),
4577 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
4578 "descr.__get__(obj[, type]) -> value"),
4579 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
4580 "descr.__set__(obj, value)"),
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004581 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
4582 wrap_descr_delete, "descr.__delete__(obj)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00004583 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00004584 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00004585 "see x.__class__.__doc__ for signature",
4586 PyWrapperFlag_KEYWORDS),
4587 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004588 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004589 {NULL}
4590};
4591
Guido van Rossumc334df52002-04-04 23:44:47 +00004592/* Given a type pointer and an offset gotten from a slotdef entry, return a
4593 pointer to the actual slot. This is not quite the same as simply adding
4594 the offset to the type pointer, since it takes care to indirect through the
4595 proper indirection pointer (as_buffer, etc.); it returns NULL if the
4596 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004597static void **
4598slotptr(PyTypeObject *type, int offset)
4599{
4600 char *ptr;
4601
Guido van Rossum09638c12002-06-13 19:17:46 +00004602 /* Note: this depends on the order of the members of etype! */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004603 assert(offset >= 0);
4604 assert(offset < offsetof(etype, as_buffer));
Guido van Rossum09638c12002-06-13 19:17:46 +00004605 if (offset >= offsetof(etype, as_sequence)) {
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004606 ptr = (void *)type->tp_as_sequence;
4607 offset -= offsetof(etype, as_sequence);
4608 }
Guido van Rossum09638c12002-06-13 19:17:46 +00004609 else if (offset >= offsetof(etype, as_mapping)) {
4610 ptr = (void *)type->tp_as_mapping;
4611 offset -= offsetof(etype, as_mapping);
4612 }
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004613 else if (offset >= offsetof(etype, as_number)) {
4614 ptr = (void *)type->tp_as_number;
4615 offset -= offsetof(etype, as_number);
4616 }
4617 else {
4618 ptr = (void *)type;
4619 }
4620 if (ptr != NULL)
4621 ptr += offset;
4622 return (void **)ptr;
4623}
Guido van Rossumf040ede2001-08-07 16:40:56 +00004624
Guido van Rossumc334df52002-04-04 23:44:47 +00004625/* Length of array of slotdef pointers used to store slots with the
4626 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
4627 the same __name__, for any __name__. Since that's a static property, it is
4628 appropriate to declare fixed-size arrays for this. */
4629#define MAX_EQUIV 10
4630
4631/* Return a slot pointer for a given name, but ONLY if the attribute has
4632 exactly one slot function. The name must be an interned string. */
4633static void **
4634resolve_slotdups(PyTypeObject *type, PyObject *name)
4635{
4636 /* XXX Maybe this could be optimized more -- but is it worth it? */
4637
4638 /* pname and ptrs act as a little cache */
4639 static PyObject *pname;
4640 static slotdef *ptrs[MAX_EQUIV];
4641 slotdef *p, **pp;
4642 void **res, **ptr;
4643
4644 if (pname != name) {
4645 /* Collect all slotdefs that match name into ptrs. */
4646 pname = name;
4647 pp = ptrs;
4648 for (p = slotdefs; p->name_strobj; p++) {
4649 if (p->name_strobj == name)
4650 *pp++ = p;
4651 }
4652 *pp = NULL;
4653 }
4654
4655 /* Look in all matching slots of the type; if exactly one of these has
4656 a filled-in slot, return its value. Otherwise return NULL. */
4657 res = NULL;
4658 for (pp = ptrs; *pp; pp++) {
4659 ptr = slotptr(type, (*pp)->offset);
4660 if (ptr == NULL || *ptr == NULL)
4661 continue;
4662 if (res != NULL)
4663 return NULL;
4664 res = ptr;
4665 }
4666 return res;
4667}
4668
4669/* Common code for update_these_slots() and fixup_slot_dispatchers(). This
4670 does some incredibly complex thinking and then sticks something into the
4671 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
4672 interests, and then stores a generic wrapper or a specific function into
4673 the slot.) Return a pointer to the next slotdef with a different offset,
4674 because that's convenient for fixup_slot_dispatchers(). */
4675static slotdef *
4676update_one_slot(PyTypeObject *type, slotdef *p)
4677{
4678 PyObject *descr;
4679 PyWrapperDescrObject *d;
4680 void *generic = NULL, *specific = NULL;
4681 int use_generic = 0;
4682 int offset = p->offset;
4683 void **ptr = slotptr(type, offset);
4684
4685 if (ptr == NULL) {
4686 do {
4687 ++p;
4688 } while (p->offset == offset);
4689 return p;
4690 }
4691 do {
4692 descr = _PyType_Lookup(type, p->name_strobj);
4693 if (descr == NULL)
4694 continue;
4695 if (descr->ob_type == &PyWrapperDescr_Type) {
4696 void **tptr = resolve_slotdups(type, p->name_strobj);
4697 if (tptr == NULL || tptr == ptr)
4698 generic = p->function;
4699 d = (PyWrapperDescrObject *)descr;
4700 if (d->d_base->wrapper == p->wrapper &&
4701 PyType_IsSubtype(type, d->d_type))
4702 {
4703 if (specific == NULL ||
4704 specific == d->d_wrapped)
4705 specific = d->d_wrapped;
4706 else
4707 use_generic = 1;
4708 }
4709 }
Guido van Rossum721f62e2002-08-09 02:14:34 +00004710 else if (descr->ob_type == &PyCFunction_Type &&
4711 PyCFunction_GET_FUNCTION(descr) ==
4712 (PyCFunction)tp_new_wrapper &&
4713 strcmp(p->name, "__new__") == 0)
4714 {
4715 /* The __new__ wrapper is not a wrapper descriptor,
4716 so must be special-cased differently.
4717 If we don't do this, creating an instance will
4718 always use slot_tp_new which will look up
4719 __new__ in the MRO which will call tp_new_wrapper
4720 which will look through the base classes looking
4721 for a static base and call its tp_new (usually
4722 PyType_GenericNew), after performing various
4723 sanity checks and constructing a new argument
4724 list. Cut all that nonsense short -- this speeds
4725 up instance creation tremendously. */
4726 specific = type->tp_new;
4727 /* XXX I'm not 100% sure that there isn't a hole
4728 in this reasoning that requires additional
4729 sanity checks. I'll buy the first person to
4730 point out a bug in this reasoning a beer. */
4731 }
Guido van Rossumc334df52002-04-04 23:44:47 +00004732 else {
4733 use_generic = 1;
4734 generic = p->function;
4735 }
4736 } while ((++p)->offset == offset);
4737 if (specific && !use_generic)
4738 *ptr = specific;
4739 else
4740 *ptr = generic;
4741 return p;
4742}
4743
Guido van Rossum22b13872002-08-06 21:41:44 +00004744static int recurse_down_subclasses(PyTypeObject *type, slotdef **pp,
Jeremy Hylton938ace62002-07-17 16:30:39 +00004745 PyObject *name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004746
Guido van Rossumc334df52002-04-04 23:44:47 +00004747/* In the type, update the slots whose slotdefs are gathered in the pp0 array,
4748 and then do the same for all this type's subtypes. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004749static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004750update_these_slots(PyTypeObject *type, slotdef **pp0, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004751{
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004752 slotdef **pp;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004753
Guido van Rossumc334df52002-04-04 23:44:47 +00004754 for (pp = pp0; *pp; pp++)
4755 update_one_slot(type, *pp);
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004756 return recurse_down_subclasses(type, pp0, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004757}
4758
Guido van Rossumc334df52002-04-04 23:44:47 +00004759/* Update the slots whose slotdefs are gathered in the pp array in all (direct
4760 or indirect) subclasses of type. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004761static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004762recurse_down_subclasses(PyTypeObject *type, slotdef **pp, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004763{
4764 PyTypeObject *subclass;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004765 PyObject *ref, *subclasses, *dict;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004766 int i, n;
4767
4768 subclasses = type->tp_subclasses;
4769 if (subclasses == NULL)
4770 return 0;
4771 assert(PyList_Check(subclasses));
4772 n = PyList_GET_SIZE(subclasses);
4773 for (i = 0; i < n; i++) {
4774 ref = PyList_GET_ITEM(subclasses, i);
4775 assert(PyWeakref_CheckRef(ref));
4776 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
Guido van Rossum59e6c532002-06-14 02:27:07 +00004777 assert(subclass != NULL);
4778 if ((PyObject *)subclass == Py_None)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004779 continue;
4780 assert(PyType_Check(subclass));
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004781 /* Avoid recursing down into unaffected classes */
4782 dict = subclass->tp_dict;
4783 if (dict != NULL && PyDict_Check(dict) &&
4784 PyDict_GetItem(dict, name) != NULL)
4785 continue;
4786 if (update_these_slots(subclass, pp, name) < 0)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004787 return -1;
4788 }
4789 return 0;
4790}
4791
Guido van Rossumc334df52002-04-04 23:44:47 +00004792/* Comparison function for qsort() to compare slotdefs by their offset, and
4793 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004794static int
4795slotdef_cmp(const void *aa, const void *bb)
4796{
4797 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
4798 int c = a->offset - b->offset;
4799 if (c != 0)
4800 return c;
4801 else
4802 return a - b;
4803}
4804
Guido van Rossumc334df52002-04-04 23:44:47 +00004805/* Initialize the slotdefs table by adding interned string objects for the
4806 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004807static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004808init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004809{
4810 slotdef *p;
4811 static int initialized = 0;
4812
4813 if (initialized)
4814 return;
4815 for (p = slotdefs; p->name; p++) {
4816 p->name_strobj = PyString_InternFromString(p->name);
4817 if (!p->name_strobj)
Guido van Rossumc334df52002-04-04 23:44:47 +00004818 Py_FatalError("Out of memory interning slotdef names");
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004819 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004820 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
4821 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004822 initialized = 1;
4823}
4824
Guido van Rossumc334df52002-04-04 23:44:47 +00004825/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004826static int
4827update_slot(PyTypeObject *type, PyObject *name)
4828{
Guido van Rossumc334df52002-04-04 23:44:47 +00004829 slotdef *ptrs[MAX_EQUIV];
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004830 slotdef *p;
4831 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004832 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004833
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004834 init_slotdefs();
4835 pp = ptrs;
4836 for (p = slotdefs; p->name; p++) {
4837 /* XXX assume name is interned! */
4838 if (p->name_strobj == name)
4839 *pp++ = p;
4840 }
4841 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004842 for (pp = ptrs; *pp; pp++) {
4843 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004844 offset = p->offset;
4845 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004846 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004847 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004848 }
Guido van Rossumc334df52002-04-04 23:44:47 +00004849 if (ptrs[0] == NULL)
4850 return 0; /* Not an attribute that affects any slots */
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004851 return update_these_slots(type, ptrs, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004852}
4853
Guido van Rossumc334df52002-04-04 23:44:47 +00004854/* Store the proper functions in the slot dispatches at class (type)
4855 definition time, based upon which operations the class overrides in its
4856 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004857static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004858fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004859{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004860 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004861
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004862 init_slotdefs();
Guido van Rossumc334df52002-04-04 23:44:47 +00004863 for (p = slotdefs; p->name; )
4864 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004865}
Guido van Rossum705f0f52001-08-24 16:47:00 +00004866
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004867static void
4868update_all_slots(PyTypeObject* type)
4869{
4870 slotdef *p;
4871
4872 init_slotdefs();
4873 for (p = slotdefs; p->name; p++) {
4874 /* update_slot returns int but can't actually fail */
4875 update_slot(type, p->name_strobj);
4876 }
4877}
4878
Guido van Rossum6d204072001-10-21 00:44:31 +00004879/* This function is called by PyType_Ready() to populate the type's
4880 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00004881 function slot (like tp_repr) that's defined in the type, one or more
4882 corresponding descriptors are added in the type's tp_dict dictionary
4883 under the appropriate name (like __repr__). Some function slots
4884 cause more than one descriptor to be added (for example, the nb_add
4885 slot adds both __add__ and __radd__ descriptors) and some function
4886 slots compete for the same descriptor (for example both sq_item and
4887 mp_subscript generate a __getitem__ descriptor).
4888
4889 In the latter case, the first slotdef entry encoutered wins. Since
4890 slotdef entries are sorted by the offset of the slot in the etype
4891 struct, this gives us some control over disambiguating between
4892 competing slots: the members of struct etype are listed from most
4893 general to least general, so the most general slot is preferred. In
4894 particular, because as_mapping comes before as_sequence, for a type
4895 that defines both mp_subscript and sq_item, mp_subscript wins.
4896
4897 This only adds new descriptors and doesn't overwrite entries in
4898 tp_dict that were previously defined. The descriptors contain a
4899 reference to the C function they must call, so that it's safe if they
4900 are copied into a subtype's __dict__ and the subtype has a different
4901 C function in its slot -- calling the method defined by the
4902 descriptor will call the C function that was used to create it,
4903 rather than the C function present in the slot when it is called.
4904 (This is important because a subtype may have a C function in the
4905 slot that calls the method from the dictionary, and we want to avoid
4906 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00004907
4908static int
4909add_operators(PyTypeObject *type)
4910{
4911 PyObject *dict = type->tp_dict;
4912 slotdef *p;
4913 PyObject *descr;
4914 void **ptr;
4915
4916 init_slotdefs();
4917 for (p = slotdefs; p->name; p++) {
4918 if (p->wrapper == NULL)
4919 continue;
4920 ptr = slotptr(type, p->offset);
4921 if (!ptr || !*ptr)
4922 continue;
4923 if (PyDict_GetItem(dict, p->name_strobj))
4924 continue;
4925 descr = PyDescr_NewWrapper(type, p, *ptr);
4926 if (descr == NULL)
4927 return -1;
4928 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
4929 return -1;
4930 Py_DECREF(descr);
4931 }
4932 if (type->tp_new != NULL) {
4933 if (add_tp_new_wrapper(type) < 0)
4934 return -1;
4935 }
4936 return 0;
4937}
4938
Guido van Rossum705f0f52001-08-24 16:47:00 +00004939
4940/* Cooperative 'super' */
4941
4942typedef struct {
4943 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00004944 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004945 PyObject *obj;
4946} superobject;
4947
Guido van Rossum6f799372001-09-20 20:46:19 +00004948static PyMemberDef super_members[] = {
4949 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
4950 "the class invoking super()"},
4951 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
4952 "the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004953 {0}
4954};
4955
Guido van Rossum705f0f52001-08-24 16:47:00 +00004956static void
4957super_dealloc(PyObject *self)
4958{
4959 superobject *su = (superobject *)self;
4960
Guido van Rossum048eb752001-10-02 21:24:57 +00004961 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00004962 Py_XDECREF(su->obj);
4963 Py_XDECREF(su->type);
4964 self->ob_type->tp_free(self);
4965}
4966
4967static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004968super_repr(PyObject *self)
4969{
4970 superobject *su = (superobject *)self;
4971
4972 if (su->obj)
4973 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00004974 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004975 su->type ? su->type->tp_name : "NULL",
4976 su->obj->ob_type->tp_name);
4977 else
4978 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00004979 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004980 su->type ? su->type->tp_name : "NULL");
4981}
4982
4983static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00004984super_getattro(PyObject *self, PyObject *name)
4985{
4986 superobject *su = (superobject *)self;
4987
4988 if (su->obj != NULL) {
Tim Petersa91e9642001-11-14 23:32:33 +00004989 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum155db9a2002-04-02 17:53:47 +00004990 PyTypeObject *starttype;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004991 descrgetfunc f;
4992 int i, n;
4993
Guido van Rossum155db9a2002-04-02 17:53:47 +00004994 starttype = su->obj->ob_type;
4995 mro = starttype->tp_mro;
4996
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004997 if (mro == NULL)
4998 n = 0;
4999 else {
5000 assert(PyTuple_Check(mro));
5001 n = PyTuple_GET_SIZE(mro);
5002 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005003 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00005004 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00005005 break;
5006 }
Guido van Rossume705ef12001-08-29 15:47:06 +00005007 if (i >= n && PyType_Check(su->obj)) {
Guido van Rossum155db9a2002-04-02 17:53:47 +00005008 starttype = (PyTypeObject *)(su->obj);
5009 mro = starttype->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005010 if (mro == NULL)
5011 n = 0;
5012 else {
5013 assert(PyTuple_Check(mro));
5014 n = PyTuple_GET_SIZE(mro);
5015 }
Guido van Rossume705ef12001-08-29 15:47:06 +00005016 for (i = 0; i < n; i++) {
5017 if ((PyObject *)(su->type) ==
5018 PyTuple_GET_ITEM(mro, i))
5019 break;
5020 }
Guido van Rossume705ef12001-08-29 15:47:06 +00005021 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005022 i++;
5023 res = NULL;
5024 for (; i < n; i++) {
5025 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00005026 if (PyType_Check(tmp))
5027 dict = ((PyTypeObject *)tmp)->tp_dict;
5028 else if (PyClass_Check(tmp))
5029 dict = ((PyClassObject *)tmp)->cl_dict;
5030 else
5031 continue;
5032 res = PyDict_GetItem(dict, name);
Guido van Rossum5b443c62001-12-03 15:38:28 +00005033 if (res != NULL && !PyDescr_IsData(res)) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00005034 Py_INCREF(res);
5035 f = res->ob_type->tp_descr_get;
5036 if (f != NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00005037 tmp = f(res, su->obj,
5038 (PyObject *)starttype);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005039 Py_DECREF(res);
5040 res = tmp;
5041 }
5042 return res;
5043 }
5044 }
5045 }
5046 return PyObject_GenericGetAttr(self, name);
5047}
5048
Guido van Rossum5b443c62001-12-03 15:38:28 +00005049static int
5050supercheck(PyTypeObject *type, PyObject *obj)
5051{
5052 if (!PyType_IsSubtype(obj->ob_type, type) &&
5053 !(PyType_Check(obj) &&
5054 PyType_IsSubtype((PyTypeObject *)obj, type))) {
5055 PyErr_SetString(PyExc_TypeError,
5056 "super(type, obj): "
5057 "obj must be an instance or subtype of type");
5058 return -1;
5059 }
5060 else
5061 return 0;
5062}
5063
Guido van Rossum705f0f52001-08-24 16:47:00 +00005064static PyObject *
5065super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5066{
5067 superobject *su = (superobject *)self;
5068 superobject *new;
5069
5070 if (obj == NULL || obj == Py_None || su->obj != NULL) {
5071 /* Not binding to an object, or already bound */
5072 Py_INCREF(self);
5073 return self;
5074 }
Guido van Rossum5b443c62001-12-03 15:38:28 +00005075 if (su->ob_type != &PySuper_Type)
5076 /* If su is an instance of a subclass of super,
5077 call its type */
5078 return PyObject_CallFunction((PyObject *)su->ob_type,
5079 "OO", su->type, obj);
5080 else {
5081 /* Inline the common case */
5082 if (supercheck(su->type, obj) < 0)
5083 return NULL;
5084 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
5085 NULL, NULL);
5086 if (new == NULL)
5087 return NULL;
5088 Py_INCREF(su->type);
5089 Py_INCREF(obj);
5090 new->type = su->type;
5091 new->obj = obj;
5092 return (PyObject *)new;
5093 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005094}
5095
5096static int
5097super_init(PyObject *self, PyObject *args, PyObject *kwds)
5098{
5099 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00005100 PyTypeObject *type;
5101 PyObject *obj = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005102
5103 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
5104 return -1;
5105 if (obj == Py_None)
5106 obj = NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005107 if (obj != NULL && supercheck(type, obj) < 0)
Guido van Rossum705f0f52001-08-24 16:47:00 +00005108 return -1;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005109 Py_INCREF(type);
5110 Py_XINCREF(obj);
5111 su->type = type;
5112 su->obj = obj;
5113 return 0;
5114}
5115
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005116PyDoc_STRVAR(super_doc,
Guido van Rossum705f0f52001-08-24 16:47:00 +00005117"super(type) -> unbound super object\n"
5118"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00005119"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00005120"Typical use to call a cooperative superclass method:\n"
5121"class C(B):\n"
5122" def meth(self, arg):\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005123" super(C, self).meth(arg)");
Guido van Rossum705f0f52001-08-24 16:47:00 +00005124
Guido van Rossum048eb752001-10-02 21:24:57 +00005125static int
5126super_traverse(PyObject *self, visitproc visit, void *arg)
5127{
5128 superobject *su = (superobject *)self;
5129 int err;
5130
5131#define VISIT(SLOT) \
5132 if (SLOT) { \
5133 err = visit((PyObject *)(SLOT), arg); \
5134 if (err) \
5135 return err; \
5136 }
5137
5138 VISIT(su->obj);
5139 VISIT(su->type);
5140
5141#undef VISIT
5142
5143 return 0;
5144}
5145
Guido van Rossum705f0f52001-08-24 16:47:00 +00005146PyTypeObject PySuper_Type = {
5147 PyObject_HEAD_INIT(&PyType_Type)
5148 0, /* ob_size */
5149 "super", /* tp_name */
5150 sizeof(superobject), /* tp_basicsize */
5151 0, /* tp_itemsize */
5152 /* methods */
5153 super_dealloc, /* tp_dealloc */
5154 0, /* tp_print */
5155 0, /* tp_getattr */
5156 0, /* tp_setattr */
5157 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005158 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005159 0, /* tp_as_number */
5160 0, /* tp_as_sequence */
5161 0, /* tp_as_mapping */
5162 0, /* tp_hash */
5163 0, /* tp_call */
5164 0, /* tp_str */
5165 super_getattro, /* tp_getattro */
5166 0, /* tp_setattro */
5167 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00005168 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
5169 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005170 super_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00005171 super_traverse, /* tp_traverse */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005172 0, /* tp_clear */
5173 0, /* tp_richcompare */
5174 0, /* tp_weaklistoffset */
5175 0, /* tp_iter */
5176 0, /* tp_iternext */
5177 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005178 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005179 0, /* tp_getset */
5180 0, /* tp_base */
5181 0, /* tp_dict */
5182 super_descr_get, /* tp_descr_get */
5183 0, /* tp_descr_set */
5184 0, /* tp_dictoffset */
5185 super_init, /* tp_init */
5186 PyType_GenericAlloc, /* tp_alloc */
5187 PyType_GenericNew, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00005188 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005189};