blob: e88f5f59248002182cd5d4151ec180c7789ce782 [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
Guido van Rossum373c7412003-01-07 13:41:37 +00001356/* Three variants on the subtype_getsets list. */
1357
1358static PyGetSetDef subtype_getsets_full[] = {
Guido van Rossumad47da02002-08-12 19:05:44 +00001359 {"__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 Rossum373c7412003-01-07 13:41:37 +00001366static PyGetSetDef subtype_getsets_dict_only[] = {
1367 {"__dict__", subtype_dict, subtype_setdict,
1368 PyDoc_STR("dictionary for instance variables (if defined)")},
1369 {0}
1370};
1371
1372static PyGetSetDef subtype_getsets_weakref_only[] = {
1373 {"__weakref__", subtype_getweakref, NULL,
1374 PyDoc_STR("list of weak references to the object (if defined)")},
1375 {0}
1376};
1377
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001378/* bozo: __getstate__ that raises TypeError */
1379
1380static PyObject *
1381bozo_func(PyObject *self, PyObject *args)
1382{
1383 PyErr_SetString(PyExc_TypeError,
1384 "a class that defines __slots__ without "
1385 "defining __getstate__ cannot be pickled");
1386 return NULL;
1387}
1388
Neal Norwitz93c1e232002-03-31 16:06:11 +00001389static PyMethodDef bozo_ml = {"__getstate__", bozo_func, METH_VARARGS};
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001390
1391static PyObject *bozo_obj = NULL;
1392
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001393static int
1394valid_identifier(PyObject *s)
1395{
Guido van Rossum03013a02002-07-16 14:30:28 +00001396 unsigned char *p;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001397 int i, n;
1398
1399 if (!PyString_Check(s)) {
1400 PyErr_SetString(PyExc_TypeError,
1401 "__slots__ must be strings");
1402 return 0;
1403 }
Guido van Rossum03013a02002-07-16 14:30:28 +00001404 p = (unsigned char *) PyString_AS_STRING(s);
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001405 n = PyString_GET_SIZE(s);
1406 /* We must reject an empty name. As a hack, we bump the
1407 length to 1 so that the loop will balk on the trailing \0. */
1408 if (n == 0)
1409 n = 1;
1410 for (i = 0; i < n; i++, p++) {
1411 if (!(i == 0 ? isalpha(*p) : isalnum(*p)) && *p != '_') {
1412 PyErr_SetString(PyExc_TypeError,
1413 "__slots__ must be identifiers");
1414 return 0;
1415 }
1416 }
1417 return 1;
1418}
1419
Martin v. Löwisd919a592002-10-14 21:07:28 +00001420#ifdef Py_USING_UNICODE
1421/* Replace Unicode objects in slots. */
1422
1423static PyObject *
1424_unicode_to_string(PyObject *slots, int nslots)
1425{
1426 PyObject *tmp = slots;
1427 PyObject *o, *o1;
1428 int i;
1429 intintargfunc copy = slots->ob_type->tp_as_sequence->sq_slice;
1430 for (i = 0; i < nslots; i++) {
1431 if (PyUnicode_Check(o = PyTuple_GET_ITEM(tmp, i))) {
1432 if (tmp == slots) {
1433 tmp = copy(slots, 0, PyTuple_GET_SIZE(slots));
1434 if (tmp == NULL)
1435 return NULL;
1436 }
1437 o1 = _PyUnicode_AsDefaultEncodedString
1438 (o, NULL);
1439 if (o1 == NULL) {
1440 Py_DECREF(tmp);
1441 return 0;
1442 }
1443 Py_INCREF(o1);
1444 Py_DECREF(o);
1445 PyTuple_SET_ITEM(tmp, i, o1);
1446 }
1447 }
1448 return tmp;
1449}
1450#endif
1451
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001452static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001453type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
1454{
1455 PyObject *name, *bases, *dict;
1456 static char *kwlist[] = {"name", "bases", "dict", 0};
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001457 PyObject *slots, *tmp, *newslots;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001458 PyTypeObject *type, *base, *tmptype, *winner;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001459 etype *et;
Guido van Rossum6f799372001-09-20 20:46:19 +00001460 PyMemberDef *mp;
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001461 int i, nbases, nslots, slotoffset, add_dict, add_weak;
Guido van Rossumad47da02002-08-12 19:05:44 +00001462 int j, may_add_dict, may_add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001463
Tim Peters3abca122001-10-27 19:37:48 +00001464 assert(args != NULL && PyTuple_Check(args));
1465 assert(kwds == NULL || PyDict_Check(kwds));
1466
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001467 /* Special case: type(x) should return x->ob_type */
Tim Peters3abca122001-10-27 19:37:48 +00001468 {
1469 const int nargs = PyTuple_GET_SIZE(args);
1470 const int nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
1471
1472 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
1473 PyObject *x = PyTuple_GET_ITEM(args, 0);
1474 Py_INCREF(x->ob_type);
1475 return (PyObject *) x->ob_type;
1476 }
1477
1478 /* SF bug 475327 -- if that didn't trigger, we need 3
1479 arguments. but PyArg_ParseTupleAndKeywords below may give
1480 a msg saying type() needs exactly 3. */
1481 if (nargs + nkwds != 3) {
1482 PyErr_SetString(PyExc_TypeError,
1483 "type() takes 1 or 3 arguments");
1484 return NULL;
1485 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001486 }
1487
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001488 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001489 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
1490 &name,
1491 &PyTuple_Type, &bases,
1492 &PyDict_Type, &dict))
1493 return NULL;
1494
1495 /* Determine the proper metatype to deal with this,
1496 and check for metatype conflicts while we're at it.
1497 Note that if some other metatype wins to contract,
1498 it's possible that its instances are not types. */
1499 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001500 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001501 for (i = 0; i < nbases; i++) {
1502 tmp = PyTuple_GET_ITEM(bases, i);
1503 tmptype = tmp->ob_type;
Tim Petersa91e9642001-11-14 23:32:33 +00001504 if (tmptype == &PyClass_Type)
1505 continue; /* Special case classic classes */
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001506 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001507 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001508 if (PyType_IsSubtype(tmptype, winner)) {
1509 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001510 continue;
1511 }
1512 PyErr_SetString(PyExc_TypeError,
1513 "metatype conflict among bases");
1514 return NULL;
1515 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001516 if (winner != metatype) {
1517 if (winner->tp_new != type_new) /* Pass it to the winner */
1518 return winner->tp_new(winner, args, kwds);
1519 metatype = winner;
1520 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001521
1522 /* Adjust for empty tuple bases */
1523 if (nbases == 0) {
1524 bases = Py_BuildValue("(O)", &PyBaseObject_Type);
1525 if (bases == NULL)
1526 return NULL;
1527 nbases = 1;
1528 }
1529 else
1530 Py_INCREF(bases);
1531
1532 /* XXX From here until type is allocated, "return NULL" leaks bases! */
1533
1534 /* Calculate best base, and check that all bases are type objects */
1535 base = best_base(bases);
1536 if (base == NULL)
1537 return NULL;
1538 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
1539 PyErr_Format(PyExc_TypeError,
1540 "type '%.100s' is not an acceptable base type",
1541 base->tp_name);
1542 return NULL;
1543 }
1544
Tim Peters6d6c1a32001-08-02 04:15:00 +00001545 /* Check for a __slots__ sequence variable in dict, and count it */
1546 slots = PyDict_GetItemString(dict, "__slots__");
1547 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +00001548 add_dict = 0;
1549 add_weak = 0;
Guido van Rossumad47da02002-08-12 19:05:44 +00001550 may_add_dict = base->tp_dictoffset == 0;
1551 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
1552 if (slots == NULL) {
1553 if (may_add_dict) {
1554 add_dict++;
1555 }
1556 if (may_add_weak) {
1557 add_weak++;
1558 }
1559 }
1560 else {
1561 /* Have slots */
1562
Tim Peters6d6c1a32001-08-02 04:15:00 +00001563 /* Make it into a tuple */
1564 if (PyString_Check(slots))
1565 slots = Py_BuildValue("(O)", slots);
1566 else
1567 slots = PySequence_Tuple(slots);
1568 if (slots == NULL)
1569 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00001570 assert(PyTuple_Check(slots));
1571
1572 /* Are slots allowed? */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001573 nslots = PyTuple_GET_SIZE(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +00001574 if (nslots > 0 && base->tp_itemsize != 0) {
1575 PyErr_Format(PyExc_TypeError,
1576 "nonempty __slots__ "
1577 "not supported for subtype of '%s'",
1578 base->tp_name);
Guido van Rossumad47da02002-08-12 19:05:44 +00001579 bad_slots:
1580 Py_DECREF(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +00001581 return NULL;
1582 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001583
Martin v. Löwisd919a592002-10-14 21:07:28 +00001584#ifdef Py_USING_UNICODE
1585 tmp = _unicode_to_string(slots, nslots);
Martin v. Löwis13b1a5c2002-10-14 21:11:34 +00001586 if (tmp != slots) {
1587 Py_DECREF(slots);
1588 slots = tmp;
1589 }
Martin v. Löwisd919a592002-10-14 21:07:28 +00001590 if (!tmp)
1591 return NULL;
1592#endif
Guido van Rossumad47da02002-08-12 19:05:44 +00001593 /* Check for valid slot names and two special cases */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001594 for (i = 0; i < nslots; i++) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001595 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
1596 char *s;
1597 if (!valid_identifier(tmp))
1598 goto bad_slots;
1599 assert(PyString_Check(tmp));
1600 s = PyString_AS_STRING(tmp);
1601 if (strcmp(s, "__dict__") == 0) {
1602 if (!may_add_dict || add_dict) {
1603 PyErr_SetString(PyExc_TypeError,
1604 "__dict__ slot disallowed: "
1605 "we already got one");
1606 goto bad_slots;
1607 }
1608 add_dict++;
1609 }
1610 if (strcmp(s, "__weakref__") == 0) {
1611 if (!may_add_weak || add_weak) {
1612 PyErr_SetString(PyExc_TypeError,
1613 "__weakref__ slot disallowed: "
1614 "either we already got one, "
1615 "or __itemsize__ != 0");
1616 goto bad_slots;
1617 }
1618 add_weak++;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001619 }
1620 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001621
Guido van Rossumad47da02002-08-12 19:05:44 +00001622 /* Copy slots into yet another tuple, demangling names */
1623 newslots = PyTuple_New(nslots - add_dict - add_weak);
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001624 if (newslots == NULL)
Guido van Rossumad47da02002-08-12 19:05:44 +00001625 goto bad_slots;
1626 for (i = j = 0; i < nslots; i++) {
1627 char *s;
Guido van Rossum8e829202002-08-16 03:47:49 +00001628 char buffer[256];
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001629 tmp = PyTuple_GET_ITEM(slots, i);
Guido van Rossumad47da02002-08-12 19:05:44 +00001630 s = PyString_AS_STRING(tmp);
1631 if ((add_dict && strcmp(s, "__dict__") == 0) ||
1632 (add_weak && strcmp(s, "__weakref__") == 0))
1633 continue;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001634 if (_Py_Mangle(PyString_AS_STRING(name),
Guido van Rossumad47da02002-08-12 19:05:44 +00001635 PyString_AS_STRING(tmp),
1636 buffer, sizeof(buffer)))
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001637 {
1638 tmp = PyString_FromString(buffer);
1639 } else {
1640 Py_INCREF(tmp);
1641 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001642 PyTuple_SET_ITEM(newslots, j, tmp);
1643 j++;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001644 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001645 assert(j == nslots - add_dict - add_weak);
1646 nslots = j;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001647 Py_DECREF(slots);
1648 slots = newslots;
1649
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001650 /* See if *this* class defines __getstate__ */
Guido van Rossumad47da02002-08-12 19:05:44 +00001651 if (PyDict_GetItemString(dict, "__getstate__") == NULL) {
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001652 /* If not, provide a bozo that raises TypeError */
1653 if (bozo_obj == NULL) {
1654 bozo_obj = PyCFunction_New(&bozo_ml, NULL);
Guido van Rossumad47da02002-08-12 19:05:44 +00001655 if (bozo_obj == NULL)
1656 goto bad_slots;
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001657 }
1658 if (PyDict_SetItemString(dict,
1659 "__getstate__",
Guido van Rossumad47da02002-08-12 19:05:44 +00001660 bozo_obj) < 0)
1661 {
1662 Py_DECREF(bozo_obj);
1663 goto bad_slots;
Guido van Rossum0628dcf2002-03-14 23:03:14 +00001664 }
1665 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001666
1667 /* Secondary bases may provide weakrefs or dict */
1668 if (nbases > 1 &&
1669 ((may_add_dict && !add_dict) ||
1670 (may_add_weak && !add_weak))) {
1671 for (i = 0; i < nbases; i++) {
1672 tmp = PyTuple_GET_ITEM(bases, i);
1673 if (tmp == (PyObject *)base)
1674 continue; /* Skip primary base */
1675 if (PyClass_Check(tmp)) {
1676 /* Classic base class provides both */
1677 if (may_add_dict && !add_dict)
1678 add_dict++;
1679 if (may_add_weak && !add_weak)
1680 add_weak++;
1681 break;
1682 }
1683 assert(PyType_Check(tmp));
1684 tmptype = (PyTypeObject *)tmp;
1685 if (may_add_dict && !add_dict &&
1686 tmptype->tp_dictoffset != 0)
1687 add_dict++;
1688 if (may_add_weak && !add_weak &&
1689 tmptype->tp_weaklistoffset != 0)
1690 add_weak++;
1691 if (may_add_dict && !add_dict)
1692 continue;
1693 if (may_add_weak && !add_weak)
1694 continue;
1695 /* Nothing more to check */
1696 break;
1697 }
1698 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001699 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001700
1701 /* XXX From here until type is safely allocated,
1702 "return NULL" may leak slots! */
1703
1704 /* Allocate the type object */
1705 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
Guido van Rossumad47da02002-08-12 19:05:44 +00001706 if (type == NULL) {
1707 Py_XDECREF(slots);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001708 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00001709 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001710
1711 /* Keep name and slots alive in the extended type object */
1712 et = (etype *)type;
1713 Py_INCREF(name);
1714 et->name = name;
1715 et->slots = slots;
1716
Guido van Rossumdc91b992001-08-08 22:26:22 +00001717 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001718 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
1719 Py_TPFLAGS_BASETYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00001720 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
1721 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00001722
1723 /* It's a new-style number unless it specifically inherits any
1724 old-style numeric behavior */
1725 if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
1726 (base->tp_as_number == NULL))
1727 type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
1728
1729 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001730 type->tp_as_number = &et->as_number;
1731 type->tp_as_sequence = &et->as_sequence;
1732 type->tp_as_mapping = &et->as_mapping;
1733 type->tp_as_buffer = &et->as_buffer;
1734 type->tp_name = PyString_AS_STRING(name);
1735
1736 /* Set tp_base and tp_bases */
1737 type->tp_bases = bases;
1738 Py_INCREF(base);
1739 type->tp_base = base;
1740
Guido van Rossum687ae002001-10-15 22:03:32 +00001741 /* Initialize tp_dict from passed-in dict */
1742 type->tp_dict = dict = PyDict_Copy(dict);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001743 if (dict == NULL) {
1744 Py_DECREF(type);
1745 return NULL;
1746 }
1747
Guido van Rossumc3542212001-08-16 09:18:56 +00001748 /* Set __module__ in the dict */
1749 if (PyDict_GetItemString(dict, "__module__") == NULL) {
1750 tmp = PyEval_GetGlobals();
1751 if (tmp != NULL) {
1752 tmp = PyDict_GetItemString(tmp, "__name__");
1753 if (tmp != NULL) {
1754 if (PyDict_SetItemString(dict, "__module__",
1755 tmp) < 0)
1756 return NULL;
1757 }
1758 }
1759 }
1760
Tim Peters2f93e282001-10-04 05:27:00 +00001761 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
Tim Peters24008312002-03-17 18:56:20 +00001762 and is a string. The __doc__ accessor will first look for tp_doc;
1763 if that fails, it will still look into __dict__.
Tim Peters2f93e282001-10-04 05:27:00 +00001764 */
1765 {
1766 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
1767 if (doc != NULL && PyString_Check(doc)) {
1768 const size_t n = (size_t)PyString_GET_SIZE(doc);
Tim Peters59f809d2001-10-04 05:43:02 +00001769 type->tp_doc = (char *)PyObject_MALLOC(n+1);
Tim Peters2f93e282001-10-04 05:27:00 +00001770 if (type->tp_doc == NULL) {
1771 Py_DECREF(type);
1772 return NULL;
1773 }
1774 memcpy(type->tp_doc, PyString_AS_STRING(doc), n+1);
1775 }
1776 }
1777
Tim Peters6d6c1a32001-08-02 04:15:00 +00001778 /* Special-case __new__: if it's a plain function,
1779 make it a static function */
1780 tmp = PyDict_GetItemString(dict, "__new__");
1781 if (tmp != NULL && PyFunction_Check(tmp)) {
1782 tmp = PyStaticMethod_New(tmp);
1783 if (tmp == NULL) {
1784 Py_DECREF(type);
1785 return NULL;
1786 }
1787 PyDict_SetItemString(dict, "__new__", tmp);
1788 Py_DECREF(tmp);
1789 }
1790
1791 /* Add descriptors for custom slots from __slots__, or for __dict__ */
1792 mp = et->members;
Neil Schemenauerc806c882001-08-29 23:54:54 +00001793 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001794 if (slots != NULL) {
1795 for (i = 0; i < nslots; i++, mp++) {
1796 mp->name = PyString_AS_STRING(
1797 PyTuple_GET_ITEM(slots, i));
Guido van Rossum64b206c2001-12-04 17:13:22 +00001798 mp->type = T_OBJECT_EX;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001799 mp->offset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +00001800 if (base->tp_weaklistoffset == 0 &&
Guido van Rossum64b206c2001-12-04 17:13:22 +00001801 strcmp(mp->name, "__weakref__") == 0) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001802 add_weak++;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001803 mp->type = T_OBJECT;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001804 mp->flags = READONLY;
Guido van Rossum9676b222001-08-17 20:32:36 +00001805 type->tp_weaklistoffset = slotoffset;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001806 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001807 slotoffset += sizeof(PyObject *);
1808 }
1809 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001810 if (add_dict) {
1811 if (base->tp_itemsize)
1812 type->tp_dictoffset = -(long)sizeof(PyObject *);
1813 else
1814 type->tp_dictoffset = slotoffset;
1815 slotoffset += sizeof(PyObject *);
1816 }
1817 if (add_weak) {
1818 assert(!base->tp_itemsize);
1819 type->tp_weaklistoffset = slotoffset;
1820 slotoffset += sizeof(PyObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001821 }
1822 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001823 type->tp_itemsize = base->tp_itemsize;
Guido van Rossum13d52f02001-08-10 21:24:08 +00001824 type->tp_members = et->members;
Guido van Rossum373c7412003-01-07 13:41:37 +00001825
1826 if (type->tp_weaklistoffset && type->tp_dictoffset)
1827 type->tp_getset = subtype_getsets_full;
1828 else if (type->tp_weaklistoffset && !type->tp_dictoffset)
1829 type->tp_getset = subtype_getsets_weakref_only;
1830 else if (!type->tp_weaklistoffset && type->tp_dictoffset)
1831 type->tp_getset = subtype_getsets_dict_only;
1832 else
1833 type->tp_getset = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001834
1835 /* Special case some slots */
1836 if (type->tp_dictoffset != 0 || nslots > 0) {
1837 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
1838 type->tp_getattro = PyObject_GenericGetAttr;
1839 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
1840 type->tp_setattro = PyObject_GenericSetAttr;
1841 }
1842 type->tp_dealloc = subtype_dealloc;
1843
Guido van Rossum9475a232001-10-05 20:51:39 +00001844 /* Enable GC unless there are really no instance variables possible */
1845 if (!(type->tp_basicsize == sizeof(PyObject) &&
1846 type->tp_itemsize == 0))
1847 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
1848
Tim Peters6d6c1a32001-08-02 04:15:00 +00001849 /* Always override allocation strategy to use regular heap */
1850 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00001851 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001852 type->tp_free = PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00001853 type->tp_traverse = subtype_traverse;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001854 type->tp_clear = subtype_clear;
Guido van Rossum048eb752001-10-02 21:24:57 +00001855 }
1856 else
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001857 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001858
1859 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001860 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001861 Py_DECREF(type);
1862 return NULL;
1863 }
1864
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001865 /* Put the proper slots in place */
1866 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00001867
Tim Peters6d6c1a32001-08-02 04:15:00 +00001868 return (PyObject *)type;
1869}
1870
1871/* Internal API to look for a name through the MRO.
1872 This returns a borrowed reference, and doesn't set an exception! */
1873PyObject *
1874_PyType_Lookup(PyTypeObject *type, PyObject *name)
1875{
1876 int i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00001877 PyObject *mro, *res, *base, *dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001878
Guido van Rossum687ae002001-10-15 22:03:32 +00001879 /* Look in tp_dict of types in MRO */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001880 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00001881
1882 /* If mro is NULL, the type is either not yet initialized
1883 by PyType_Ready(), or already cleared by type_clear().
1884 Either way the safest thing to do is to return NULL. */
1885 if (mro == NULL)
1886 return NULL;
1887
Tim Peters6d6c1a32001-08-02 04:15:00 +00001888 assert(PyTuple_Check(mro));
1889 n = PyTuple_GET_SIZE(mro);
1890 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001891 base = PyTuple_GET_ITEM(mro, i);
1892 if (PyClass_Check(base))
1893 dict = ((PyClassObject *)base)->cl_dict;
1894 else {
1895 assert(PyType_Check(base));
1896 dict = ((PyTypeObject *)base)->tp_dict;
1897 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001898 assert(dict && PyDict_Check(dict));
1899 res = PyDict_GetItem(dict, name);
1900 if (res != NULL)
1901 return res;
1902 }
1903 return NULL;
1904}
1905
1906/* This is similar to PyObject_GenericGetAttr(),
1907 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
1908static PyObject *
1909type_getattro(PyTypeObject *type, PyObject *name)
1910{
1911 PyTypeObject *metatype = type->ob_type;
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001912 PyObject *meta_attribute, *attribute;
1913 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001914
1915 /* Initialize this type (we'll assume the metatype is initialized) */
1916 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001917 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001918 return NULL;
1919 }
1920
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001921 /* No readable descriptor found yet */
1922 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00001923
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001924 /* Look for the attribute in the metatype */
1925 meta_attribute = _PyType_Lookup(metatype, name);
1926
1927 if (meta_attribute != NULL) {
1928 meta_get = meta_attribute->ob_type->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00001929
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001930 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
1931 /* Data descriptors implement tp_descr_set to intercept
1932 * writes. Assume the attribute is not overridden in
1933 * type's tp_dict (and bases): call the descriptor now.
1934 */
1935 return meta_get(meta_attribute, (PyObject *)type,
1936 (PyObject *)metatype);
1937 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001938 }
1939
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001940 /* No data descriptor found on metatype. Look in tp_dict of this
1941 * type and its bases */
1942 attribute = _PyType_Lookup(type, name);
1943 if (attribute != NULL) {
1944 /* Implement descriptor functionality, if any */
1945 descrgetfunc local_get = attribute->ob_type->tp_descr_get;
1946 if (local_get != NULL) {
1947 /* NULL 2nd argument indicates the descriptor was
1948 * found on the target object itself (or a base) */
1949 return local_get(attribute, (PyObject *)NULL,
1950 (PyObject *)type);
1951 }
Tim Peters34592512002-07-11 06:23:50 +00001952
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001953 Py_INCREF(attribute);
1954 return attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001955 }
1956
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001957 /* No attribute found in local __dict__ (or bases): use the
1958 * descriptor from the metatype, if any */
1959 if (meta_get != NULL)
1960 return meta_get(meta_attribute, (PyObject *)type,
1961 (PyObject *)metatype);
1962
1963 /* If an ordinary attribute was found on the metatype, return it now */
1964 if (meta_attribute != NULL) {
1965 Py_INCREF(meta_attribute);
1966 return meta_attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001967 }
1968
1969 /* Give up */
1970 PyErr_Format(PyExc_AttributeError,
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001971 "type object '%.50s' has no attribute '%.400s'",
1972 type->tp_name, PyString_AS_STRING(name));
Tim Peters6d6c1a32001-08-02 04:15:00 +00001973 return NULL;
1974}
1975
1976static int
1977type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
1978{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001979 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
1980 PyErr_Format(
1981 PyExc_TypeError,
1982 "can't set attributes of built-in/extension type '%s'",
1983 type->tp_name);
1984 return -1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001985 }
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00001986 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
1987 return -1;
1988 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001989}
1990
1991static void
1992type_dealloc(PyTypeObject *type)
1993{
1994 etype *et;
1995
1996 /* Assert this is a heap-allocated type object */
1997 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00001998 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00001999 PyObject_ClearWeakRefs((PyObject *)type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002000 et = (etype *)type;
2001 Py_XDECREF(type->tp_base);
2002 Py_XDECREF(type->tp_dict);
2003 Py_XDECREF(type->tp_bases);
2004 Py_XDECREF(type->tp_mro);
Guido van Rossum687ae002001-10-15 22:03:32 +00002005 Py_XDECREF(type->tp_cache);
Guido van Rossum1c450732001-10-08 15:18:27 +00002006 Py_XDECREF(type->tp_subclasses);
Neal Norwitzcee5ca02002-07-30 00:42:06 +00002007 PyObject_Free(type->tp_doc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002008 Py_XDECREF(et->name);
2009 Py_XDECREF(et->slots);
2010 type->ob_type->tp_free((PyObject *)type);
2011}
2012
Guido van Rossum1c450732001-10-08 15:18:27 +00002013static PyObject *
2014type_subclasses(PyTypeObject *type, PyObject *args_ignored)
2015{
2016 PyObject *list, *raw, *ref;
2017 int i, n;
2018
2019 list = PyList_New(0);
2020 if (list == NULL)
2021 return NULL;
2022 raw = type->tp_subclasses;
2023 if (raw == NULL)
2024 return list;
2025 assert(PyList_Check(raw));
2026 n = PyList_GET_SIZE(raw);
2027 for (i = 0; i < n; i++) {
2028 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00002029 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00002030 ref = PyWeakref_GET_OBJECT(ref);
2031 if (ref != Py_None) {
2032 if (PyList_Append(list, ref) < 0) {
2033 Py_DECREF(list);
2034 return NULL;
2035 }
2036 }
2037 }
2038 return list;
2039}
2040
Tim Peters6d6c1a32001-08-02 04:15:00 +00002041static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002042 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002043 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
Guido van Rossum1c450732001-10-08 15:18:27 +00002044 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002045 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002046 {0}
2047};
2048
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002049PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002050"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002051"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002052
Guido van Rossum048eb752001-10-02 21:24:57 +00002053static int
2054type_traverse(PyTypeObject *type, visitproc visit, void *arg)
2055{
Guido van Rossum048eb752001-10-02 21:24:57 +00002056 int err;
2057
Guido van Rossuma3862092002-06-10 15:24:42 +00002058 /* Because of type_is_gc(), the collector only calls this
2059 for heaptypes. */
2060 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002061
2062#define VISIT(SLOT) \
2063 if (SLOT) { \
2064 err = visit((PyObject *)(SLOT), arg); \
2065 if (err) \
2066 return err; \
2067 }
2068
2069 VISIT(type->tp_dict);
Guido van Rossum687ae002001-10-15 22:03:32 +00002070 VISIT(type->tp_cache);
Guido van Rossum048eb752001-10-02 21:24:57 +00002071 VISIT(type->tp_mro);
2072 VISIT(type->tp_bases);
2073 VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00002074
2075 /* There's no need to visit type->tp_subclasses or
2076 ((etype *)type)->slots, because they can't be involved
2077 in cycles; tp_subclasses is a list of weak references,
2078 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00002079
2080#undef VISIT
2081
2082 return 0;
2083}
2084
2085static int
2086type_clear(PyTypeObject *type)
2087{
Guido van Rossum048eb752001-10-02 21:24:57 +00002088 PyObject *tmp;
2089
Guido van Rossuma3862092002-06-10 15:24:42 +00002090 /* Because of type_is_gc(), the collector only calls this
2091 for heaptypes. */
2092 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002093
2094#define CLEAR(SLOT) \
2095 if (SLOT) { \
2096 tmp = (PyObject *)(SLOT); \
2097 SLOT = NULL; \
2098 Py_DECREF(tmp); \
2099 }
2100
Guido van Rossuma3862092002-06-10 15:24:42 +00002101 /* The only field we need to clear is tp_mro, which is part of a
2102 hard cycle (its first element is the class itself) that won't
2103 be broken otherwise (it's a tuple and tuples don't have a
2104 tp_clear handler). None of the other fields need to be
2105 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00002106
Guido van Rossuma3862092002-06-10 15:24:42 +00002107 tp_dict:
2108 It is a dict, so the collector will call its tp_clear.
2109
2110 tp_cache:
2111 Not used; if it were, it would be a dict.
2112
2113 tp_bases, tp_base:
2114 If these are involved in a cycle, there must be at least
2115 one other, mutable object in the cycle, e.g. a base
2116 class's dict; the cycle will be broken that way.
2117
2118 tp_subclasses:
2119 A list of weak references can't be part of a cycle; and
2120 lists have their own tp_clear.
2121
2122 slots (in etype):
2123 A tuple of strings can't be part of a cycle.
2124 */
2125
2126 CLEAR(type->tp_mro);
Tim Peters2f93e282001-10-04 05:27:00 +00002127
Guido van Rossum048eb752001-10-02 21:24:57 +00002128#undef CLEAR
2129
2130 return 0;
2131}
2132
2133static int
2134type_is_gc(PyTypeObject *type)
2135{
2136 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
2137}
2138
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002139PyTypeObject PyType_Type = {
2140 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002141 0, /* ob_size */
2142 "type", /* tp_name */
2143 sizeof(etype), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00002144 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002145 (destructor)type_dealloc, /* tp_dealloc */
2146 0, /* tp_print */
2147 0, /* tp_getattr */
2148 0, /* tp_setattr */
2149 type_compare, /* tp_compare */
2150 (reprfunc)type_repr, /* tp_repr */
2151 0, /* tp_as_number */
2152 0, /* tp_as_sequence */
2153 0, /* tp_as_mapping */
2154 (hashfunc)_Py_HashPointer, /* tp_hash */
2155 (ternaryfunc)type_call, /* tp_call */
2156 0, /* tp_str */
2157 (getattrofunc)type_getattro, /* tp_getattro */
2158 (setattrofunc)type_setattro, /* tp_setattro */
2159 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00002160 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2161 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002162 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00002163 (traverseproc)type_traverse, /* tp_traverse */
2164 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002165 0, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00002166 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002167 0, /* tp_iter */
2168 0, /* tp_iternext */
2169 type_methods, /* tp_methods */
2170 type_members, /* tp_members */
2171 type_getsets, /* tp_getset */
2172 0, /* tp_base */
2173 0, /* tp_dict */
2174 0, /* tp_descr_get */
2175 0, /* tp_descr_set */
2176 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
2177 0, /* tp_init */
2178 0, /* tp_alloc */
2179 type_new, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002180 PyObject_GC_Del, /* tp_free */
Guido van Rossum048eb752001-10-02 21:24:57 +00002181 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002182};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002183
2184
2185/* The base type of all types (eventually)... except itself. */
2186
2187static int
2188object_init(PyObject *self, PyObject *args, PyObject *kwds)
2189{
2190 return 0;
2191}
2192
2193static void
2194object_dealloc(PyObject *self)
2195{
2196 self->ob_type->tp_free(self);
2197}
2198
Guido van Rossum8e248182001-08-12 05:17:56 +00002199static PyObject *
2200object_repr(PyObject *self)
2201{
Guido van Rossum76e69632001-08-16 18:52:43 +00002202 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00002203 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002204
Guido van Rossum76e69632001-08-16 18:52:43 +00002205 type = self->ob_type;
2206 mod = type_module(type, NULL);
2207 if (mod == NULL)
2208 PyErr_Clear();
2209 else if (!PyString_Check(mod)) {
2210 Py_DECREF(mod);
2211 mod = NULL;
2212 }
2213 name = type_name(type, NULL);
2214 if (name == NULL)
2215 return NULL;
2216 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002217 rtn = PyString_FromFormat("<%s.%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002218 PyString_AS_STRING(mod),
2219 PyString_AS_STRING(name),
2220 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002221 else
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002222 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002223 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002224 Py_XDECREF(mod);
2225 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00002226 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002227}
2228
Guido van Rossumb8f63662001-08-15 23:57:02 +00002229static PyObject *
2230object_str(PyObject *self)
2231{
2232 unaryfunc f;
2233
2234 f = self->ob_type->tp_repr;
2235 if (f == NULL)
2236 f = object_repr;
2237 return f(self);
2238}
2239
Guido van Rossum8e248182001-08-12 05:17:56 +00002240static long
2241object_hash(PyObject *self)
2242{
2243 return _Py_HashPointer(self);
2244}
Guido van Rossum8e248182001-08-12 05:17:56 +00002245
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002246static PyObject *
2247object_get_class(PyObject *self, void *closure)
2248{
2249 Py_INCREF(self->ob_type);
2250 return (PyObject *)(self->ob_type);
2251}
2252
2253static int
2254equiv_structs(PyTypeObject *a, PyTypeObject *b)
2255{
2256 return a == b ||
2257 (a != NULL &&
2258 b != NULL &&
2259 a->tp_basicsize == b->tp_basicsize &&
2260 a->tp_itemsize == b->tp_itemsize &&
2261 a->tp_dictoffset == b->tp_dictoffset &&
2262 a->tp_weaklistoffset == b->tp_weaklistoffset &&
2263 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
2264 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
2265}
2266
2267static int
2268same_slots_added(PyTypeObject *a, PyTypeObject *b)
2269{
2270 PyTypeObject *base = a->tp_base;
2271 int size;
2272
2273 if (base != b->tp_base)
2274 return 0;
2275 if (equiv_structs(a, base) && equiv_structs(b, base))
2276 return 1;
2277 size = base->tp_basicsize;
2278 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
2279 size += sizeof(PyObject *);
2280 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
2281 size += sizeof(PyObject *);
2282 return size == a->tp_basicsize && size == b->tp_basicsize;
2283}
2284
2285static int
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002286compatible_for_assignment(PyTypeObject* old, PyTypeObject* new, char* attr)
2287{
2288 PyTypeObject *newbase, *oldbase;
2289
2290 if (new->tp_dealloc != old->tp_dealloc ||
2291 new->tp_free != old->tp_free)
2292 {
2293 PyErr_Format(PyExc_TypeError,
2294 "%s assignment: "
2295 "'%s' deallocator differs from '%s'",
2296 attr,
2297 new->tp_name,
2298 old->tp_name);
2299 return 0;
2300 }
2301 newbase = new;
2302 oldbase = old;
2303 while (equiv_structs(newbase, newbase->tp_base))
2304 newbase = newbase->tp_base;
2305 while (equiv_structs(oldbase, oldbase->tp_base))
2306 oldbase = oldbase->tp_base;
2307 if (newbase != oldbase &&
2308 (newbase->tp_base != oldbase->tp_base ||
2309 !same_slots_added(newbase, oldbase))) {
2310 PyErr_Format(PyExc_TypeError,
2311 "%s assignment: "
2312 "'%s' object layout differs from '%s'",
2313 attr,
2314 new->tp_name,
2315 old->tp_name);
2316 return 0;
2317 }
Tim Petersea7f75d2002-12-07 21:39:16 +00002318
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002319 return 1;
2320}
2321
2322static int
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002323object_set_class(PyObject *self, PyObject *value, void *closure)
2324{
2325 PyTypeObject *old = self->ob_type;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002326 PyTypeObject *new;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002327
Guido van Rossumb6b89422002-04-15 01:03:30 +00002328 if (value == NULL) {
2329 PyErr_SetString(PyExc_TypeError,
2330 "can't delete __class__ attribute");
2331 return -1;
2332 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002333 if (!PyType_Check(value)) {
2334 PyErr_Format(PyExc_TypeError,
2335 "__class__ must be set to new-style class, not '%s' object",
2336 value->ob_type->tp_name);
2337 return -1;
2338 }
2339 new = (PyTypeObject *)value;
Guido van Rossum40af8892002-08-10 05:42:07 +00002340 if (!(new->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
2341 !(old->tp_flags & Py_TPFLAGS_HEAPTYPE))
2342 {
2343 PyErr_Format(PyExc_TypeError,
2344 "__class__ assignment: only for heap types");
2345 return -1;
2346 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002347 if (compatible_for_assignment(new, old, "__class__")) {
2348 Py_INCREF(new);
2349 self->ob_type = new;
2350 Py_DECREF(old);
2351 return 0;
2352 }
2353 else {
Guido van Rossum9ee4b942002-05-24 18:47:47 +00002354 return -1;
2355 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002356}
2357
2358static PyGetSetDef object_getsets[] = {
2359 {"__class__", object_get_class, object_set_class,
Neal Norwitz858e34f2002-08-13 17:18:45 +00002360 PyDoc_STR("the object's class")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002361 {0}
2362};
2363
Guido van Rossum3926a632001-09-25 16:25:58 +00002364static PyObject *
2365object_reduce(PyObject *self, PyObject *args)
2366{
2367 /* Call copy_reg._reduce(self) */
2368 static PyObject *copy_reg_str;
2369 PyObject *copy_reg, *res;
2370
2371 if (!copy_reg_str) {
2372 copy_reg_str = PyString_InternFromString("copy_reg");
2373 if (copy_reg_str == NULL)
2374 return NULL;
2375 }
2376 copy_reg = PyImport_Import(copy_reg_str);
2377 if (!copy_reg)
2378 return NULL;
2379 res = PyEval_CallMethod(copy_reg, "_reduce", "(O)", self);
2380 Py_DECREF(copy_reg);
2381 return res;
2382}
2383
2384static PyMethodDef object_methods[] = {
Tim Petersea7f75d2002-12-07 21:39:16 +00002385 {"__reduce__", object_reduce, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002386 PyDoc_STR("helper for pickle")},
Guido van Rossum3926a632001-09-25 16:25:58 +00002387 {0}
2388};
2389
Tim Peters6d6c1a32001-08-02 04:15:00 +00002390PyTypeObject PyBaseObject_Type = {
2391 PyObject_HEAD_INIT(&PyType_Type)
2392 0, /* ob_size */
2393 "object", /* tp_name */
2394 sizeof(PyObject), /* tp_basicsize */
2395 0, /* tp_itemsize */
2396 (destructor)object_dealloc, /* tp_dealloc */
2397 0, /* tp_print */
2398 0, /* tp_getattr */
2399 0, /* tp_setattr */
2400 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002401 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002402 0, /* tp_as_number */
2403 0, /* tp_as_sequence */
2404 0, /* tp_as_mapping */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002405 object_hash, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002406 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002407 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002408 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002409 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002410 0, /* tp_as_buffer */
2411 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002412 PyDoc_STR("The most base type"), /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002413 0, /* tp_traverse */
2414 0, /* tp_clear */
2415 0, /* tp_richcompare */
2416 0, /* tp_weaklistoffset */
2417 0, /* tp_iter */
2418 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00002419 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002420 0, /* tp_members */
2421 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002422 0, /* tp_base */
2423 0, /* tp_dict */
2424 0, /* tp_descr_get */
2425 0, /* tp_descr_set */
2426 0, /* tp_dictoffset */
2427 object_init, /* tp_init */
2428 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossumc11e1922001-08-09 19:38:15 +00002429 PyType_GenericNew, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002430 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002431};
2432
2433
2434/* Initialize the __dict__ in a type object */
2435
Fred Drake7bf97152002-03-28 05:33:33 +00002436static PyObject *
2437create_specialmethod(PyMethodDef *meth, PyObject *(*func)(PyObject *))
2438{
2439 PyObject *cfunc;
2440 PyObject *result;
2441
2442 cfunc = PyCFunction_New(meth, NULL);
2443 if (cfunc == NULL)
2444 return NULL;
2445 result = func(cfunc);
2446 Py_DECREF(cfunc);
2447 return result;
2448}
2449
Tim Peters6d6c1a32001-08-02 04:15:00 +00002450static int
2451add_methods(PyTypeObject *type, PyMethodDef *meth)
2452{
Guido van Rossum687ae002001-10-15 22:03:32 +00002453 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002454
2455 for (; meth->ml_name != NULL; meth++) {
2456 PyObject *descr;
2457 if (PyDict_GetItemString(dict, meth->ml_name))
2458 continue;
Fred Drake7bf97152002-03-28 05:33:33 +00002459 if (meth->ml_flags & METH_CLASS) {
2460 if (meth->ml_flags & METH_STATIC) {
2461 PyErr_SetString(PyExc_ValueError,
2462 "method cannot be both class and static");
2463 return -1;
2464 }
Tim Petersbca1cbc2002-12-09 22:56:13 +00002465 descr = PyDescr_NewClassMethod(type, meth);
Fred Drake7bf97152002-03-28 05:33:33 +00002466 }
2467 else if (meth->ml_flags & METH_STATIC) {
2468 descr = create_specialmethod(meth, PyStaticMethod_New);
2469 }
2470 else {
2471 descr = PyDescr_NewMethod(type, meth);
2472 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002473 if (descr == NULL)
2474 return -1;
Fred Drake7bf97152002-03-28 05:33:33 +00002475 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002476 return -1;
2477 Py_DECREF(descr);
2478 }
2479 return 0;
2480}
2481
2482static int
Guido van Rossum6f799372001-09-20 20:46:19 +00002483add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002484{
Guido van Rossum687ae002001-10-15 22:03:32 +00002485 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002486
2487 for (; memb->name != NULL; memb++) {
2488 PyObject *descr;
2489 if (PyDict_GetItemString(dict, memb->name))
2490 continue;
2491 descr = PyDescr_NewMember(type, memb);
2492 if (descr == NULL)
2493 return -1;
2494 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
2495 return -1;
2496 Py_DECREF(descr);
2497 }
2498 return 0;
2499}
2500
2501static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00002502add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002503{
Guido van Rossum687ae002001-10-15 22:03:32 +00002504 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002505
2506 for (; gsp->name != NULL; gsp++) {
2507 PyObject *descr;
2508 if (PyDict_GetItemString(dict, gsp->name))
2509 continue;
2510 descr = PyDescr_NewGetSet(type, gsp);
2511
2512 if (descr == NULL)
2513 return -1;
2514 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
2515 return -1;
2516 Py_DECREF(descr);
2517 }
2518 return 0;
2519}
2520
Guido van Rossum13d52f02001-08-10 21:24:08 +00002521static void
2522inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002523{
2524 int oldsize, newsize;
2525
Guido van Rossum13d52f02001-08-10 21:24:08 +00002526 /* Special flag magic */
2527 if (!type->tp_as_buffer && base->tp_as_buffer) {
2528 type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
2529 type->tp_flags |=
2530 base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
2531 }
2532 if (!type->tp_as_sequence && base->tp_as_sequence) {
2533 type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
2534 type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
2535 }
2536 if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
2537 (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
2538 if ((!type->tp_as_number && base->tp_as_number) ||
2539 (!type->tp_as_sequence && base->tp_as_sequence)) {
2540 type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
2541 if (!type->tp_as_number && !type->tp_as_sequence) {
2542 type->tp_flags |= base->tp_flags &
2543 Py_TPFLAGS_HAVE_INPLACEOPS;
2544 }
2545 }
2546 /* Wow */
2547 }
2548 if (!type->tp_as_number && base->tp_as_number) {
2549 type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
2550 type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
2551 }
2552
2553 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00002554 oldsize = base->tp_basicsize;
2555 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
2556 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
2557 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00002558 (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
2559 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00002560 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00002561 if (type->tp_traverse == NULL)
2562 type->tp_traverse = base->tp_traverse;
2563 if (type->tp_clear == NULL)
2564 type->tp_clear = base->tp_clear;
2565 }
2566 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
Guido van Rossumf884b742001-12-17 17:14:22 +00002567 /* The condition below could use some explanation.
2568 It appears that tp_new is not inherited for static types
2569 whose base class is 'object'; this seems to be a precaution
2570 so that old extension types don't suddenly become
2571 callable (object.__new__ wouldn't insure the invariants
2572 that the extension type's own factory function ensures).
2573 Heap types, of course, are under our control, so they do
2574 inherit tp_new; static extension types that specify some
2575 other built-in type as the default are considered
2576 new-style-aware so they also inherit object.__new__. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002577 if (base != &PyBaseObject_Type ||
2578 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2579 if (type->tp_new == NULL)
2580 type->tp_new = base->tp_new;
2581 }
2582 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00002583 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00002584
2585 /* Copy other non-function slots */
2586
2587#undef COPYVAL
2588#define COPYVAL(SLOT) \
2589 if (type->SLOT == 0) type->SLOT = base->SLOT
2590
2591 COPYVAL(tp_itemsize);
2592 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
2593 COPYVAL(tp_weaklistoffset);
2594 }
2595 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2596 COPYVAL(tp_dictoffset);
2597 }
Guido van Rossum13d52f02001-08-10 21:24:08 +00002598}
2599
2600static void
2601inherit_slots(PyTypeObject *type, PyTypeObject *base)
2602{
2603 PyTypeObject *basebase;
2604
2605#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00002606#undef COPYSLOT
2607#undef COPYNUM
2608#undef COPYSEQ
2609#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00002610#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00002611
2612#define SLOTDEFINED(SLOT) \
2613 (base->SLOT != 0 && \
2614 (basebase == NULL || base->SLOT != basebase->SLOT))
2615
Tim Peters6d6c1a32001-08-02 04:15:00 +00002616#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00002617 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00002618
2619#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
2620#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
2621#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00002622#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002623
Guido van Rossum13d52f02001-08-10 21:24:08 +00002624 /* This won't inherit indirect slots (from tp_as_number etc.)
2625 if type doesn't provide the space. */
2626
2627 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
2628 basebase = base->tp_base;
2629 if (basebase->tp_as_number == NULL)
2630 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002631 COPYNUM(nb_add);
2632 COPYNUM(nb_subtract);
2633 COPYNUM(nb_multiply);
2634 COPYNUM(nb_divide);
2635 COPYNUM(nb_remainder);
2636 COPYNUM(nb_divmod);
2637 COPYNUM(nb_power);
2638 COPYNUM(nb_negative);
2639 COPYNUM(nb_positive);
2640 COPYNUM(nb_absolute);
2641 COPYNUM(nb_nonzero);
2642 COPYNUM(nb_invert);
2643 COPYNUM(nb_lshift);
2644 COPYNUM(nb_rshift);
2645 COPYNUM(nb_and);
2646 COPYNUM(nb_xor);
2647 COPYNUM(nb_or);
2648 COPYNUM(nb_coerce);
2649 COPYNUM(nb_int);
2650 COPYNUM(nb_long);
2651 COPYNUM(nb_float);
2652 COPYNUM(nb_oct);
2653 COPYNUM(nb_hex);
2654 COPYNUM(nb_inplace_add);
2655 COPYNUM(nb_inplace_subtract);
2656 COPYNUM(nb_inplace_multiply);
2657 COPYNUM(nb_inplace_divide);
2658 COPYNUM(nb_inplace_remainder);
2659 COPYNUM(nb_inplace_power);
2660 COPYNUM(nb_inplace_lshift);
2661 COPYNUM(nb_inplace_rshift);
2662 COPYNUM(nb_inplace_and);
2663 COPYNUM(nb_inplace_xor);
2664 COPYNUM(nb_inplace_or);
Guido van Rossumdc91b992001-08-08 22:26:22 +00002665 if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
2666 COPYNUM(nb_true_divide);
2667 COPYNUM(nb_floor_divide);
2668 COPYNUM(nb_inplace_true_divide);
2669 COPYNUM(nb_inplace_floor_divide);
2670 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002671 }
2672
Guido van Rossum13d52f02001-08-10 21:24:08 +00002673 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
2674 basebase = base->tp_base;
2675 if (basebase->tp_as_sequence == NULL)
2676 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002677 COPYSEQ(sq_length);
2678 COPYSEQ(sq_concat);
2679 COPYSEQ(sq_repeat);
2680 COPYSEQ(sq_item);
2681 COPYSEQ(sq_slice);
2682 COPYSEQ(sq_ass_item);
2683 COPYSEQ(sq_ass_slice);
2684 COPYSEQ(sq_contains);
2685 COPYSEQ(sq_inplace_concat);
2686 COPYSEQ(sq_inplace_repeat);
2687 }
2688
Guido van Rossum13d52f02001-08-10 21:24:08 +00002689 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
2690 basebase = base->tp_base;
2691 if (basebase->tp_as_mapping == NULL)
2692 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002693 COPYMAP(mp_length);
2694 COPYMAP(mp_subscript);
2695 COPYMAP(mp_ass_subscript);
2696 }
2697
Tim Petersfc57ccb2001-10-12 02:38:24 +00002698 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
2699 basebase = base->tp_base;
2700 if (basebase->tp_as_buffer == NULL)
2701 basebase = NULL;
2702 COPYBUF(bf_getreadbuffer);
2703 COPYBUF(bf_getwritebuffer);
2704 COPYBUF(bf_getsegcount);
2705 COPYBUF(bf_getcharbuffer);
2706 }
2707
Guido van Rossum13d52f02001-08-10 21:24:08 +00002708 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002709
Tim Peters6d6c1a32001-08-02 04:15:00 +00002710 COPYSLOT(tp_dealloc);
2711 COPYSLOT(tp_print);
2712 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
2713 type->tp_getattr = base->tp_getattr;
2714 type->tp_getattro = base->tp_getattro;
2715 }
2716 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
2717 type->tp_setattr = base->tp_setattr;
2718 type->tp_setattro = base->tp_setattro;
2719 }
2720 /* tp_compare see tp_richcompare */
2721 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00002722 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002723 COPYSLOT(tp_call);
2724 COPYSLOT(tp_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002725 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00002726 if (type->tp_compare == NULL &&
2727 type->tp_richcompare == NULL &&
2728 type->tp_hash == NULL)
2729 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00002730 type->tp_compare = base->tp_compare;
2731 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002732 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002733 }
2734 }
2735 else {
2736 COPYSLOT(tp_compare);
2737 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002738 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
2739 COPYSLOT(tp_iter);
2740 COPYSLOT(tp_iternext);
2741 }
2742 if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2743 COPYSLOT(tp_descr_get);
2744 COPYSLOT(tp_descr_set);
2745 COPYSLOT(tp_dictoffset);
2746 COPYSLOT(tp_init);
2747 COPYSLOT(tp_alloc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002748 COPYSLOT(tp_free);
Guido van Rossumcc8fe042002-04-05 17:10:16 +00002749 COPYSLOT(tp_is_gc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002750 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002751}
2752
Jeremy Hylton938ace62002-07-17 16:30:39 +00002753static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00002754
Tim Peters6d6c1a32001-08-02 04:15:00 +00002755int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002756PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002757{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002758 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002759 PyTypeObject *base;
2760 int i, n;
2761
Guido van Rossumcab05802002-06-10 15:29:03 +00002762 if (type->tp_flags & Py_TPFLAGS_READY) {
2763 assert(type->tp_dict != NULL);
Guido van Rossumd614f972001-08-10 17:39:49 +00002764 return 0;
Guido van Rossumcab05802002-06-10 15:29:03 +00002765 }
Guido van Rossumd614f972001-08-10 17:39:49 +00002766 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00002767
2768 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002769
2770 /* Initialize tp_base (defaults to BaseObject unless that's us) */
2771 base = type->tp_base;
2772 if (base == NULL && type != &PyBaseObject_Type)
2773 base = type->tp_base = &PyBaseObject_Type;
2774
Guido van Rossum323a9cf2002-08-14 17:26:30 +00002775 /* Initialize the base class */
2776 if (base && base->tp_dict == NULL) {
2777 if (PyType_Ready(base) < 0)
2778 goto error;
2779 }
2780
Guido van Rossum0986d822002-04-08 01:38:42 +00002781 /* Initialize ob_type if NULL. This means extensions that want to be
2782 compilable separately on Windows can call PyType_Ready() instead of
2783 initializing the ob_type field of their type objects. */
2784 if (type->ob_type == NULL)
2785 type->ob_type = base->ob_type;
2786
Tim Peters6d6c1a32001-08-02 04:15:00 +00002787 /* Initialize tp_bases */
2788 bases = type->tp_bases;
2789 if (bases == NULL) {
2790 if (base == NULL)
2791 bases = PyTuple_New(0);
2792 else
2793 bases = Py_BuildValue("(O)", base);
2794 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00002795 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002796 type->tp_bases = bases;
2797 }
2798
Guido van Rossum687ae002001-10-15 22:03:32 +00002799 /* Initialize tp_dict */
2800 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002801 if (dict == NULL) {
2802 dict = PyDict_New();
2803 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00002804 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00002805 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002806 }
2807
Guido van Rossum687ae002001-10-15 22:03:32 +00002808 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002809 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002810 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002811 if (type->tp_methods != NULL) {
2812 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002813 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002814 }
2815 if (type->tp_members != NULL) {
2816 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002817 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002818 }
2819 if (type->tp_getset != NULL) {
2820 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00002821 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002822 }
2823
Tim Peters6d6c1a32001-08-02 04:15:00 +00002824 /* Calculate method resolution order */
2825 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00002826 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002827 }
2828
Guido van Rossum13d52f02001-08-10 21:24:08 +00002829 /* Inherit special flags from dominant base */
2830 if (type->tp_base != NULL)
2831 inherit_special(type, type->tp_base);
2832
Tim Peters6d6c1a32001-08-02 04:15:00 +00002833 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002834 bases = type->tp_mro;
2835 assert(bases != NULL);
2836 assert(PyTuple_Check(bases));
2837 n = PyTuple_GET_SIZE(bases);
2838 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002839 PyObject *b = PyTuple_GET_ITEM(bases, i);
2840 if (PyType_Check(b))
2841 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002842 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002843
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00002844 /* if the type dictionary doesn't contain a __doc__, set it from
2845 the tp_doc slot.
2846 */
2847 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
2848 if (type->tp_doc != NULL) {
2849 PyObject *doc = PyString_FromString(type->tp_doc);
2850 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
2851 Py_DECREF(doc);
2852 } else {
Guido van Rossumd4641072002-04-03 02:13:37 +00002853 PyDict_SetItemString(type->tp_dict,
2854 "__doc__", Py_None);
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00002855 }
2856 }
2857
Guido van Rossum13d52f02001-08-10 21:24:08 +00002858 /* Some more special stuff */
2859 base = type->tp_base;
2860 if (base != NULL) {
2861 if (type->tp_as_number == NULL)
2862 type->tp_as_number = base->tp_as_number;
2863 if (type->tp_as_sequence == NULL)
2864 type->tp_as_sequence = base->tp_as_sequence;
2865 if (type->tp_as_mapping == NULL)
2866 type->tp_as_mapping = base->tp_as_mapping;
2867 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002868
Guido van Rossum1c450732001-10-08 15:18:27 +00002869 /* Link into each base class's list of subclasses */
2870 bases = type->tp_bases;
2871 n = PyTuple_GET_SIZE(bases);
2872 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002873 PyObject *b = PyTuple_GET_ITEM(bases, i);
2874 if (PyType_Check(b) &&
2875 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00002876 goto error;
2877 }
2878
Guido van Rossum13d52f02001-08-10 21:24:08 +00002879 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00002880 assert(type->tp_dict != NULL);
2881 type->tp_flags =
2882 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002883 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00002884
2885 error:
2886 type->tp_flags &= ~Py_TPFLAGS_READYING;
2887 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002888}
2889
Guido van Rossum1c450732001-10-08 15:18:27 +00002890static int
2891add_subclass(PyTypeObject *base, PyTypeObject *type)
2892{
2893 int i;
2894 PyObject *list, *ref, *new;
2895
2896 list = base->tp_subclasses;
2897 if (list == NULL) {
2898 base->tp_subclasses = list = PyList_New(0);
2899 if (list == NULL)
2900 return -1;
2901 }
2902 assert(PyList_Check(list));
2903 new = PyWeakref_NewRef((PyObject *)type, NULL);
2904 i = PyList_GET_SIZE(list);
2905 while (--i >= 0) {
2906 ref = PyList_GET_ITEM(list, i);
2907 assert(PyWeakref_CheckRef(ref));
Guido van Rossum3930bc32002-10-18 13:51:49 +00002908 if (PyWeakref_GET_OBJECT(ref) == Py_None)
2909 return PyList_SetItem(list, i, new);
Guido van Rossum1c450732001-10-08 15:18:27 +00002910 }
2911 i = PyList_Append(list, new);
2912 Py_DECREF(new);
2913 return i;
2914}
2915
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002916static void
2917remove_subclass(PyTypeObject *base, PyTypeObject *type)
2918{
2919 int i;
2920 PyObject *list, *ref;
2921
2922 list = base->tp_subclasses;
2923 if (list == NULL) {
2924 return;
2925 }
2926 assert(PyList_Check(list));
2927 i = PyList_GET_SIZE(list);
2928 while (--i >= 0) {
2929 ref = PyList_GET_ITEM(list, i);
2930 assert(PyWeakref_CheckRef(ref));
2931 if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
2932 /* this can't fail, right? */
2933 PySequence_DelItem(list, i);
2934 return;
2935 }
2936 }
2937}
Tim Peters6d6c1a32001-08-02 04:15:00 +00002938
2939/* Generic wrappers for overloadable 'operators' such as __getitem__ */
2940
2941/* There's a wrapper *function* for each distinct function typedef used
2942 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
2943 wrapper *table* for each distinct operation (e.g. __len__, __add__).
2944 Most tables have only one entry; the tables for binary operators have two
2945 entries, one regular and one with reversed arguments. */
2946
2947static PyObject *
2948wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
2949{
2950 inquiry func = (inquiry)wrapped;
2951 int res;
2952
2953 if (!PyArg_ParseTuple(args, ""))
2954 return NULL;
2955 res = (*func)(self);
2956 if (res == -1 && PyErr_Occurred())
2957 return NULL;
2958 return PyInt_FromLong((long)res);
2959}
2960
Tim Peters6d6c1a32001-08-02 04:15:00 +00002961static PyObject *
2962wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
2963{
2964 binaryfunc func = (binaryfunc)wrapped;
2965 PyObject *other;
2966
2967 if (!PyArg_ParseTuple(args, "O", &other))
2968 return NULL;
2969 return (*func)(self, other);
2970}
2971
2972static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002973wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
2974{
2975 binaryfunc func = (binaryfunc)wrapped;
2976 PyObject *other;
2977
2978 if (!PyArg_ParseTuple(args, "O", &other))
2979 return NULL;
2980 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002981 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002982 Py_INCREF(Py_NotImplemented);
2983 return Py_NotImplemented;
2984 }
2985 return (*func)(self, other);
2986}
2987
2988static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00002989wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
2990{
2991 binaryfunc func = (binaryfunc)wrapped;
2992 PyObject *other;
2993
2994 if (!PyArg_ParseTuple(args, "O", &other))
2995 return NULL;
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002996 if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002997 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00002998 Py_INCREF(Py_NotImplemented);
2999 return Py_NotImplemented;
3000 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003001 return (*func)(other, self);
3002}
3003
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003004static PyObject *
3005wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
3006{
3007 coercion func = (coercion)wrapped;
3008 PyObject *other, *res;
3009 int ok;
3010
3011 if (!PyArg_ParseTuple(args, "O", &other))
3012 return NULL;
3013 ok = func(&self, &other);
3014 if (ok < 0)
3015 return NULL;
3016 if (ok > 0) {
3017 Py_INCREF(Py_NotImplemented);
3018 return Py_NotImplemented;
3019 }
3020 res = PyTuple_New(2);
3021 if (res == NULL) {
3022 Py_DECREF(self);
3023 Py_DECREF(other);
3024 return NULL;
3025 }
3026 PyTuple_SET_ITEM(res, 0, self);
3027 PyTuple_SET_ITEM(res, 1, other);
3028 return res;
3029}
3030
Tim Peters6d6c1a32001-08-02 04:15:00 +00003031static PyObject *
3032wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
3033{
3034 ternaryfunc func = (ternaryfunc)wrapped;
3035 PyObject *other;
3036 PyObject *third = Py_None;
3037
3038 /* Note: This wrapper only works for __pow__() */
3039
3040 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
3041 return NULL;
3042 return (*func)(self, other, third);
3043}
3044
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00003045static PyObject *
3046wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3047{
3048 ternaryfunc func = (ternaryfunc)wrapped;
3049 PyObject *other;
3050 PyObject *third = Py_None;
3051
3052 /* Note: This wrapper only works for __pow__() */
3053
3054 if (!PyArg_ParseTuple(args, "O|O", &other, &third))
3055 return NULL;
3056 return (*func)(other, self, third);
3057}
3058
Tim Peters6d6c1a32001-08-02 04:15:00 +00003059static PyObject *
3060wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
3061{
3062 unaryfunc func = (unaryfunc)wrapped;
3063
3064 if (!PyArg_ParseTuple(args, ""))
3065 return NULL;
3066 return (*func)(self);
3067}
3068
Tim Peters6d6c1a32001-08-02 04:15:00 +00003069static PyObject *
3070wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
3071{
3072 intargfunc func = (intargfunc)wrapped;
3073 int i;
3074
3075 if (!PyArg_ParseTuple(args, "i", &i))
3076 return NULL;
3077 return (*func)(self, i);
3078}
3079
Guido van Rossum5d815f32001-08-17 21:57:47 +00003080static int
3081getindex(PyObject *self, PyObject *arg)
3082{
3083 int i;
3084
3085 i = PyInt_AsLong(arg);
3086 if (i == -1 && PyErr_Occurred())
3087 return -1;
3088 if (i < 0) {
3089 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
3090 if (sq && sq->sq_length) {
3091 int n = (*sq->sq_length)(self);
3092 if (n < 0)
3093 return -1;
3094 i += n;
3095 }
3096 }
3097 return i;
3098}
3099
3100static PyObject *
3101wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
3102{
3103 intargfunc func = (intargfunc)wrapped;
3104 PyObject *arg;
3105 int i;
3106
Guido van Rossumf4593e02001-10-03 12:09:30 +00003107 if (PyTuple_GET_SIZE(args) == 1) {
3108 arg = PyTuple_GET_ITEM(args, 0);
3109 i = getindex(self, arg);
3110 if (i == -1 && PyErr_Occurred())
3111 return NULL;
3112 return (*func)(self, i);
3113 }
3114 PyArg_ParseTuple(args, "O", &arg);
3115 assert(PyErr_Occurred());
3116 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003117}
3118
Tim Peters6d6c1a32001-08-02 04:15:00 +00003119static PyObject *
3120wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
3121{
3122 intintargfunc func = (intintargfunc)wrapped;
3123 int i, j;
3124
3125 if (!PyArg_ParseTuple(args, "ii", &i, &j))
3126 return NULL;
3127 return (*func)(self, i, j);
3128}
3129
Tim Peters6d6c1a32001-08-02 04:15:00 +00003130static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003131wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003132{
3133 intobjargproc func = (intobjargproc)wrapped;
3134 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003135 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003136
Guido van Rossum5d815f32001-08-17 21:57:47 +00003137 if (!PyArg_ParseTuple(args, "OO", &arg, &value))
3138 return NULL;
3139 i = getindex(self, arg);
3140 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00003141 return NULL;
3142 res = (*func)(self, i, value);
3143 if (res == -1 && PyErr_Occurred())
3144 return NULL;
3145 Py_INCREF(Py_None);
3146 return Py_None;
3147}
3148
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003149static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003150wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003151{
3152 intobjargproc func = (intobjargproc)wrapped;
3153 int i, res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003154 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003155
Guido van Rossum5d815f32001-08-17 21:57:47 +00003156 if (!PyArg_ParseTuple(args, "O", &arg))
3157 return NULL;
3158 i = getindex(self, arg);
3159 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003160 return NULL;
3161 res = (*func)(self, i, NULL);
3162 if (res == -1 && PyErr_Occurred())
3163 return NULL;
3164 Py_INCREF(Py_None);
3165 return Py_None;
3166}
3167
Tim Peters6d6c1a32001-08-02 04:15:00 +00003168static PyObject *
3169wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
3170{
3171 intintobjargproc func = (intintobjargproc)wrapped;
3172 int i, j, res;
3173 PyObject *value;
3174
3175 if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
3176 return NULL;
3177 res = (*func)(self, i, j, value);
3178 if (res == -1 && PyErr_Occurred())
3179 return NULL;
3180 Py_INCREF(Py_None);
3181 return Py_None;
3182}
3183
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003184static PyObject *
3185wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
3186{
3187 intintobjargproc func = (intintobjargproc)wrapped;
3188 int i, j, res;
3189
3190 if (!PyArg_ParseTuple(args, "ii", &i, &j))
3191 return NULL;
3192 res = (*func)(self, i, j, NULL);
3193 if (res == -1 && PyErr_Occurred())
3194 return NULL;
3195 Py_INCREF(Py_None);
3196 return Py_None;
3197}
3198
Tim Peters6d6c1a32001-08-02 04:15:00 +00003199/* XXX objobjproc is a misnomer; should be objargpred */
3200static PyObject *
3201wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
3202{
3203 objobjproc func = (objobjproc)wrapped;
3204 int res;
3205 PyObject *value;
3206
3207 if (!PyArg_ParseTuple(args, "O", &value))
3208 return NULL;
3209 res = (*func)(self, value);
3210 if (res == -1 && PyErr_Occurred())
3211 return NULL;
3212 return PyInt_FromLong((long)res);
3213}
3214
Tim Peters6d6c1a32001-08-02 04:15:00 +00003215static PyObject *
3216wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
3217{
3218 objobjargproc func = (objobjargproc)wrapped;
3219 int res;
3220 PyObject *key, *value;
3221
3222 if (!PyArg_ParseTuple(args, "OO", &key, &value))
3223 return NULL;
3224 res = (*func)(self, key, value);
3225 if (res == -1 && PyErr_Occurred())
3226 return NULL;
3227 Py_INCREF(Py_None);
3228 return Py_None;
3229}
3230
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003231static PyObject *
3232wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
3233{
3234 objobjargproc func = (objobjargproc)wrapped;
3235 int res;
3236 PyObject *key;
3237
3238 if (!PyArg_ParseTuple(args, "O", &key))
3239 return NULL;
3240 res = (*func)(self, key, NULL);
3241 if (res == -1 && PyErr_Occurred())
3242 return NULL;
3243 Py_INCREF(Py_None);
3244 return Py_None;
3245}
3246
Tim Peters6d6c1a32001-08-02 04:15:00 +00003247static PyObject *
3248wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
3249{
3250 cmpfunc func = (cmpfunc)wrapped;
3251 int res;
3252 PyObject *other;
3253
3254 if (!PyArg_ParseTuple(args, "O", &other))
3255 return NULL;
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00003256 if (other->ob_type->tp_compare != func &&
3257 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00003258 PyErr_Format(
3259 PyExc_TypeError,
3260 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
3261 self->ob_type->tp_name,
3262 self->ob_type->tp_name,
3263 other->ob_type->tp_name);
3264 return NULL;
3265 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003266 res = (*func)(self, other);
3267 if (PyErr_Occurred())
3268 return NULL;
3269 return PyInt_FromLong((long)res);
3270}
3271
Tim Peters6d6c1a32001-08-02 04:15:00 +00003272static PyObject *
3273wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
3274{
3275 setattrofunc func = (setattrofunc)wrapped;
3276 int res;
3277 PyObject *name, *value;
3278
3279 if (!PyArg_ParseTuple(args, "OO", &name, &value))
3280 return NULL;
3281 res = (*func)(self, name, value);
3282 if (res < 0)
3283 return NULL;
3284 Py_INCREF(Py_None);
3285 return Py_None;
3286}
3287
3288static PyObject *
3289wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
3290{
3291 setattrofunc func = (setattrofunc)wrapped;
3292 int res;
3293 PyObject *name;
3294
3295 if (!PyArg_ParseTuple(args, "O", &name))
3296 return NULL;
3297 res = (*func)(self, name, NULL);
3298 if (res < 0)
3299 return NULL;
3300 Py_INCREF(Py_None);
3301 return Py_None;
3302}
3303
Tim Peters6d6c1a32001-08-02 04:15:00 +00003304static PyObject *
3305wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
3306{
3307 hashfunc func = (hashfunc)wrapped;
3308 long res;
3309
3310 if (!PyArg_ParseTuple(args, ""))
3311 return NULL;
3312 res = (*func)(self);
3313 if (res == -1 && PyErr_Occurred())
3314 return NULL;
3315 return PyInt_FromLong(res);
3316}
3317
Tim Peters6d6c1a32001-08-02 04:15:00 +00003318static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00003319wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003320{
3321 ternaryfunc func = (ternaryfunc)wrapped;
3322
Guido van Rossumc8e56452001-10-22 00:43:43 +00003323 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003324}
3325
Tim Peters6d6c1a32001-08-02 04:15:00 +00003326static PyObject *
3327wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
3328{
3329 richcmpfunc func = (richcmpfunc)wrapped;
3330 PyObject *other;
3331
3332 if (!PyArg_ParseTuple(args, "O", &other))
3333 return NULL;
3334 return (*func)(self, other, op);
3335}
3336
3337#undef RICHCMP_WRAPPER
3338#define RICHCMP_WRAPPER(NAME, OP) \
3339static PyObject * \
3340richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
3341{ \
3342 return wrap_richcmpfunc(self, args, wrapped, OP); \
3343}
3344
Jack Jansen8e938b42001-08-08 15:29:49 +00003345RICHCMP_WRAPPER(lt, Py_LT)
3346RICHCMP_WRAPPER(le, Py_LE)
3347RICHCMP_WRAPPER(eq, Py_EQ)
3348RICHCMP_WRAPPER(ne, Py_NE)
3349RICHCMP_WRAPPER(gt, Py_GT)
3350RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003351
Tim Peters6d6c1a32001-08-02 04:15:00 +00003352static PyObject *
3353wrap_next(PyObject *self, PyObject *args, void *wrapped)
3354{
3355 unaryfunc func = (unaryfunc)wrapped;
3356 PyObject *res;
3357
3358 if (!PyArg_ParseTuple(args, ""))
3359 return NULL;
3360 res = (*func)(self);
3361 if (res == NULL && !PyErr_Occurred())
3362 PyErr_SetNone(PyExc_StopIteration);
3363 return res;
3364}
3365
Tim Peters6d6c1a32001-08-02 04:15:00 +00003366static PyObject *
3367wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
3368{
3369 descrgetfunc func = (descrgetfunc)wrapped;
3370 PyObject *obj;
3371 PyObject *type = NULL;
3372
3373 if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
3374 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003375 return (*func)(self, obj, type);
3376}
3377
Tim Peters6d6c1a32001-08-02 04:15:00 +00003378static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003379wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003380{
3381 descrsetfunc func = (descrsetfunc)wrapped;
3382 PyObject *obj, *value;
3383 int ret;
3384
3385 if (!PyArg_ParseTuple(args, "OO", &obj, &value))
3386 return NULL;
3387 ret = (*func)(self, obj, value);
3388 if (ret < 0)
3389 return NULL;
3390 Py_INCREF(Py_None);
3391 return Py_None;
3392}
Guido van Rossum22b13872002-08-06 21:41:44 +00003393
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00003394static PyObject *
3395wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
3396{
3397 descrsetfunc func = (descrsetfunc)wrapped;
3398 PyObject *obj;
3399 int ret;
3400
3401 if (!PyArg_ParseTuple(args, "O", &obj))
3402 return NULL;
3403 ret = (*func)(self, obj, NULL);
3404 if (ret < 0)
3405 return NULL;
3406 Py_INCREF(Py_None);
3407 return Py_None;
3408}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003409
Tim Peters6d6c1a32001-08-02 04:15:00 +00003410static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00003411wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003412{
3413 initproc func = (initproc)wrapped;
3414
Guido van Rossumc8e56452001-10-22 00:43:43 +00003415 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003416 return NULL;
3417 Py_INCREF(Py_None);
3418 return Py_None;
3419}
3420
Tim Peters6d6c1a32001-08-02 04:15:00 +00003421static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003422tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003423{
Barry Warsaw60f01882001-08-22 19:24:42 +00003424 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003425 PyObject *arg0, *res;
3426
3427 if (self == NULL || !PyType_Check(self))
3428 Py_FatalError("__new__() called with non-type 'self'");
3429 type = (PyTypeObject *)self;
3430 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003431 PyErr_Format(PyExc_TypeError,
3432 "%s.__new__(): not enough arguments",
3433 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003434 return NULL;
3435 }
3436 arg0 = PyTuple_GET_ITEM(args, 0);
3437 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003438 PyErr_Format(PyExc_TypeError,
3439 "%s.__new__(X): X is not a type object (%s)",
3440 type->tp_name,
3441 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003442 return NULL;
3443 }
3444 subtype = (PyTypeObject *)arg0;
3445 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003446 PyErr_Format(PyExc_TypeError,
3447 "%s.__new__(%s): %s is not a subtype of %s",
3448 type->tp_name,
3449 subtype->tp_name,
3450 subtype->tp_name,
3451 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003452 return NULL;
3453 }
Barry Warsaw60f01882001-08-22 19:24:42 +00003454
3455 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00003456 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00003457 most derived base that's not a heap type is this type. */
3458 staticbase = subtype;
3459 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
3460 staticbase = staticbase->tp_base;
Guido van Rossuma8c60f42001-09-14 19:43:36 +00003461 if (staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003462 PyErr_Format(PyExc_TypeError,
3463 "%s.__new__(%s) is not safe, use %s.__new__()",
3464 type->tp_name,
3465 subtype->tp_name,
3466 staticbase == NULL ? "?" : staticbase->tp_name);
3467 return NULL;
3468 }
3469
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003470 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
3471 if (args == NULL)
3472 return NULL;
3473 res = type->tp_new(subtype, args, kwds);
3474 Py_DECREF(args);
3475 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003476}
3477
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003478static struct PyMethodDef tp_new_methoddef[] = {
3479 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00003480 PyDoc_STR("T.__new__(S, ...) -> "
3481 "a new object with type S, a subtype of T")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00003482 {0}
3483};
3484
3485static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003486add_tp_new_wrapper(PyTypeObject *type)
3487{
Guido van Rossumf040ede2001-08-07 16:40:56 +00003488 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003489
Guido van Rossum687ae002001-10-15 22:03:32 +00003490 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00003491 return 0;
3492 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003493 if (func == NULL)
3494 return -1;
Guido van Rossum687ae002001-10-15 22:03:32 +00003495 return PyDict_SetItemString(type->tp_dict, "__new__", func);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003496}
3497
Guido van Rossumf040ede2001-08-07 16:40:56 +00003498/* Slot wrappers that call the corresponding __foo__ slot. See comments
3499 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003500
Guido van Rossumdc91b992001-08-08 22:26:22 +00003501#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003502static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003503FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003504{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00003505 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003506 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003507}
3508
Guido van Rossumdc91b992001-08-08 22:26:22 +00003509#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003510static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003511FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003512{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003513 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003514 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003515}
3516
Guido van Rossumcd118802003-01-06 22:57:47 +00003517/* Boolean helper for SLOT1BINFULL().
3518 right.__class__ is a nontrivial subclass of left.__class__. */
3519static int
3520method_is_overloaded(PyObject *left, PyObject *right, char *name)
3521{
3522 PyObject *a, *b;
3523 int ok;
3524
3525 b = PyObject_GetAttrString((PyObject *)(right->ob_type), name);
3526 if (b == NULL) {
3527 PyErr_Clear();
3528 /* If right doesn't have it, it's not overloaded */
3529 return 0;
3530 }
3531
3532 a = PyObject_GetAttrString((PyObject *)(left->ob_type), name);
3533 if (a == NULL) {
3534 PyErr_Clear();
3535 Py_DECREF(b);
3536 /* If right has it but left doesn't, it's overloaded */
3537 return 1;
3538 }
3539
3540 ok = PyObject_RichCompareBool(a, b, Py_NE);
3541 Py_DECREF(a);
3542 Py_DECREF(b);
3543 if (ok < 0) {
3544 PyErr_Clear();
3545 return 0;
3546 }
3547
3548 return ok;
3549}
3550
Guido van Rossumdc91b992001-08-08 22:26:22 +00003551
3552#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003553static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003554FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003555{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003556 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00003557 int do_other = self->ob_type != other->ob_type && \
3558 other->ob_type->tp_as_number != NULL && \
3559 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003560 if (self->ob_type->tp_as_number != NULL && \
3561 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
3562 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00003563 if (do_other && \
Guido van Rossumcd118802003-01-06 22:57:47 +00003564 PyType_IsSubtype(other->ob_type, self->ob_type) && \
3565 method_is_overloaded(self, other, ROPSTR)) { \
Guido van Rossum55f20992001-10-01 17:18:22 +00003566 r = call_maybe( \
3567 other, ROPSTR, &rcache_str, "(O)", self); \
3568 if (r != Py_NotImplemented) \
3569 return r; \
3570 Py_DECREF(r); \
3571 do_other = 0; \
3572 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00003573 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00003574 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003575 if (r != Py_NotImplemented || \
3576 other->ob_type == self->ob_type) \
3577 return r; \
3578 Py_DECREF(r); \
3579 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00003580 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00003581 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00003582 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003583 } \
3584 Py_INCREF(Py_NotImplemented); \
3585 return Py_NotImplemented; \
3586}
3587
3588#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
3589 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
3590
3591#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
3592static PyObject * \
3593FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
3594{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003595 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003596 return call_method(self, OPSTR, &cache_str, \
3597 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003598}
3599
3600static int
3601slot_sq_length(PyObject *self)
3602{
Guido van Rossum2730b132001-08-28 18:22:14 +00003603 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00003604 PyObject *res = call_method(self, "__len__", &len_str, "()");
Guido van Rossum26111622001-10-01 16:42:49 +00003605 int len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003606
3607 if (res == NULL)
3608 return -1;
Guido van Rossum26111622001-10-01 16:42:49 +00003609 len = (int)PyInt_AsLong(res);
3610 Py_DECREF(res);
Jeremy Hylton73a088e2002-07-25 16:43:29 +00003611 if (len == -1 && PyErr_Occurred())
3612 return -1;
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00003613 if (len < 0) {
Guido van Rossum22b13872002-08-06 21:41:44 +00003614 PyErr_SetString(PyExc_ValueError,
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00003615 "__len__() should return >= 0");
3616 return -1;
3617 }
Guido van Rossum26111622001-10-01 16:42:49 +00003618 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003619}
3620
Guido van Rossumdc91b992001-08-08 22:26:22 +00003621SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
3622SLOT1(slot_sq_repeat, "__mul__", int, "i")
Guido van Rossumf4593e02001-10-03 12:09:30 +00003623
3624/* Super-optimized version of slot_sq_item.
3625 Other slots could do the same... */
3626static PyObject *
3627slot_sq_item(PyObject *self, int i)
3628{
3629 static PyObject *getitem_str;
3630 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
3631 descrgetfunc f;
3632
3633 if (getitem_str == NULL) {
3634 getitem_str = PyString_InternFromString("__getitem__");
3635 if (getitem_str == NULL)
3636 return NULL;
3637 }
3638 func = _PyType_Lookup(self->ob_type, getitem_str);
3639 if (func != NULL) {
Guido van Rossumf4593e02001-10-03 12:09:30 +00003640 if ((f = func->ob_type->tp_descr_get) == NULL)
3641 Py_INCREF(func);
Neal Norwitz673cd822002-10-18 16:33:13 +00003642 else {
Guido van Rossumf4593e02001-10-03 12:09:30 +00003643 func = f(func, self, (PyObject *)(self->ob_type));
Neal Norwitz673cd822002-10-18 16:33:13 +00003644 if (func == NULL) {
3645 return NULL;
3646 }
3647 }
Guido van Rossumf4593e02001-10-03 12:09:30 +00003648 ival = PyInt_FromLong(i);
3649 if (ival != NULL) {
3650 args = PyTuple_New(1);
3651 if (args != NULL) {
3652 PyTuple_SET_ITEM(args, 0, ival);
3653 retval = PyObject_Call(func, args, NULL);
3654 Py_XDECREF(args);
3655 Py_XDECREF(func);
3656 return retval;
3657 }
3658 }
3659 }
3660 else {
3661 PyErr_SetObject(PyExc_AttributeError, getitem_str);
3662 }
3663 Py_XDECREF(args);
3664 Py_XDECREF(ival);
3665 Py_XDECREF(func);
3666 return NULL;
3667}
3668
Guido van Rossumdc91b992001-08-08 22:26:22 +00003669SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003670
3671static int
3672slot_sq_ass_item(PyObject *self, int index, PyObject *value)
3673{
3674 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003675 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003676
3677 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003678 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003679 "(i)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003680 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003681 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003682 "(iO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003683 if (res == NULL)
3684 return -1;
3685 Py_DECREF(res);
3686 return 0;
3687}
3688
3689static int
3690slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
3691{
3692 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003693 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003694
3695 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003696 res = call_method(self, "__delslice__", &delslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003697 "(ii)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003698 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003699 res = call_method(self, "__setslice__", &setslice_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003700 "(iiO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003701 if (res == NULL)
3702 return -1;
3703 Py_DECREF(res);
3704 return 0;
3705}
3706
3707static int
3708slot_sq_contains(PyObject *self, PyObject *value)
3709{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003710 PyObject *func, *res, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00003711 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003712
Guido van Rossum55f20992001-10-01 17:18:22 +00003713 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003714
3715 if (func != NULL) {
3716 args = Py_BuildValue("(O)", value);
3717 if (args == NULL)
3718 res = NULL;
3719 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003720 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003721 Py_DECREF(args);
3722 }
3723 Py_DECREF(func);
3724 if (res == NULL)
3725 return -1;
3726 return PyObject_IsTrue(res);
3727 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003728 else if (PyErr_Occurred())
3729 return -1;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003730 else {
Tim Peters16a77ad2001-09-08 04:00:12 +00003731 return _PySequence_IterSearch(self, value,
3732 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003733 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003734}
3735
Guido van Rossumdc91b992001-08-08 22:26:22 +00003736SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
3737SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003738
3739#define slot_mp_length slot_sq_length
3740
Guido van Rossumdc91b992001-08-08 22:26:22 +00003741SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003742
3743static int
3744slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
3745{
3746 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00003747 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003748
3749 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00003750 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003751 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003752 else
Guido van Rossum2730b132001-08-28 18:22:14 +00003753 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00003754 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003755 if (res == NULL)
3756 return -1;
3757 Py_DECREF(res);
3758 return 0;
3759}
3760
Guido van Rossumdc91b992001-08-08 22:26:22 +00003761SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
3762SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
3763SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
3764SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
3765SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
3766SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
3767
Jeremy Hylton938ace62002-07-17 16:30:39 +00003768static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00003769
3770SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
3771 nb_power, "__pow__", "__rpow__")
3772
3773static PyObject *
3774slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
3775{
Guido van Rossum2730b132001-08-28 18:22:14 +00003776 static PyObject *pow_str;
3777
Guido van Rossumdc91b992001-08-08 22:26:22 +00003778 if (modulus == Py_None)
3779 return slot_nb_power_binary(self, other);
Guido van Rossum23094982002-06-10 14:30:43 +00003780 /* Three-arg power doesn't use __rpow__. But ternary_op
3781 can call this when the second argument's type uses
3782 slot_nb_power, so check before calling self.__pow__. */
3783 if (self->ob_type->tp_as_number != NULL &&
3784 self->ob_type->tp_as_number->nb_power == slot_nb_power) {
3785 return call_method(self, "__pow__", &pow_str,
3786 "(OO)", other, modulus);
3787 }
3788 Py_INCREF(Py_NotImplemented);
3789 return Py_NotImplemented;
Guido van Rossumdc91b992001-08-08 22:26:22 +00003790}
3791
3792SLOT0(slot_nb_negative, "__neg__")
3793SLOT0(slot_nb_positive, "__pos__")
3794SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003795
3796static int
3797slot_nb_nonzero(PyObject *self)
3798{
Tim Petersea7f75d2002-12-07 21:39:16 +00003799 PyObject *func, *args;
Guido van Rossum60718732001-08-28 17:47:51 +00003800 static PyObject *nonzero_str, *len_str;
Tim Petersea7f75d2002-12-07 21:39:16 +00003801 int result = -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003802
Guido van Rossum55f20992001-10-01 17:18:22 +00003803 func = lookup_maybe(self, "__nonzero__", &nonzero_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003804 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00003805 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00003806 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00003807 func = lookup_maybe(self, "__len__", &len_str);
Tim Petersea7f75d2002-12-07 21:39:16 +00003808 if (func == NULL)
3809 return PyErr_Occurred() ? -1 : 1;
3810 }
3811 args = PyTuple_New(0);
3812 if (args != NULL) {
3813 PyObject *temp = PyObject_Call(func, args, NULL);
3814 Py_DECREF(args);
3815 if (temp != NULL) {
3816 result = PyObject_IsTrue(temp);
3817 Py_DECREF(temp);
Guido van Rossum55f20992001-10-01 17:18:22 +00003818 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00003819 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003820 Py_DECREF(func);
Tim Petersea7f75d2002-12-07 21:39:16 +00003821 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003822}
3823
Guido van Rossumdc91b992001-08-08 22:26:22 +00003824SLOT0(slot_nb_invert, "__invert__")
3825SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
3826SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
3827SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
3828SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
3829SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003830
3831static int
3832slot_nb_coerce(PyObject **a, PyObject **b)
3833{
3834 static PyObject *coerce_str;
3835 PyObject *self = *a, *other = *b;
3836
3837 if (self->ob_type->tp_as_number != NULL &&
3838 self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3839 PyObject *r;
3840 r = call_maybe(
3841 self, "__coerce__", &coerce_str, "(O)", other);
3842 if (r == NULL)
3843 return -1;
3844 if (r == Py_NotImplemented) {
3845 Py_DECREF(r);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003846 }
Guido van Rossum55f20992001-10-01 17:18:22 +00003847 else {
3848 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3849 PyErr_SetString(PyExc_TypeError,
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003850 "__coerce__ didn't return a 2-tuple");
Guido van Rossum55f20992001-10-01 17:18:22 +00003851 Py_DECREF(r);
3852 return -1;
3853 }
3854 *a = PyTuple_GET_ITEM(r, 0);
3855 Py_INCREF(*a);
3856 *b = PyTuple_GET_ITEM(r, 1);
3857 Py_INCREF(*b);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003858 Py_DECREF(r);
Guido van Rossum55f20992001-10-01 17:18:22 +00003859 return 0;
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003860 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003861 }
3862 if (other->ob_type->tp_as_number != NULL &&
3863 other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
3864 PyObject *r;
3865 r = call_maybe(
3866 other, "__coerce__", &coerce_str, "(O)", self);
3867 if (r == NULL)
3868 return -1;
3869 if (r == Py_NotImplemented) {
3870 Py_DECREF(r);
3871 return 1;
3872 }
3873 if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
3874 PyErr_SetString(PyExc_TypeError,
3875 "__coerce__ didn't return a 2-tuple");
3876 Py_DECREF(r);
3877 return -1;
3878 }
3879 *a = PyTuple_GET_ITEM(r, 1);
3880 Py_INCREF(*a);
3881 *b = PyTuple_GET_ITEM(r, 0);
3882 Py_INCREF(*b);
3883 Py_DECREF(r);
3884 return 0;
3885 }
3886 return 1;
3887}
3888
Guido van Rossumdc91b992001-08-08 22:26:22 +00003889SLOT0(slot_nb_int, "__int__")
3890SLOT0(slot_nb_long, "__long__")
3891SLOT0(slot_nb_float, "__float__")
3892SLOT0(slot_nb_oct, "__oct__")
3893SLOT0(slot_nb_hex, "__hex__")
3894SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
3895SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
3896SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
3897SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
3898SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003899SLOT1(slot_nb_inplace_power, "__ipow__", PyObject *, "O")
Guido van Rossumdc91b992001-08-08 22:26:22 +00003900SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
3901SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
3902SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
3903SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
3904SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
3905SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
3906 "__floordiv__", "__rfloordiv__")
3907SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
3908SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
3909SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00003910
3911static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00003912half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003913{
Guido van Rossumb8f63662001-08-15 23:57:02 +00003914 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003915 static PyObject *cmp_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003916 int c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003917
Guido van Rossum60718732001-08-28 17:47:51 +00003918 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003919 if (func == NULL) {
3920 PyErr_Clear();
3921 }
3922 else {
3923 args = Py_BuildValue("(O)", other);
3924 if (args == NULL)
3925 res = NULL;
3926 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00003927 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003928 Py_DECREF(args);
3929 }
Raymond Hettingerab5dae32002-06-24 13:08:16 +00003930 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003931 if (res != Py_NotImplemented) {
3932 if (res == NULL)
3933 return -2;
3934 c = PyInt_AsLong(res);
3935 Py_DECREF(res);
3936 if (c == -1 && PyErr_Occurred())
3937 return -2;
3938 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
3939 }
3940 Py_DECREF(res);
3941 }
3942 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003943}
3944
Guido van Rossumab3b0342001-09-18 20:38:53 +00003945/* This slot is published for the benefit of try_3way_compare in object.c */
3946int
3947_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00003948{
3949 int c;
3950
Guido van Rossumab3b0342001-09-18 20:38:53 +00003951 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003952 c = half_compare(self, other);
3953 if (c <= 1)
3954 return c;
3955 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00003956 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00003957 c = half_compare(other, self);
3958 if (c < -1)
3959 return -2;
3960 if (c <= 1)
3961 return -c;
3962 }
3963 return (void *)self < (void *)other ? -1 :
3964 (void *)self > (void *)other ? 1 : 0;
3965}
3966
3967static PyObject *
3968slot_tp_repr(PyObject *self)
3969{
3970 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003971 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003972
Guido van Rossum60718732001-08-28 17:47:51 +00003973 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003974 if (func != NULL) {
3975 res = PyEval_CallObject(func, NULL);
3976 Py_DECREF(func);
3977 return res;
3978 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00003979 PyErr_Clear();
3980 return PyString_FromFormat("<%s object at %p>",
3981 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003982}
3983
3984static PyObject *
3985slot_tp_str(PyObject *self)
3986{
3987 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00003988 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003989
Guido van Rossum60718732001-08-28 17:47:51 +00003990 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003991 if (func != NULL) {
3992 res = PyEval_CallObject(func, NULL);
3993 Py_DECREF(func);
3994 return res;
3995 }
3996 else {
3997 PyErr_Clear();
3998 return slot_tp_repr(self);
3999 }
4000}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004001
4002static long
4003slot_tp_hash(PyObject *self)
4004{
Tim Peters61ce0a92002-12-06 23:38:02 +00004005 PyObject *func;
Guido van Rossum60718732001-08-28 17:47:51 +00004006 static PyObject *hash_str, *eq_str, *cmp_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004007 long h;
4008
Guido van Rossum60718732001-08-28 17:47:51 +00004009 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004010
4011 if (func != NULL) {
Tim Peters61ce0a92002-12-06 23:38:02 +00004012 PyObject *res = PyEval_CallObject(func, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004013 Py_DECREF(func);
4014 if (res == NULL)
4015 return -1;
4016 h = PyInt_AsLong(res);
Tim Peters61ce0a92002-12-06 23:38:02 +00004017 Py_DECREF(res);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004018 }
4019 else {
4020 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004021 func = lookup_method(self, "__eq__", &eq_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004022 if (func == NULL) {
4023 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004024 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004025 }
4026 if (func != NULL) {
4027 Py_DECREF(func);
4028 PyErr_SetString(PyExc_TypeError, "unhashable type");
4029 return -1;
4030 }
4031 PyErr_Clear();
4032 h = _Py_HashPointer((void *)self);
4033 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004034 if (h == -1 && !PyErr_Occurred())
4035 h = -2;
4036 return h;
4037}
4038
4039static PyObject *
4040slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
4041{
Guido van Rossum60718732001-08-28 17:47:51 +00004042 static PyObject *call_str;
4043 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004044 PyObject *res;
4045
4046 if (meth == NULL)
4047 return NULL;
4048 res = PyObject_Call(meth, args, kwds);
4049 Py_DECREF(meth);
4050 return res;
4051}
4052
Guido van Rossum14a6f832001-10-17 13:59:09 +00004053/* There are two slot dispatch functions for tp_getattro.
4054
4055 - slot_tp_getattro() is used when __getattribute__ is overridden
4056 but no __getattr__ hook is present;
4057
4058 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
4059
Guido van Rossumc334df52002-04-04 23:44:47 +00004060 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
4061 detects the absence of __getattr__ and then installs the simpler slot if
4062 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00004063
Tim Peters6d6c1a32001-08-02 04:15:00 +00004064static PyObject *
4065slot_tp_getattro(PyObject *self, PyObject *name)
4066{
Guido van Rossum14a6f832001-10-17 13:59:09 +00004067 static PyObject *getattribute_str = NULL;
4068 return call_method(self, "__getattribute__", &getattribute_str,
4069 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004070}
4071
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004072static PyObject *
4073slot_tp_getattr_hook(PyObject *self, PyObject *name)
4074{
4075 PyTypeObject *tp = self->ob_type;
4076 PyObject *getattr, *getattribute, *res;
4077 static PyObject *getattribute_str = NULL;
4078 static PyObject *getattr_str = NULL;
4079
4080 if (getattr_str == NULL) {
4081 getattr_str = PyString_InternFromString("__getattr__");
4082 if (getattr_str == NULL)
4083 return NULL;
4084 }
4085 if (getattribute_str == NULL) {
4086 getattribute_str =
4087 PyString_InternFromString("__getattribute__");
4088 if (getattribute_str == NULL)
4089 return NULL;
4090 }
4091 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004092 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004093 /* No __getattr__ hook: use a simpler dispatcher */
4094 tp->tp_getattro = slot_tp_getattro;
4095 return slot_tp_getattro(self, name);
4096 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004097 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004098 if (getattribute == NULL ||
4099 (getattribute->ob_type == &PyWrapperDescr_Type &&
4100 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
4101 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004102 res = PyObject_GenericGetAttr(self, name);
4103 else
4104 res = PyObject_CallFunction(getattribute, "OO", self, name);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004105 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004106 PyErr_Clear();
4107 res = PyObject_CallFunction(getattr, "OO", self, name);
4108 }
4109 return res;
4110}
4111
Tim Peters6d6c1a32001-08-02 04:15:00 +00004112static int
4113slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
4114{
4115 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004116 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004117
4118 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004119 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004120 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004121 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004122 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004123 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004124 if (res == NULL)
4125 return -1;
4126 Py_DECREF(res);
4127 return 0;
4128}
4129
4130/* Map rich comparison operators to their __xx__ namesakes */
4131static char *name_op[] = {
4132 "__lt__",
4133 "__le__",
4134 "__eq__",
4135 "__ne__",
4136 "__gt__",
4137 "__ge__",
4138};
4139
4140static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00004141half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004142{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004143 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004144 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00004145
Guido van Rossum60718732001-08-28 17:47:51 +00004146 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004147 if (func == NULL) {
4148 PyErr_Clear();
4149 Py_INCREF(Py_NotImplemented);
4150 return Py_NotImplemented;
4151 }
4152 args = Py_BuildValue("(O)", other);
4153 if (args == NULL)
4154 res = NULL;
4155 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004156 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004157 Py_DECREF(args);
4158 }
4159 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004160 return res;
4161}
4162
Guido van Rossumb8f63662001-08-15 23:57:02 +00004163/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
4164static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
4165
4166static PyObject *
4167slot_tp_richcompare(PyObject *self, PyObject *other, int op)
4168{
4169 PyObject *res;
4170
4171 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
4172 res = half_richcompare(self, other, op);
4173 if (res != Py_NotImplemented)
4174 return res;
4175 Py_DECREF(res);
4176 }
4177 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
4178 res = half_richcompare(other, self, swapped_op[op]);
4179 if (res != Py_NotImplemented) {
4180 return res;
4181 }
4182 Py_DECREF(res);
4183 }
4184 Py_INCREF(Py_NotImplemented);
4185 return Py_NotImplemented;
4186}
4187
4188static PyObject *
4189slot_tp_iter(PyObject *self)
4190{
4191 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004192 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004193
Guido van Rossum60718732001-08-28 17:47:51 +00004194 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004195 if (func != NULL) {
Guido van Rossum84b2bed2002-08-16 17:01:09 +00004196 PyObject *args;
4197 args = res = PyTuple_New(0);
4198 if (args != NULL) {
4199 res = PyObject_Call(func, args, NULL);
4200 Py_DECREF(args);
4201 }
4202 Py_DECREF(func);
4203 return res;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004204 }
4205 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004206 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004207 if (func == NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00004208 PyErr_SetString(PyExc_TypeError,
4209 "iteration over non-sequence");
Guido van Rossumb8f63662001-08-15 23:57:02 +00004210 return NULL;
4211 }
4212 Py_DECREF(func);
4213 return PySeqIter_New(self);
4214}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004215
4216static PyObject *
4217slot_tp_iternext(PyObject *self)
4218{
Guido van Rossum2730b132001-08-28 18:22:14 +00004219 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00004220 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004221}
4222
Guido van Rossum1a493502001-08-17 16:47:50 +00004223static PyObject *
4224slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4225{
4226 PyTypeObject *tp = self->ob_type;
4227 PyObject *get;
4228 static PyObject *get_str = NULL;
4229
4230 if (get_str == NULL) {
4231 get_str = PyString_InternFromString("__get__");
4232 if (get_str == NULL)
4233 return NULL;
4234 }
4235 get = _PyType_Lookup(tp, get_str);
4236 if (get == NULL) {
4237 /* Avoid further slowdowns */
4238 if (tp->tp_descr_get == slot_tp_descr_get)
4239 tp->tp_descr_get = NULL;
4240 Py_INCREF(self);
4241 return self;
4242 }
Guido van Rossum2c252392001-08-24 10:13:31 +00004243 if (obj == NULL)
4244 obj = Py_None;
4245 if (type == NULL)
4246 type = Py_None;
Guido van Rossum1a493502001-08-17 16:47:50 +00004247 return PyObject_CallFunction(get, "OOO", self, obj, type);
4248}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004249
4250static int
4251slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
4252{
Guido van Rossum2c252392001-08-24 10:13:31 +00004253 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004254 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00004255
4256 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00004257 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004258 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00004259 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004260 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004261 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004262 if (res == NULL)
4263 return -1;
4264 Py_DECREF(res);
4265 return 0;
4266}
4267
4268static int
4269slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
4270{
Guido van Rossum60718732001-08-28 17:47:51 +00004271 static PyObject *init_str;
4272 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004273 PyObject *res;
4274
4275 if (meth == NULL)
4276 return -1;
4277 res = PyObject_Call(meth, args, kwds);
4278 Py_DECREF(meth);
4279 if (res == NULL)
4280 return -1;
4281 Py_DECREF(res);
4282 return 0;
4283}
4284
4285static PyObject *
4286slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4287{
Guido van Rossum7bed2132002-08-08 21:57:53 +00004288 static PyObject *new_str;
4289 PyObject *func;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004290 PyObject *newargs, *x;
4291 int i, n;
4292
Guido van Rossum7bed2132002-08-08 21:57:53 +00004293 if (new_str == NULL) {
4294 new_str = PyString_InternFromString("__new__");
4295 if (new_str == NULL)
4296 return NULL;
4297 }
4298 func = PyObject_GetAttr((PyObject *)type, new_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004299 if (func == NULL)
4300 return NULL;
4301 assert(PyTuple_Check(args));
4302 n = PyTuple_GET_SIZE(args);
4303 newargs = PyTuple_New(n+1);
4304 if (newargs == NULL)
4305 return NULL;
4306 Py_INCREF(type);
4307 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
4308 for (i = 0; i < n; i++) {
4309 x = PyTuple_GET_ITEM(args, i);
4310 Py_INCREF(x);
4311 PyTuple_SET_ITEM(newargs, i+1, x);
4312 }
4313 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00004314 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004315 Py_DECREF(func);
4316 return x;
4317}
4318
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004319static void
4320slot_tp_del(PyObject *self)
4321{
4322 static PyObject *del_str = NULL;
4323 PyObject *del, *res;
4324 PyObject *error_type, *error_value, *error_traceback;
4325
4326 /* Temporarily resurrect the object. */
4327 assert(self->ob_refcnt == 0);
4328 self->ob_refcnt = 1;
4329
4330 /* Save the current exception, if any. */
4331 PyErr_Fetch(&error_type, &error_value, &error_traceback);
4332
4333 /* Execute __del__ method, if any. */
4334 del = lookup_maybe(self, "__del__", &del_str);
4335 if (del != NULL) {
4336 res = PyEval_CallObject(del, NULL);
4337 if (res == NULL)
4338 PyErr_WriteUnraisable(del);
4339 else
4340 Py_DECREF(res);
4341 Py_DECREF(del);
4342 }
4343
4344 /* Restore the saved exception. */
4345 PyErr_Restore(error_type, error_value, error_traceback);
4346
4347 /* Undo the temporary resurrection; can't use DECREF here, it would
4348 * cause a recursive call.
4349 */
4350 assert(self->ob_refcnt > 0);
4351 if (--self->ob_refcnt == 0)
4352 return; /* this is the normal path out */
4353
4354 /* __del__ resurrected it! Make it look like the original Py_DECREF
4355 * never happened.
4356 */
4357 {
4358 int refcnt = self->ob_refcnt;
4359 _Py_NewReference(self);
4360 self->ob_refcnt = refcnt;
4361 }
4362 assert(!PyType_IS_GC(self->ob_type) ||
4363 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
4364 /* If Py_REF_DEBUG, the original decref dropped _Py_RefTotal, but
4365 * _Py_NewReference bumped it again, so that's a wash.
4366 * If Py_TRACE_REFS, _Py_NewReference re-added self to the object
4367 * chain, so no more to do there either.
4368 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
4369 * _Py_NewReference bumped tp_allocs: both of those need to be
4370 * undone.
4371 */
4372#ifdef COUNT_ALLOCS
4373 --self->ob_type->tp_frees;
4374 --self->ob_type->tp_allocs;
4375#endif
4376}
4377
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004378
4379/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
4380 functions. The offsets here are relative to the 'etype' structure, which
4381 incorporates the additional structures used for numbers, sequences and
4382 mappings. Note that multiple names may map to the same slot (e.g. __eq__,
4383 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00004384 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
4385 terminated with an all-zero entry. (This table is further initialized and
4386 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004387
Guido van Rossum6d204072001-10-21 00:44:31 +00004388typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004389
4390#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00004391#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004392#undef ETSLOT
4393#undef SQSLOT
4394#undef MPSLOT
4395#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00004396#undef UNSLOT
4397#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004398#undef BINSLOT
4399#undef RBINSLOT
4400
Guido van Rossum6d204072001-10-21 00:44:31 +00004401#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004402 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
4403 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00004404#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
4405 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004406 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00004407#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004408 {NAME, offsetof(etype, SLOT), (void *)(FUNCTION), WRAPPER, \
4409 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00004410#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4411 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
4412#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4413 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
4414#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4415 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
4416#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4417 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
4418 "x." NAME "() <==> " DOC)
4419#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4420 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
4421 "x." NAME "(y) <==> x" DOC "y")
4422#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
4423 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
4424 "x." NAME "(y) <==> x" DOC "y")
4425#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
4426 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
4427 "x." NAME "(y) <==> y" DOC "x")
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004428
4429static slotdef slotdefs[] = {
Guido van Rossum6d204072001-10-21 00:44:31 +00004430 SQSLOT("__len__", sq_length, slot_sq_length, wrap_inquiry,
4431 "x.__len__() <==> len(x)"),
4432 SQSLOT("__add__", sq_concat, slot_sq_concat, wrap_binaryfunc,
4433 "x.__add__(y) <==> x+y"),
4434 SQSLOT("__mul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
4435 "x.__mul__(n) <==> x*n"),
4436 SQSLOT("__rmul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
4437 "x.__rmul__(n) <==> n*x"),
4438 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
4439 "x.__getitem__(y) <==> x[y]"),
4440 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_intintargfunc,
4441 "x.__getslice__(i, j) <==> x[i:j]"),
4442 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
4443 "x.__setitem__(i, y) <==> x[i]=y"),
4444 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
4445 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004446 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Guido van Rossum6d204072001-10-21 00:44:31 +00004447 wrap_intintobjargproc,
4448 "x.__setslice__(i, j, y) <==> x[i:j]=y"),
4449 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
4450 "x.__delslice__(i, j) <==> del x[i:j]"),
4451 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
4452 "x.__contains__(y) <==> y in x"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004453 SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat,
Guido van Rossum6d204072001-10-21 00:44:31 +00004454 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004455 SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat,
Guido van Rossum6d204072001-10-21 00:44:31 +00004456 wrap_intargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004457
Guido van Rossum6d204072001-10-21 00:44:31 +00004458 MPSLOT("__len__", mp_length, slot_mp_length, wrap_inquiry,
4459 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00004460 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004461 wrap_binaryfunc,
4462 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004463 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004464 wrap_objobjargproc,
4465 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004466 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004467 wrap_delitem,
4468 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004469
Guido van Rossum6d204072001-10-21 00:44:31 +00004470 BINSLOT("__add__", nb_add, slot_nb_add,
4471 "+"),
4472 RBINSLOT("__radd__", nb_add, slot_nb_add,
4473 "+"),
4474 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
4475 "-"),
4476 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
4477 "-"),
4478 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
4479 "*"),
4480 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
4481 "*"),
4482 BINSLOT("__div__", nb_divide, slot_nb_divide,
4483 "/"),
4484 RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
4485 "/"),
4486 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
4487 "%"),
4488 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
4489 "%"),
4490 BINSLOT("__divmod__", nb_divmod, slot_nb_divmod,
4491 "divmod(x, y)"),
4492 RBINSLOT("__rdivmod__", nb_divmod, slot_nb_divmod,
4493 "divmod(y, x)"),
4494 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
4495 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
4496 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
4497 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
4498 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
4499 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
4500 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
4501 "abs(x)"),
Guido van Rossumdfce3bf2002-03-10 14:11:16 +00004502 UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquiry,
Guido van Rossum6d204072001-10-21 00:44:31 +00004503 "x != 0"),
4504 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
4505 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
4506 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
4507 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
4508 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
4509 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
4510 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
4511 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
4512 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
4513 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
4514 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
4515 NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
4516 "x.__coerce__(y) <==> coerce(x, y)"),
4517 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
4518 "int(x)"),
4519 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
4520 "long(x)"),
4521 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
4522 "float(x)"),
4523 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
4524 "oct(x)"),
4525 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
4526 "hex(x)"),
4527 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
4528 wrap_binaryfunc, "+"),
4529 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
4530 wrap_binaryfunc, "-"),
4531 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
4532 wrap_binaryfunc, "*"),
4533 IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
4534 wrap_binaryfunc, "/"),
4535 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
4536 wrap_binaryfunc, "%"),
4537 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
Guido van Rossum6e5680f2002-10-15 01:01:53 +00004538 wrap_binaryfunc, "**"),
Guido van Rossum6d204072001-10-21 00:44:31 +00004539 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
4540 wrap_binaryfunc, "<<"),
4541 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
4542 wrap_binaryfunc, ">>"),
4543 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
4544 wrap_binaryfunc, "&"),
4545 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
4546 wrap_binaryfunc, "^"),
4547 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
4548 wrap_binaryfunc, "|"),
4549 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
4550 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
4551 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
4552 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
4553 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
4554 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
4555 IBSLOT("__itruediv__", nb_inplace_true_divide,
4556 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004557
Guido van Rossum6d204072001-10-21 00:44:31 +00004558 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
4559 "x.__str__() <==> str(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00004560 TPSLOT("__str__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00004561 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
4562 "x.__repr__() <==> repr(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00004563 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00004564 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
4565 "x.__cmp__(y) <==> cmp(x,y)"),
4566 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
4567 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00004568 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
4569 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004570 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00004571 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
4572 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
4573 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
4574 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
4575 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
4576 "x.__setattr__('name', value) <==> x.name = value"),
4577 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
4578 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
4579 "x.__delattr__('name') <==> del x.name"),
4580 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
4581 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
4582 "x.__lt__(y) <==> x<y"),
4583 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
4584 "x.__le__(y) <==> x<=y"),
4585 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
4586 "x.__eq__(y) <==> x==y"),
4587 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
4588 "x.__ne__(y) <==> x!=y"),
4589 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
4590 "x.__gt__(y) <==> x>y"),
4591 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
4592 "x.__ge__(y) <==> x>=y"),
4593 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
4594 "x.__iter__() <==> iter(x)"),
4595 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
4596 "x.next() -> the next value, or raise StopIteration"),
4597 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
4598 "descr.__get__(obj[, type]) -> value"),
4599 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
4600 "descr.__set__(obj, value)"),
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004601 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
4602 wrap_descr_delete, "descr.__delete__(obj)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00004603 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00004604 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00004605 "see x.__class__.__doc__ for signature",
4606 PyWrapperFlag_KEYWORDS),
4607 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004608 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004609 {NULL}
4610};
4611
Guido van Rossumc334df52002-04-04 23:44:47 +00004612/* Given a type pointer and an offset gotten from a slotdef entry, return a
4613 pointer to the actual slot. This is not quite the same as simply adding
4614 the offset to the type pointer, since it takes care to indirect through the
4615 proper indirection pointer (as_buffer, etc.); it returns NULL if the
4616 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004617static void **
4618slotptr(PyTypeObject *type, int offset)
4619{
4620 char *ptr;
4621
Guido van Rossum09638c12002-06-13 19:17:46 +00004622 /* Note: this depends on the order of the members of etype! */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004623 assert(offset >= 0);
4624 assert(offset < offsetof(etype, as_buffer));
Guido van Rossum09638c12002-06-13 19:17:46 +00004625 if (offset >= offsetof(etype, as_sequence)) {
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004626 ptr = (void *)type->tp_as_sequence;
4627 offset -= offsetof(etype, as_sequence);
4628 }
Guido van Rossum09638c12002-06-13 19:17:46 +00004629 else if (offset >= offsetof(etype, as_mapping)) {
4630 ptr = (void *)type->tp_as_mapping;
4631 offset -= offsetof(etype, as_mapping);
4632 }
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004633 else if (offset >= offsetof(etype, as_number)) {
4634 ptr = (void *)type->tp_as_number;
4635 offset -= offsetof(etype, as_number);
4636 }
4637 else {
4638 ptr = (void *)type;
4639 }
4640 if (ptr != NULL)
4641 ptr += offset;
4642 return (void **)ptr;
4643}
Guido van Rossumf040ede2001-08-07 16:40:56 +00004644
Guido van Rossumc334df52002-04-04 23:44:47 +00004645/* Length of array of slotdef pointers used to store slots with the
4646 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
4647 the same __name__, for any __name__. Since that's a static property, it is
4648 appropriate to declare fixed-size arrays for this. */
4649#define MAX_EQUIV 10
4650
4651/* Return a slot pointer for a given name, but ONLY if the attribute has
4652 exactly one slot function. The name must be an interned string. */
4653static void **
4654resolve_slotdups(PyTypeObject *type, PyObject *name)
4655{
4656 /* XXX Maybe this could be optimized more -- but is it worth it? */
4657
4658 /* pname and ptrs act as a little cache */
4659 static PyObject *pname;
4660 static slotdef *ptrs[MAX_EQUIV];
4661 slotdef *p, **pp;
4662 void **res, **ptr;
4663
4664 if (pname != name) {
4665 /* Collect all slotdefs that match name into ptrs. */
4666 pname = name;
4667 pp = ptrs;
4668 for (p = slotdefs; p->name_strobj; p++) {
4669 if (p->name_strobj == name)
4670 *pp++ = p;
4671 }
4672 *pp = NULL;
4673 }
4674
4675 /* Look in all matching slots of the type; if exactly one of these has
4676 a filled-in slot, return its value. Otherwise return NULL. */
4677 res = NULL;
4678 for (pp = ptrs; *pp; pp++) {
4679 ptr = slotptr(type, (*pp)->offset);
4680 if (ptr == NULL || *ptr == NULL)
4681 continue;
4682 if (res != NULL)
4683 return NULL;
4684 res = ptr;
4685 }
4686 return res;
4687}
4688
4689/* Common code for update_these_slots() and fixup_slot_dispatchers(). This
4690 does some incredibly complex thinking and then sticks something into the
4691 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
4692 interests, and then stores a generic wrapper or a specific function into
4693 the slot.) Return a pointer to the next slotdef with a different offset,
4694 because that's convenient for fixup_slot_dispatchers(). */
4695static slotdef *
4696update_one_slot(PyTypeObject *type, slotdef *p)
4697{
4698 PyObject *descr;
4699 PyWrapperDescrObject *d;
4700 void *generic = NULL, *specific = NULL;
4701 int use_generic = 0;
4702 int offset = p->offset;
4703 void **ptr = slotptr(type, offset);
4704
4705 if (ptr == NULL) {
4706 do {
4707 ++p;
4708 } while (p->offset == offset);
4709 return p;
4710 }
4711 do {
4712 descr = _PyType_Lookup(type, p->name_strobj);
4713 if (descr == NULL)
4714 continue;
4715 if (descr->ob_type == &PyWrapperDescr_Type) {
4716 void **tptr = resolve_slotdups(type, p->name_strobj);
4717 if (tptr == NULL || tptr == ptr)
4718 generic = p->function;
4719 d = (PyWrapperDescrObject *)descr;
4720 if (d->d_base->wrapper == p->wrapper &&
4721 PyType_IsSubtype(type, d->d_type))
4722 {
4723 if (specific == NULL ||
4724 specific == d->d_wrapped)
4725 specific = d->d_wrapped;
4726 else
4727 use_generic = 1;
4728 }
4729 }
Guido van Rossum721f62e2002-08-09 02:14:34 +00004730 else if (descr->ob_type == &PyCFunction_Type &&
4731 PyCFunction_GET_FUNCTION(descr) ==
4732 (PyCFunction)tp_new_wrapper &&
4733 strcmp(p->name, "__new__") == 0)
4734 {
4735 /* The __new__ wrapper is not a wrapper descriptor,
4736 so must be special-cased differently.
4737 If we don't do this, creating an instance will
4738 always use slot_tp_new which will look up
4739 __new__ in the MRO which will call tp_new_wrapper
4740 which will look through the base classes looking
4741 for a static base and call its tp_new (usually
4742 PyType_GenericNew), after performing various
4743 sanity checks and constructing a new argument
4744 list. Cut all that nonsense short -- this speeds
4745 up instance creation tremendously. */
4746 specific = type->tp_new;
4747 /* XXX I'm not 100% sure that there isn't a hole
4748 in this reasoning that requires additional
4749 sanity checks. I'll buy the first person to
4750 point out a bug in this reasoning a beer. */
4751 }
Guido van Rossumc334df52002-04-04 23:44:47 +00004752 else {
4753 use_generic = 1;
4754 generic = p->function;
4755 }
4756 } while ((++p)->offset == offset);
4757 if (specific && !use_generic)
4758 *ptr = specific;
4759 else
4760 *ptr = generic;
4761 return p;
4762}
4763
Guido van Rossum22b13872002-08-06 21:41:44 +00004764static int recurse_down_subclasses(PyTypeObject *type, slotdef **pp,
Jeremy Hylton938ace62002-07-17 16:30:39 +00004765 PyObject *name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004766
Guido van Rossumc334df52002-04-04 23:44:47 +00004767/* In the type, update the slots whose slotdefs are gathered in the pp0 array,
4768 and then do the same for all this type's subtypes. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004769static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004770update_these_slots(PyTypeObject *type, slotdef **pp0, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004771{
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004772 slotdef **pp;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004773
Guido van Rossumc334df52002-04-04 23:44:47 +00004774 for (pp = pp0; *pp; pp++)
4775 update_one_slot(type, *pp);
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004776 return recurse_down_subclasses(type, pp0, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004777}
4778
Guido van Rossumc334df52002-04-04 23:44:47 +00004779/* Update the slots whose slotdefs are gathered in the pp array in all (direct
4780 or indirect) subclasses of type. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004781static int
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004782recurse_down_subclasses(PyTypeObject *type, slotdef **pp, PyObject *name)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004783{
4784 PyTypeObject *subclass;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004785 PyObject *ref, *subclasses, *dict;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004786 int i, n;
4787
4788 subclasses = type->tp_subclasses;
4789 if (subclasses == NULL)
4790 return 0;
4791 assert(PyList_Check(subclasses));
4792 n = PyList_GET_SIZE(subclasses);
4793 for (i = 0; i < n; i++) {
4794 ref = PyList_GET_ITEM(subclasses, i);
4795 assert(PyWeakref_CheckRef(ref));
4796 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
Guido van Rossum59e6c532002-06-14 02:27:07 +00004797 assert(subclass != NULL);
4798 if ((PyObject *)subclass == Py_None)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004799 continue;
4800 assert(PyType_Check(subclass));
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004801 /* Avoid recursing down into unaffected classes */
4802 dict = subclass->tp_dict;
4803 if (dict != NULL && PyDict_Check(dict) &&
4804 PyDict_GetItem(dict, name) != NULL)
4805 continue;
4806 if (update_these_slots(subclass, pp, name) < 0)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004807 return -1;
4808 }
4809 return 0;
4810}
4811
Guido van Rossumc334df52002-04-04 23:44:47 +00004812/* Comparison function for qsort() to compare slotdefs by their offset, and
4813 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004814static int
4815slotdef_cmp(const void *aa, const void *bb)
4816{
4817 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
4818 int c = a->offset - b->offset;
4819 if (c != 0)
4820 return c;
4821 else
4822 return a - b;
4823}
4824
Guido van Rossumc334df52002-04-04 23:44:47 +00004825/* Initialize the slotdefs table by adding interned string objects for the
4826 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004827static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004828init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004829{
4830 slotdef *p;
4831 static int initialized = 0;
4832
4833 if (initialized)
4834 return;
4835 for (p = slotdefs; p->name; p++) {
4836 p->name_strobj = PyString_InternFromString(p->name);
4837 if (!p->name_strobj)
Guido van Rossumc334df52002-04-04 23:44:47 +00004838 Py_FatalError("Out of memory interning slotdef names");
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004839 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004840 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
4841 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004842 initialized = 1;
4843}
4844
Guido van Rossumc334df52002-04-04 23:44:47 +00004845/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004846static int
4847update_slot(PyTypeObject *type, PyObject *name)
4848{
Guido van Rossumc334df52002-04-04 23:44:47 +00004849 slotdef *ptrs[MAX_EQUIV];
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004850 slotdef *p;
4851 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004852 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004853
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004854 init_slotdefs();
4855 pp = ptrs;
4856 for (p = slotdefs; p->name; p++) {
4857 /* XXX assume name is interned! */
4858 if (p->name_strobj == name)
4859 *pp++ = p;
4860 }
4861 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004862 for (pp = ptrs; *pp; pp++) {
4863 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004864 offset = p->offset;
4865 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004866 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004867 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004868 }
Guido van Rossumc334df52002-04-04 23:44:47 +00004869 if (ptrs[0] == NULL)
4870 return 0; /* Not an attribute that affects any slots */
Guido van Rossumb85a8b72001-10-16 17:00:48 +00004871 return update_these_slots(type, ptrs, name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00004872}
4873
Guido van Rossumc334df52002-04-04 23:44:47 +00004874/* Store the proper functions in the slot dispatches at class (type)
4875 definition time, based upon which operations the class overrides in its
4876 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004877static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004878fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004879{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004880 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004881
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004882 init_slotdefs();
Guido van Rossumc334df52002-04-04 23:44:47 +00004883 for (p = slotdefs; p->name; )
4884 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004885}
Guido van Rossum705f0f52001-08-24 16:47:00 +00004886
Michael W. Hudson98bbc492002-11-26 14:47:27 +00004887static void
4888update_all_slots(PyTypeObject* type)
4889{
4890 slotdef *p;
4891
4892 init_slotdefs();
4893 for (p = slotdefs; p->name; p++) {
4894 /* update_slot returns int but can't actually fail */
4895 update_slot(type, p->name_strobj);
4896 }
4897}
4898
Guido van Rossum6d204072001-10-21 00:44:31 +00004899/* This function is called by PyType_Ready() to populate the type's
4900 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00004901 function slot (like tp_repr) that's defined in the type, one or more
4902 corresponding descriptors are added in the type's tp_dict dictionary
4903 under the appropriate name (like __repr__). Some function slots
4904 cause more than one descriptor to be added (for example, the nb_add
4905 slot adds both __add__ and __radd__ descriptors) and some function
4906 slots compete for the same descriptor (for example both sq_item and
4907 mp_subscript generate a __getitem__ descriptor).
4908
4909 In the latter case, the first slotdef entry encoutered wins. Since
4910 slotdef entries are sorted by the offset of the slot in the etype
4911 struct, this gives us some control over disambiguating between
4912 competing slots: the members of struct etype are listed from most
4913 general to least general, so the most general slot is preferred. In
4914 particular, because as_mapping comes before as_sequence, for a type
4915 that defines both mp_subscript and sq_item, mp_subscript wins.
4916
4917 This only adds new descriptors and doesn't overwrite entries in
4918 tp_dict that were previously defined. The descriptors contain a
4919 reference to the C function they must call, so that it's safe if they
4920 are copied into a subtype's __dict__ and the subtype has a different
4921 C function in its slot -- calling the method defined by the
4922 descriptor will call the C function that was used to create it,
4923 rather than the C function present in the slot when it is called.
4924 (This is important because a subtype may have a C function in the
4925 slot that calls the method from the dictionary, and we want to avoid
4926 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00004927
4928static int
4929add_operators(PyTypeObject *type)
4930{
4931 PyObject *dict = type->tp_dict;
4932 slotdef *p;
4933 PyObject *descr;
4934 void **ptr;
4935
4936 init_slotdefs();
4937 for (p = slotdefs; p->name; p++) {
4938 if (p->wrapper == NULL)
4939 continue;
4940 ptr = slotptr(type, p->offset);
4941 if (!ptr || !*ptr)
4942 continue;
4943 if (PyDict_GetItem(dict, p->name_strobj))
4944 continue;
4945 descr = PyDescr_NewWrapper(type, p, *ptr);
4946 if (descr == NULL)
4947 return -1;
4948 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
4949 return -1;
4950 Py_DECREF(descr);
4951 }
4952 if (type->tp_new != NULL) {
4953 if (add_tp_new_wrapper(type) < 0)
4954 return -1;
4955 }
4956 return 0;
4957}
4958
Guido van Rossum705f0f52001-08-24 16:47:00 +00004959
4960/* Cooperative 'super' */
4961
4962typedef struct {
4963 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00004964 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00004965 PyObject *obj;
4966} superobject;
4967
Guido van Rossum6f799372001-09-20 20:46:19 +00004968static PyMemberDef super_members[] = {
4969 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
4970 "the class invoking super()"},
4971 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
4972 "the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004973 {0}
4974};
4975
Guido van Rossum705f0f52001-08-24 16:47:00 +00004976static void
4977super_dealloc(PyObject *self)
4978{
4979 superobject *su = (superobject *)self;
4980
Guido van Rossum048eb752001-10-02 21:24:57 +00004981 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00004982 Py_XDECREF(su->obj);
4983 Py_XDECREF(su->type);
4984 self->ob_type->tp_free(self);
4985}
4986
4987static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004988super_repr(PyObject *self)
4989{
4990 superobject *su = (superobject *)self;
4991
4992 if (su->obj)
4993 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00004994 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00004995 su->type ? su->type->tp_name : "NULL",
4996 su->obj->ob_type->tp_name);
4997 else
4998 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00004999 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005000 su->type ? su->type->tp_name : "NULL");
5001}
5002
5003static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00005004super_getattro(PyObject *self, PyObject *name)
5005{
5006 superobject *su = (superobject *)self;
5007
5008 if (su->obj != NULL) {
Tim Petersa91e9642001-11-14 23:32:33 +00005009 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005010 PyTypeObject *starttype;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005011 descrgetfunc f;
5012 int i, n;
5013
Guido van Rossum155db9a2002-04-02 17:53:47 +00005014 starttype = su->obj->ob_type;
5015 mro = starttype->tp_mro;
5016
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005017 if (mro == NULL)
5018 n = 0;
5019 else {
5020 assert(PyTuple_Check(mro));
5021 n = PyTuple_GET_SIZE(mro);
5022 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005023 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00005024 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00005025 break;
5026 }
Guido van Rossume705ef12001-08-29 15:47:06 +00005027 if (i >= n && PyType_Check(su->obj)) {
Guido van Rossum155db9a2002-04-02 17:53:47 +00005028 starttype = (PyTypeObject *)(su->obj);
5029 mro = starttype->tp_mro;
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005030 if (mro == NULL)
5031 n = 0;
5032 else {
5033 assert(PyTuple_Check(mro));
5034 n = PyTuple_GET_SIZE(mro);
5035 }
Guido van Rossume705ef12001-08-29 15:47:06 +00005036 for (i = 0; i < n; i++) {
5037 if ((PyObject *)(su->type) ==
5038 PyTuple_GET_ITEM(mro, i))
5039 break;
5040 }
Guido van Rossume705ef12001-08-29 15:47:06 +00005041 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005042 i++;
5043 res = NULL;
5044 for (; i < n; i++) {
5045 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00005046 if (PyType_Check(tmp))
5047 dict = ((PyTypeObject *)tmp)->tp_dict;
5048 else if (PyClass_Check(tmp))
5049 dict = ((PyClassObject *)tmp)->cl_dict;
5050 else
5051 continue;
5052 res = PyDict_GetItem(dict, name);
Guido van Rossum5b443c62001-12-03 15:38:28 +00005053 if (res != NULL && !PyDescr_IsData(res)) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00005054 Py_INCREF(res);
5055 f = res->ob_type->tp_descr_get;
5056 if (f != NULL) {
Guido van Rossumd4641072002-04-03 02:13:37 +00005057 tmp = f(res, su->obj,
5058 (PyObject *)starttype);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005059 Py_DECREF(res);
5060 res = tmp;
5061 }
5062 return res;
5063 }
5064 }
5065 }
5066 return PyObject_GenericGetAttr(self, name);
5067}
5068
Guido van Rossum5b443c62001-12-03 15:38:28 +00005069static int
5070supercheck(PyTypeObject *type, PyObject *obj)
5071{
5072 if (!PyType_IsSubtype(obj->ob_type, type) &&
5073 !(PyType_Check(obj) &&
5074 PyType_IsSubtype((PyTypeObject *)obj, type))) {
5075 PyErr_SetString(PyExc_TypeError,
5076 "super(type, obj): "
5077 "obj must be an instance or subtype of type");
5078 return -1;
5079 }
5080 else
5081 return 0;
5082}
5083
Guido van Rossum705f0f52001-08-24 16:47:00 +00005084static PyObject *
5085super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5086{
5087 superobject *su = (superobject *)self;
5088 superobject *new;
5089
5090 if (obj == NULL || obj == Py_None || su->obj != NULL) {
5091 /* Not binding to an object, or already bound */
5092 Py_INCREF(self);
5093 return self;
5094 }
Guido van Rossum5b443c62001-12-03 15:38:28 +00005095 if (su->ob_type != &PySuper_Type)
5096 /* If su is an instance of a subclass of super,
5097 call its type */
5098 return PyObject_CallFunction((PyObject *)su->ob_type,
5099 "OO", su->type, obj);
5100 else {
5101 /* Inline the common case */
5102 if (supercheck(su->type, obj) < 0)
5103 return NULL;
5104 new = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
5105 NULL, NULL);
5106 if (new == NULL)
5107 return NULL;
5108 Py_INCREF(su->type);
5109 Py_INCREF(obj);
5110 new->type = su->type;
5111 new->obj = obj;
5112 return (PyObject *)new;
5113 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005114}
5115
5116static int
5117super_init(PyObject *self, PyObject *args, PyObject *kwds)
5118{
5119 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00005120 PyTypeObject *type;
5121 PyObject *obj = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005122
5123 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
5124 return -1;
5125 if (obj == Py_None)
5126 obj = NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005127 if (obj != NULL && supercheck(type, obj) < 0)
Guido van Rossum705f0f52001-08-24 16:47:00 +00005128 return -1;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005129 Py_INCREF(type);
5130 Py_XINCREF(obj);
5131 su->type = type;
5132 su->obj = obj;
5133 return 0;
5134}
5135
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005136PyDoc_STRVAR(super_doc,
Guido van Rossum705f0f52001-08-24 16:47:00 +00005137"super(type) -> unbound super object\n"
5138"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00005139"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00005140"Typical use to call a cooperative superclass method:\n"
5141"class C(B):\n"
5142" def meth(self, arg):\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005143" super(C, self).meth(arg)");
Guido van Rossum705f0f52001-08-24 16:47:00 +00005144
Guido van Rossum048eb752001-10-02 21:24:57 +00005145static int
5146super_traverse(PyObject *self, visitproc visit, void *arg)
5147{
5148 superobject *su = (superobject *)self;
5149 int err;
5150
5151#define VISIT(SLOT) \
5152 if (SLOT) { \
5153 err = visit((PyObject *)(SLOT), arg); \
5154 if (err) \
5155 return err; \
5156 }
5157
5158 VISIT(su->obj);
5159 VISIT(su->type);
5160
5161#undef VISIT
5162
5163 return 0;
5164}
5165
Guido van Rossum705f0f52001-08-24 16:47:00 +00005166PyTypeObject PySuper_Type = {
5167 PyObject_HEAD_INIT(&PyType_Type)
5168 0, /* ob_size */
5169 "super", /* tp_name */
5170 sizeof(superobject), /* tp_basicsize */
5171 0, /* tp_itemsize */
5172 /* methods */
5173 super_dealloc, /* tp_dealloc */
5174 0, /* tp_print */
5175 0, /* tp_getattr */
5176 0, /* tp_setattr */
5177 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005178 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005179 0, /* tp_as_number */
5180 0, /* tp_as_sequence */
5181 0, /* tp_as_mapping */
5182 0, /* tp_hash */
5183 0, /* tp_call */
5184 0, /* tp_str */
5185 super_getattro, /* tp_getattro */
5186 0, /* tp_setattro */
5187 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00005188 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
5189 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005190 super_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00005191 super_traverse, /* tp_traverse */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005192 0, /* tp_clear */
5193 0, /* tp_richcompare */
5194 0, /* tp_weaklistoffset */
5195 0, /* tp_iter */
5196 0, /* tp_iternext */
5197 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005198 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005199 0, /* tp_getset */
5200 0, /* tp_base */
5201 0, /* tp_dict */
5202 super_descr_get, /* tp_descr_get */
5203 0, /* tp_descr_set */
5204 0, /* tp_dictoffset */
5205 super_init, /* tp_init */
5206 PyType_GenericAlloc, /* tp_alloc */
5207 PyType_GenericNew, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00005208 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005209};